diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 743a38ea83..256f5b66f5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,11 @@ on: pull_request: types: [opened, synchronize, reopened, edited] workflow_dispatch: + inputs: + flyway_base_sha: + description: Full immutable commit SHA of the receiving parent to compare Flyway history against + required: true + type: string run-name: CI — Validation ${{ github.event_name == 'pull_request' && format('pr-{0} base-{1} head-{2}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha) || github.ref_name }} @@ -553,6 +558,27 @@ jobs: - name: ⬇️ Checkout Code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - name: Fetch exact Flyway parent + env: + FLYWAY_BASE_SHA: ${{ github.event_name == 'workflow_dispatch' && inputs.flyway_base_sha || github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} + FLYWAY_EVENT_NAME: ${{ github.event_name }} + run: | + if [[ "$FLYWAY_BASE_SHA" == "0000000000000000000000000000000000000000" && "$FLYWAY_EVENT_NAME" != "workflow_dispatch" ]]; then + exit 0 + fi + if [[ ! "$FLYWAY_BASE_SHA" =~ ^[[:xdigit:]]{40}$ || "$FLYWAY_BASE_SHA" == "0000000000000000000000000000000000000000" ]]; then + echo "Flyway parent requires a full nonzero immutable 40-character SHA" >&2 + exit 1 + fi + if ! git cat-file -e "${FLYWAY_BASE_SHA}^{commit}" 2>/dev/null; then + git fetch --no-tags --depth=1 origin "$FLYWAY_BASE_SHA" + fi + resolved_sha="$(git rev-parse --verify "${FLYWAY_BASE_SHA}^{commit}")" + if [[ "${resolved_sha,,}" != "${FLYWAY_BASE_SHA,,}" ]]; then + echo "Flyway base SHA did not resolve to the requested commit" >&2 + exit 1 + fi + - name: ⚙️ Set Up Java uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6 with: @@ -573,6 +599,8 @@ jobs: cache-read-only: false - name: 🧪 Check Flyway Migration Versions + env: + FIREMUD_FLYWAY_BASE_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.flyway_base_sha || github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} run: ./gradlew checkFlywayVersions grpc-transport-config-sanity-checks: diff --git a/build.gradle.kts b/build.gradle.kts index a09a2c7b6c..13ca387277 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -411,8 +411,12 @@ tasks.register("linkCheck") { tasks.register("checkFlywayVersions") { group = "verification" - description = "Checks service Flyway migrations for duplicate or out-of-order versions." - commandLine("bash", "dev-tools/validation/check-flyway-versions.sh") + description = "Checks combined Flyway migration versions and additions against an immutable parent when available." + val baseRef = providers.gradleProperty("flywayBaseRef").orNull + commandLine( + listOf("bash", "dev-tools/validation/check-flyway-versions.sh") + + if (baseRef != null) listOf("--base-ref", baseRef) else emptyList() + ) } tasks.register("checkGrpcTransportConfig") { diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index fe7306cdbf..3610bd373d 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -54,6 +54,8 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +Passive original StartSession admission/activation protection storage adds no callable acquisition, read or settlement API. SQL terminal integrity is not authenticated Game Session/World terminal authority, and no protection grants runtime admission or activation. The [Account storage consequence](./runtime-and-data.md#original-startsession-source-protection-storage) and [focused proof tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) retain the exact boundary and open producer/consumer gates. + The initial private gameplay LOGIN owner, signer, registry, and response-recovery code is present as unregistered Account source, with focused proof sources. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. This does not add or activate an API, proto method, or Spring composition; the source has no caller-selected profile or property override. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact proof scope; deployed ACL/TLS, signer-key custody, caller authentication, gameplay admission, and runtime activation remain unproved. Account UUID generation currently has three established provenances: `ACCOUNT_REPOSITORY_INSERT` uses `AccountRepository` and `UUID.randomUUID()`; `ACCOUNT_V29_MIGRATION` uses `gen_random_uuid()` for retained rows; and `ACCOUNT_DATABASE_INSERT` uses the `gen_random_uuid()` database default. These current producer outputs are RFC 4122 version 4 UUIDs. This records generator provenance and does not claim that database constraints reject custom UUID versions. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fa969a4388..a71a75a8c2 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The additive [V1003 source-protection storage](../../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql) provides passive original StartSession admission and activation protection relations and source-writer exclusions. It adds no registered producer or transport. Qualification and remaining composition gates are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). + Account has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. It adds no endpoint or runtime registration; deployed ACL/TLS, signer-key custody, caller authentication, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. Account's unregistered original-ACK storage seam requires PostgreSQL 18 for fresh operations: the original executor performs a writable SERIALIZABLE physical COMMIT on its enlisted connection and returns an opaque acknowledgement only after observing the database clock before unchanged expiry; a separate transaction commits the exact receipt. Receiving V146 changes only the fresh receipt-insert guard, preserving the donor V122 SQL unchanged as receiving V144. Its historical durable reader remains PostgreSQL 16-only, so lost-acknowledgement recovery and retained-receipt retries remain denied on PostgreSQL 18. This storage evidence does not authenticate a caller, establish current Account ownership or admission, authorize gameplay, or register runtime behavior. Migration provenance and pending receiving proof are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). @@ -329,3 +331,19 @@ Account owns the sole supported v1 Stripe integration for FireMUD hosting-plan b This service sends verification and password reset emails using a configured SMTP provider. Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when a known-account post-commit SMTP send throws; those exceptions are caught and logged, while unknown requests create no token and schedule no email. **Current gap:** these sends still run synchronously after commit, so SMTP latency remains a timing oracle; durable asynchronous delivery is absent. Focused service tests prove exception containment, not timing resistance, HTTP-level timing parity, or durable delivery, so this is not full account-enumeration resistance. Public email-verification initiation no longer accepts a numeric account selector, while the internal gRPC method remains account-ID based. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). The configured default verification URL is a `GET /auth/verify-email` link while Account exposes verification as `POST /auth/verify-email`; the default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). The shipped defaults therefore do not route users to the canonical POST APIs ([Account API Contracts](./api-contracts.md#rest-apis)); deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live. + +## Original StartSession Source-Protection Storage + +Account retains admission and activation protection separately from the original World participation. Each protection stores the complete original tuple and redemption projection, capture, ordered source-child evidence, actual Game Session owner mutation/attempt/fence, and unchanged original lease expiry. Admission additionally binds the complete World admission hold; activation binds the canonical World PREPARING evidence and its separate activation request. Database checks validate the nested original issuance-operation identity rather than accepting a matching projection hash alone. Identity/fence allocation, exact current lookup and append-only guards preserve the first protection without renewing authority. + +The existing Account source-lock order remains canonical: source-key locks precede protection-row locks, and NOWAIT refuses a reversed or unavailable acquisition. Pending admission or activation blocks the existing source-hold, source-change and hosted-terms disclosure paths until the distinct protection has its exact immutable terminal settlement. Expiry, World receiving settlement, absence and an asserted outcome cannot release another protection. Settlement stores the complete original protection and exact terminal binding; these SQL checks validate integrity and do not authenticate the terminal producer. The owner obligations remain defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). + +Forward [V1004 lifecycle integrity](../../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql) applies one complete closed lifecycle validator to PREPARING evidence before protection acquisition and ACTIVE evidence during COMMITTED settlement. Settlement also binds the retained PREPARING request and immutable owner values; acquisition cannot retain a malformed carrier which its matching COMMITTED result must reject. Malformed or ambiguous lifecycle carriers retain the pending source-writer exclusion; exact ABORTED terminal handling remains separate. This storage validation does not authenticate World or activate the source path. Current proof and limits belong in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). + +Forward [V1004.1](../../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql) also rejects a COMMITTED ACTIVE lifecycle whose `lifecycleEpoch` or `rowVersion` is lower than the retained PREPARING counter. Equal or increased counters remain valid; malformed values and other lifecycle binding checks keep V1004's behavior. This remains Account storage integrity validation and does not authenticate World or activate the source path. + +Forward [V1004.2](../../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql) runs V1004's existing closed PREPARING validator on retained protection evidence before V1004.1's counter comparisons. Thus missing or malformed retained counters cannot bypass monotonicity through SQL `NULL` comparison behavior. It also requires the activation request UUID text at acquisition to equal PostgreSQL's canonical UUID text, rejecting alternate spellings before protection and source-child rows commit. These are storage-integrity checks; they do not backfill retained rows, authenticate World, or activate the source path. + +Forward [V1004.3](../../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) requires all four Base64 carriers in the Account activation request to match the canonical encoding of their decoded tuple, projection, launch-read, and PREPARING bytes before protection acquisition. This prevents accepted whitespace spellings from being retained in an immutable request that later settlement must compare. It changes only the existing acquisition guard and does not backfill rows, authenticate World, or activate the source path. Current proof and limits are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). + +V1003 preserves canonical predecessor SQL and retained owner rows; it never backfills protection, adopts missing historical evidence, fabricates owner proof or registers runtime authority. Its scoped PostgreSQL fixtures explicitly stipulate upstream capture/redemption/World rows with upstream producer triggers disabled while leaving the protection and source-writer guards under test enabled. Such execution establishes storage integrity, exclusion and retained-history behavior only. Genuine current-owner acquisition, authenticated terminal reads/settlement, continuously protected admission, activation and the separate selected-owner source-reservation obligation remain unproved. diff --git a/design/architecture/microservices/entity-management-service/README.md b/design/architecture/microservices/entity-management-service/README.md index ee6c681fd2..446abd5e8e 100644 --- a/design/architecture/microservices/entity-management-service/README.md +++ b/design/architecture/microservices/entity-management-service/README.md @@ -6,7 +6,9 @@ Handles player characters, NPCs, runtime actor identity, items, and all inventor ## Implementation Status -Persisted rows and realm-aware listing exist, but synthetic-ID paths, fixed RPG columns, published entry-policy/descriptor/template resolution, policy-specific roster handling, namespace-idempotent auto-provision, and fork-local copy proof remain gaps. +Entity V1003–V1010 prepares opaque actor UUIDs, quarantine metadata, namespace/scope integrity, and assignment/receipt/roster storage while retaining legacy values. Exact canonical repository readers, including `ActorIdentityRepository` and `CharacterRepository`, are registered Spring beans. The assignment, receipt, and roster service compositions remain manually composed and unregistered, with no authenticated clients or gRPC handlers. Existing legacy reads, roster listing, updates, cache access, scoped consumers, condition expiry, and cleanup retain develop behavior; this preparation does not enforce runtime quarantine or replace gameplay admission. Authenticated owner provenance, the real Game Session caller and execution replacement, and production activation remain unproved. Focused storage and unchanged legacy player-flow qualification is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); [Entity API Contracts](./api-contracts.md#implementation-status) owns the detailed source and wire contract. + +The focused SQL-isolation fixtures may insert owner-resolved rows to test exact tenant/account/namespace/scope predicates; those rows are fixture evidence only and do not prove an Account or Game Design owner supplied that provenance at runtime. Existing `shared-live`, `instance:`, numeric Account/tenant IDs, names, caller checksums, and Game Session pointers never fill missing UUID provenance. World-owned `character_location` and `npc_location` tables, together with their authoritative movement, occupancy, and read paths, are target-only. They are absent from the current schema and runtime; current room topology or session bindings do not establish location authority, and Entity Management must not persist a competing location table, field, or cache authority. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index bf12d23d73..8d5e80bed4 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,9 +6,11 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status -The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. Its two methods define pre-admission, non-admitting reads restricted to `PRESEEDED_ONLY`; any other policy value is non-authorizing and returns `FAILED_PRECONDITION`. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. +Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has no runtime handler, authenticated client, peer interceptor, or bean registration in this boundary. Legacy adapters and consumers retain develop behavior. The qualified immutable donor contains the complete migration tail; focused qualification of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required. -The `ReadSelectedPreseededAssignment` `intent_digest` is the bare lowercase 64-hex SHA-256 of Entity's immutable assignment-intent preimage, with no `sha256:` prefix. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. The operation and account values come from `PreseededActorAssignmentRequest.assignmentUuid` and `.canonicalAccountUuid`, corresponding to `assignment_uuid` in the selected-assignment response and `canonical_account_uuid` on its request and response. `actorKind` and `displayName` come from the original `request.corePayload`, not the currently selected roster actor's `actor_kind` or `display_name`. Target values come from the independently resolved `PreseededActorAssignmentOwnerEvidence` used to create the persisted assignment receipt; their corresponding `CanonicalGameplayRosterTarget` wire fields are `tenant_uuid`, `realm_uuid`, `world_slug`, `realm_slug`, `game_instance_uuid`, `catalog_revision`, `canonical_version_uuid`, `published_policy_digest`, `playable_state_namespace_uuid`, `published_release_bundle_ref`, `playable_state_scope`, and `entry_policy`. In particular, internal `gameInstanceId` is a bounded opaque string; the `game_instance_uuid` wire field name does not add UUID parsing or normalization to its digest value. The internal `frozenPolicyDigest` is the same persisted value represented by `CanonicalGameplayRosterTarget.published_policy_digest`; it is bare lowercase 64-hex without a `sha256:` prefix and is not separately derived. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUID values use canonical `UUID.toString()` form, counters use base-10 decimal text, and `actorKind`, `playableStateScope`, and `entryPolicy` use only the short strings listed above. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest returned by the selected-assignment read is the original persisted receipt digest, not recomputed from that read's request, the current roster, or current owner/Account observations. See the [Entity proto](../../../../protos/entity-management/v1/entity_management_service.proto) for the wire field names. +The target read semantics are: any policy other than `PRESEEDED_ONLY` is non-authorizing and returns `FAILED_PRECONDITION`; `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. PRESEEDED_ONLY actor display names are nonblank, trimmed, control-free text bounded to 100 Unicode code points, matching the accepted assignment core. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. + +The `ReadSelectedPreseededAssignment` `intent_digest` is the bare lowercase 64-hex SHA-256 of Entity's immutable assignment-intent preimage, with no `sha256:` prefix. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. The operation and account values come from `PreseededActorAssignmentRequest.assignmentUuid` and `.canonicalAccountUuid`, corresponding to `assignment_uuid` in the selected-assignment response and `canonical_account_uuid` on its request and response. `actorKind` and `displayName` come from the original `request.corePayload`, not the currently selected roster actor's `actor_kind` or `display_name`. Target values come from the independently resolved `PreseededActorAssignmentOwnerEvidence` used to create the persisted assignment receipt; their corresponding `CanonicalGameplayRosterTarget` wire fields are `tenant_uuid`, `realm_uuid`, `world_slug`, `realm_slug`, `game_instance_uuid`, `catalog_revision`, `canonical_version_uuid`, `published_policy_digest`, `playable_state_namespace_uuid`, `published_release_bundle_ref`, `playable_state_scope`, and `entry_policy`. In particular, internal `gameInstanceId` is a bounded opaque string; the `game_instance_uuid` wire field name does not add UUID parsing or normalization to its digest value. At the canonical roster bridge, the owner supplies `game_instance_uuid` as already canonical, non-nil UUID text under the shared [Identifier Format Conventions](../../system-architecture-identifier-glossary.md#identifier-format-conventions). That boundary contract does not change the generic assignment digest path: it hashes the exact opaque owner-supplied text and does not infer aliases, parse, or normalize it. The internal `frozenPolicyDigest` is the same persisted value represented by `CanonicalGameplayRosterTarget.published_policy_digest`; it is bare lowercase 64-hex without a `sha256:` prefix and is not separately derived. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUID values use canonical `UUID.toString()` form, counters use base-10 decimal text, and `actorKind`, `playableStateScope`, and `entryPolicy` use only the short strings listed above. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest returned by the selected-assignment read is the original persisted receipt digest, not recomputed from that read's request, the current roster, or current owner/Account observations. See the [Entity proto](../../../../protos/entity-management/v1/entity_management_service.proto) for the wire field names. The live crafting REST surface is runtime-reachable but is not a tenant-authorized gameplay or design-time boundary: `POST /crafting/recipes` accepts a caller-supplied `tenantId` in `CraftingRecipeDto`, and `GET /crafting/recipes/{id}` accepts only a globally-shaped recipe id. The ping-only authoritative OpenAPI document declares root `security: []`; the crafting handlers and schemas are omitted from that contract. The deployed Entity HTTP interceptor currently requires only an `AUTHENTICATED` bearer (crafting is not in the public-route list), while the controllers do not apply `SessionContext` tenant authorization and the service/repository do not bind either operation to the authenticated caller. The create path can therefore persist a caller-selected tenant (and an existing DTO id can update by id), while the read path performs an ID-only recipe lookup. `CraftingControllerTest` and `CraftingServiceImplTest` cover request/recipe validation and happy-path persistence only; they do not prove unauthenticated denial, tenant-qualified lookup/update, or cross-tenant item ownership. The handlers must remain unsupported/fenced or gain the target caller-bound authorization before they can be treated as a supported route. @@ -43,7 +45,8 @@ curl http://localhost:8080/ping ## gRPC - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `entity_management_service.proto`. -- `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – separate target wire contract for the `PRESEEDED_ONLY` pre-admission roster branch. Both carry `shared.v1.PlayerExecutionContext`; its scope string is exactly `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The first binds the authenticated account/session/request and prospective tenant/realm/namespace/scope/instance target, while the second additionally binds `context.character_id` to the selected UUID and exact roster snapshot. The selection response echoes discovery bindings only; it mints no assignment receipt or admission proof, which remain with the owning downstream write/readback. The exact same-namespace Game Session workload mTLS identity is allowlisted. These reads are not actor admission or a session-binding shortcut, and their proto has no handler or activation yet. + +- `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – target `PRESEEDED_ONLY` pre-admission wire contract described in [Implementation Status](#implementation-status). Source models and manually composed services are present; authenticated transport handlers and caller registration are not. The result is discovery evidence, not actor admission or a session-binding shortcut. - `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Current behavior: the scalar-only request validates tenant, account, and scope, then Entity returns an application `FAILED_PRECONDITION` before `CharacterService` allocation because the request cannot carry the authenticated owner proof and durable operation binding. Target behavior remains Entity-owned allocation and persistence of a primary controllable actor after the caller has passed Account membership/grant/realm admission. The target request carries the resolved `{accountId, tenantId, worldSlug, realmSlug}`, stable `playableStateNamespaceId`, the `playableStateScope` supplied only as authoritative realm-snapshot/attestation evidence, active `gameInstanceId`, explicit `entryPolicy=PLAYER_CREATED`, exact published descriptor identity/version, player creation input, and proof of the catalog/admission-pointer snapshot. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks the policy against the canonical snapshot and the applicable descriptor identity/version. It also carries caller-stable `createCharacterRequestId` and canonical `mutationDigest`; Entity recomputes the digest over the immutable trusted target, `entryPolicy`, exact descriptor/version, and creation input. The durable operation guard key is `{tenantId, playableStateNamespaceId, accountId, createCharacterRequestId}`. Within one local transaction, Entity admits and locks that guard plus digest, serializes the `PLAYER_CREATED` zero-roster boundary on `{tenantId, playableStateNamespaceId, accountId}`, and rereads the roster against the unchanged policy and descriptor/version before allocation. Only a still-empty roster may allocate; concurrent distinct request identities cannot both cross a stale zero-roster observation. Entity then atomically persists the allocated `{accountId, tenantId, playableStateNamespaceId, characterId}` association and replayable response. The same guard and digest exact-replay the original response; the same guard with a different digest returns `IDEMPOTENCY_CONFLICT` before allocation. Callers cannot choose or derive `playableStateScope`; Entity must reject caller-derived evidence and validate the exact immutable namespace/scope pair. A scope change under one namespace is rejected and never creates a second or split actor record. Entity allocates `characterId` only after the operation guard, validates the namespace/scope and active-instance fence, and never derives identity from account/name/hash or delegates character ownership to Account. Durable persistence/keying remains `{tenantId, playableStateNamespaceId, characterId}`; `playableStateScope` remains separately validated immutable routing/authorization evidence, `gameInstanceId` is only the replaceable active-runtime fence, and neither is a durable character-identity dimension. Entity Management does not expose a direct player REST route. This target boundary remains an implementation/proof gap; current implementation proves denial only. - `UpdateEntity(UpdateEntityRequest) returns (UpdateEntityResponse)` – updates mutable character state for the requested `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, characterId}` target. `playableStateScope` must be the authoritative realm-snapshot/attestation result; callers cannot choose or derive it, and Entity validates the exact immutable namespace/scope pair before mutation. A caller-selected or changed scope, missing/mismatched namespace or scope, stale snapshot, caller-asserted instance, or global `characterId` is rejected rather than updating or splitting records. Target state also requires a fresh, server-resolved active-instance authorization fence for that exact namespace/scope and instance, checked atomically immediately before mutation. The current request path does not yet carry and prove the complete fresh fence, so it remains an implementation/proof gap and must not be treated as target enforcement. - `QueryInventory(QueryInventoryRequest) returns (QueryInventoryResponse)` – the current response is an unpaged repeated `InventoryItem items[]` projection. The live handler emits `item_id`, `item_name`, `item_description`, and `quantity`, and conditionally emits `container_instance_id`, `item_instance_id`, and `visible_ref` when those values are present. This projection does not establish complete instance-aware identity or stack/concurrency safety: rich pagination, complete holder-local stack uniqueness, find-then-create concurrency, and explicit-family duplicate handling remain target/proof gaps documented in [Runtime and Data](./runtime-and-data.md#implementation-status). diff --git a/design/architecture/microservices/entity-management-service/operations.md b/design/architecture/microservices/entity-management-service/operations.md index 8e18a05c8f..25178aa707 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -10,6 +10,76 @@ The current replacement-validation path is also narrower than the target contrac At the live enqueue boundary, the current Automation implementation expands each enabled command node over its target entity ids, assigns `commandOrdinal`, and enforces configured bounded per-run and per-entity fan-out with atomic rejection before admission when a bound is exceeded. The current path still does not prove complete durable child/target identity or end-to-end fan-out/replay semantics; the target Command-Handoff Identity and its atomic rejection distinction remain required. `automationDispatchId` alone is not a dedupe key; use the complete Command-Handoff Identity for the target contract. +The actor-identity and assignment/roster changes in this preparation are storage and unregistered source only. Existing runtime consumers, expiry, and cleanup retain develop behavior; no new quarantine hold or authenticated roster handler is active. Follow [Entity Runtime and Data](./runtime-and-data.md#implementation-status) for this boundary and [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof) for pending proof. + +## V1004 Concurrent Index Migration Recovery + +Entity V1004 creates `ux_characters_character_uuid_idx` concurrently, then `idx_characters_owner_resolved_roster` concurrently, and finally attaches the first index as the `ux_characters_character_uuid` unique constraint. Follow the [database migration contract](../../system-architecture-database-migrations.md) for migration activation and roll-forward. These local recovery steps preserve all character rows and require writer admission to remain closed and quiesced throughout inspection and recovery. + +Use the deployed Entity `SERVICE_SCHEMA` value, confirm the selected schema, and inspect the exact index definitions, PostgreSQL validity/readiness flags, and any attached constraint before taking action. In `psql`, set `service_schema` to that deployed schema and run: + +```sql +SET search_path TO :"service_schema"; + +SELECT current_schema() AS selected_schema, current_schemas(false) AS search_path_schemas; + +SELECT ns.nspname AS schema_name, + idx.relname AS index_name, + pg_get_indexdef(idx.oid) AS index_definition, + pi.indisvalid, + pi.indisready, + pi.indisunique, + con.conname AS attached_constraint +FROM pg_class AS idx +JOIN pg_namespace AS ns ON ns.oid = idx.relnamespace +JOIN pg_index AS pi ON pi.indexrelid = idx.oid +LEFT JOIN pg_constraint AS con ON con.conindid = idx.oid +WHERE ns.nspname = :'service_schema' + AND idx.relname IN ( + 'ux_characters_character_uuid_idx', + 'idx_characters_owner_resolved_roster', + 'ux_characters_character_uuid' + ) +ORDER BY idx.relname; +``` + +Before a concurrent index build or drop, inspect long-running transactions and blockers in the target database; concurrent index operations can wait on old snapshots and other transactions. This read-only query identifies long-running active transactions and sessions blocking or blocked by another backend: + +```sql +SELECT activity.pid, + activity.usename, + activity.state, + now() - activity.xact_start AS transaction_age, + now() - activity.query_start AS query_age, + activity.wait_event_type, + activity.wait_event, + pg_blocking_pids(activity.pid) AS blocking_pids, + activity.query +FROM pg_stat_activity AS activity +WHERE activity.datname = current_database() + AND activity.pid <> pg_backend_pid() + AND (activity.state <> 'idle' OR cardinality(pg_blocking_pids(activity.pid)) > 0) +ORDER BY activity.xact_start NULLS LAST, activity.query_start NULLS LAST; +``` + +An invalid index may be removed only after confirming it is one of these exact V1004 indexes, is unattached to a constraint, and its definition matches the expected V1004 object. Use the deployed schema explicitly. Run only the statement for the specific index confirmed invalid and unattached; each statement must run outside a transaction. + +Only if inspection confirms `ux_characters_character_uuid_idx` is invalid, unattached, and matches the expected V1004 definition: + +```sql +DROP INDEX CONCURRENTLY IF EXISTS :"service_schema".ux_characters_character_uuid_idx; +``` + +Only if inspection independently confirms `idx_characters_owner_resolved_roster` is invalid, unattached, and matches the expected V1004 definition: + +```sql +DROP INDEX CONCURRENTLY IF EXISTS :"service_schema".idx_characters_owner_resolved_roster; +``` + +Drop only the specific invalid, unattached index confirmed by inspection, then verify it is absent. Do not drop a valid index or the attached `ux_characters_character_uuid` constraint as generic cleanup. A blind Flyway repair-and-migrate is unsafe when an earlier V1004 statement succeeded: retrying the whole file may collide with a surviving valid index, and attaching the unique index renames it to the constraint's final name. If either expected index is valid, the final constraint exists, or the observed state is otherwise mixed, stop automatic retry and use an operator-reviewed, phase-specific roll-forward plan that accounts for Flyway history and the exact surviving definitions. Do not delete or rewrite character data to make the migration proceed. + +Dropping invalid, unattached indexes does not remove the failed V1004 entry from Flyway history. Only when exact post-cleanup inspection proves that both `ux_characters_character_uuid_idx` and `idx_characters_owner_resolved_roster` indexes and the `ux_characters_character_uuid` constraint are absent, repair the failed V1004 history entry in the owning Entity schema/history table before rerunning migrate, keeping writer admission closed and writers quiesced throughout. Any surviving valid object or mixed state still requires the operator-reviewed, phase-specific roll-forward plan above. + ## Target Replacement Operations Replacement operations use the stable `playableStateNamespaceId` and owner-resolved `playableStateScope` for durable S1/S2 state and the active `gameInstanceId` as a runtime fence; Entity validates the scope and never derives it from the opaque namespace. Explicitly disposable S3 families may remain instance-keyed. Entity must report owner-local classification, mapping validation/application, and cleanup acknowledgement to World Management. Unknown or unregistered families block cutover/termination, and an echoed `remapSetId` is not proof of mapping application. [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) and [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) own the cross-service decisions; this file records the Entity operational consequence. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index b9eaa2b9eb..a8c377679e 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -21,6 +21,12 @@ This document defines Entity Management’s runtime model, persistence ownership - The current `characterGraph` helper caches `getWithInventory(characterId)` by character ID alone with a TTL and performs no namespace or authoritative version validation. It is not the target namespace-qualified Class A `character-cache:*` contract; until that contract is implemented and proved, this cache is not correctness authority. - `EntityDraftDesignDigestServiceImpl` currently emits `digestSchemaVersion=1` without hashing item `equipmentSlotGroupKey`, while `EquipmentServiceImpl` uses that field for slot compatibility admission. The digest is therefore incomplete for equipment semantics: different slot-group constraints may attest the same content digest. Target convergence adds the normalized field, bumps the schema version, and proves cross-version digest isolation plus publish-gate rejection of a changed constraint. +- Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows. Existing legacy consumers retain develop behavior for legacy rows, while numeric character, inventory, equipment, friend, resource and condition predicates exclude actors carrying canonical `tenant_uuid` provenance even when their status becomes `QUARANTINED`, including updates and condition expiry. Legitimate legacy/quarantined rows with null canonical tenant provenance retain legacy behavior. Entity's private tenant-row association is not a platform numeric tenant identity; equal numeric values do not authorize legacy access to a canonical actor. Canonical UUID assignment, receipt and roster predicates remain separate. This narrow storage bridge boundary does not activate runtime quarantine enforcement or canonical player admission. +- Entity V1006–V1010 adds committed assignment/receipt and sealed roster-snapshot storage with canonical publication identity and exact owner counters. The source services are manually composed and unregistered; no authenticated transport, actor promotion of retained legacy rows, or runtime admission is activated. The detailed assignment/roster contract remains in [Entity API Contracts](./api-contracts.md#implementation-status). +- Sealed canonical roster snapshots and their actor references are immutable Entity-owned records: append a new snapshot/reference set when the canonical target or roster changes, preserving the existing deletion guards. Before any handler, service, or alternative snapshot writer is registered, this family must have an ADR 0163 retention declaration covering its class, terminal and reference blockers, compatible horizon, holds, metrics, cleanup cadence, and proved owner-local disposal. This does not set a numeric horizon, authorize deletion, or establish indefinite retention. The current passive writer has no registered production call chain; its pending implementation obligation is tracked under #2967 and is not completion or merge proof. +- Standard, production, and test Flyway profiles use PostgreSQL `transactional-lock=false` for V1004's concurrent index builds. Entity V1003–V1010 follows unchanged develop Saga V1000–V1002 under the default combined migration locations. Current storage, fresh packaged legacy player-flow, and actual-parent upgrade qualification and its local infrastructure limits are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). +- Actual authenticated owner provenance and the real Game Session caller/controller/execution replacement remain incomplete. Test-created `OWNER_RESOLVED` rows establish bounded storage isolation only; legacy names, numeric IDs, `shared-live`, `instance:`, and runtime pointers never fill missing canonical owner evidence. Runtime quarantine guards, cleanup holds, and condition-expiry retention belong to the later runtime boundary. + ## Architecture and Design Notes - Uses the service-owned PostgreSQL schema and the platform `jOOQ + Flyway` persistence direction. Flyway owns schema evolution and generated jOOQ types are the default SQL access path; the narrow PostgreSQL-specific plain-SQL escape hatch requires focused proof and does not create a parallel ORM authority. diff --git a/design/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index 532816116c..a2b9cbcbb0 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -47,7 +47,7 @@ This document is the current target authority for SQL persistence, schema owners - Saga tables are created inside the owning service schema via the shared `${serviceSchema}.saga_*` migrations rather than a separate dedicated `saga` schema. - New migrations are committed alongside service code so history stays with the owning service. -Shared migration artifacts use a collision-free versioning convention relative to adopter-local migrations. An applied shared migration is never renumbered, rewritten, or silently replaced; a shared change is a new compatible migration under that convention. A physical PostgreSQL cluster or database may host multiple service schemas, but that does not permit cross-service DDL, foreign keys, direct table reads, or one service to advance or repair another service's Flyway history. +Shared migration artifacts use a collision-free versioning convention relative to adopter-local migrations. Default Flyway ordering and validation remain enabled. Before allocating a new service-local version, inspect the immutable receiving parent’s complete effective migration set, including every shared location loaded by that service; the new version must be strictly greater than that combined local/shared frontier. A new shared migration must be strictly greater than every adopting service’s effective frontier, so a service-local extension cannot make the next shared migration an ignored lower version. Compare added artifacts against the receiving parent with the existing Flyway version checker, and prove fresh bootstrap and upgrade from the actual installed combined history. A manually dispatched CI run must supply the receiving parent’s full immutable commit SHA; CI fetches that exact commit when needed and fails if it is unavailable so the same parent comparison remains in force. Re-version only never-applied candidate artifacts when correcting allocation; preserve their SQL bytes and every applied artifact’s filename and checksum. An applied shared migration is never renumbered, rewritten, or silently replaced; a shared change is a new compatible migration under that convention. A physical PostgreSQL cluster or database may host multiple service schemas, but that does not permit cross-service DDL, foreign keys, direct table reads, or one service to advance or repair another service's Flyway history. ### Objective Compatibility Gates diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 6b83ab2217..ec9adb9cd0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -236,6 +236,11 @@ Entry format: - Expected pattern: read the class’s declared package before specifying a test filter, and verify task execution rather than equating build success with every requested check passing. Enable the repository’s canonical full-check property when selecting static tasks. - Current status: corrected package selection passed 50 focused unit cases; the subsequent runtime fix passed 58 selected unit cases. A separate canonical `-PfullCheck` run executed the required static checks successfully. No validation requirement was waived. +- `2026-10-13`: Native Linux Docker proof can still invoke a Windows credential helper + - Context: the claimed Gameplay fresh-bootstrap run rebuilt all service jars and images successfully, then failed before startup while pulling public Redis images. WSL reported `UtilAcceptVsock` and `accept4` timeout errors followed by a Docker credential lookup failure. + - Observation: using the native Linux Docker socket does not select a separate client credential configuration. A run-scoped private client configuration can omit unavailable Windows credential helpers while preserving static registry settings and Compose plugin discovery; the global client configuration need not change. + - Current status: the required proof using packaged service artifacts passes both transports with the isolated configuration and pinned public images. This client failure establishes neither an application regression nor a cause for the earlier Testcontainers endpoint refusals. + - `2026-10-14`: Review-period bookkeeping must not contend for provider execution locks - Context: the Overseer reported that Gameplay's three concurrent metadata reset batches encountered active-provider errors during the native rollout, with no actual provider active. - Observation: reset-versus-reset global lock contention was reported as provider activity, and network/full-stack refresh made local counter bookkeeping slow and coupled to unrelated source readiness. @@ -243,4 +248,20 @@ Entry format: - Current status: local transactional implementation is prepared; installed-selector promotion and live rollout verification remain pending with the owning orchestrator. - Reconsideration trigger: verify concurrent metadata batches after coordinated version-matched selector promotion. +- `2026-10-14`: Transfer terminal-owned work at a native command boundary + - Context: a replacement subagent could not attach to the main agent’s existing execution session; the tools returned an unknown process ID even though the main agent could still observe its running batch. + - Expected pattern: keep one execution owner, finish the current native command without cancellation, then resume only the missing stable operation keys from the canonical store in the new owner’s terminal. An execution-session ID does not transfer process ownership across agent contexts. Use the same boundary to drain incompatible database writers before coordinated selector promotion. + - Evidence limits: completion counts and rollout timings remain in the owning controller job. This handoff does not replace the separate concurrent-reset reconsideration trigger above. + +- `2026-10-14`: Verify user-visible rendering against installed controller input + - Observation: Root deployed the numeric review-limit renderer before the matching controller fields were installed. Formatter tests passed, but interim live queue rows showed `Limits not reported`. + - Expected pattern: pair rendering changes with the version-matched controller input and verify the actual endpoint before claiming the related user-facing outcome is complete. This is a reusable verification lesson, not an additional approval gate or lifecycle policy. + - Recovery: coordinated controller promotion and actual-endpoint verification restored numeric limits; the owning controller job retains the rollout details. + - 2026-10-15: Administrative review settings share a dispatch boundary with provider-backed commands. When removing latency from one setting command, inspect the neighbouring stop/allocation/reset dispatch family and prove each actual entrypoint with Git, GitHub and subprocess access forbidden; method-only fixtures can preserve legacy behavior while missing expensive controller construction. Retain evidence-bound consumption as a separate operation rather than weakening request admission. + +- `2026-10-14`: Native fix attribution needs the exact requested postimage + - Context: Gameplay recorded a requested AA-1.3 tracker-row repair as fixed after its nearby narrative and migration proof passed, while the named row still lacked the migration anchors. + - Observation: the next CLI review exposed the unchanged row. Documentation hygiene checks had passed because they do not verify that a requested semantic target changed. The original native fix record therefore overstated its proof. + - Expected pattern: inspect the exact requested row or declaration before recording an accepted-fix resolution; verify its named anchors instead of relying on a nearby paragraph or a broad substring replacement. + - Current status: the exact row is corrected and verified. An immutable audited resolution correction points to the published repair while retaining the original wrong attribution; the User and Overseer were informed. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index f2167c082c..7a8b72e22c 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -12,7 +12,7 @@ Current residual: the crafting handlers remain runtime-reachable legacy implemen The capability-table CRUD entry below refers only to this legacy persistence/service-controller seam; it is not a supported public REST API or gameplay crafting flow. -PLAYER-01 remains a target ownership contract, not a capability completion. Detailed persisted actor, policy, descriptor/template, and fork-copy rules are owned by [Entity Management](../../architecture/microservices/entity-management-service/runtime-and-data.md). Gameplay tracking retains only the consequence that actor-state/effect work must use Entity's persisted realm-valid identity; current synthetic-ID, fixed-schema, policy-resolution, provisioning, and fork-copy proof gaps remain. +PLAYER-01 remains a target ownership contract, not a capability completion. Detailed persisted actor, policy, descriptor/template, and fork-copy rules are owned by [Entity Management](../../architecture/microservices/entity-management-service/runtime-and-data.md). The preparation adds opaque UUID/quarantine metadata, canonical assignment/receipt/roster storage, and manually composed unregistered source services. Existing legacy consumers retain develop behavior. Authenticated owner provenance, real caller/controller/execution replacement, runtime quarantine enforcement, and gameplay activation remain later work; storage fixtures do not close those gaps. Passive `CHARACTER_CREATE/1` receiving support is now present in common-platform-core: [the family codec](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java) composes the existing `MutationDigestV1` grammar with schema-three `RealmEntryPolicy`; its bounded [authored-source projection parser](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java) checks the retained `GameplayRuleManifest` and `PlayerCreationDescriptor` inputs. The [shared vector resource](../../../services/common-platform-core/src/test/resources/operator/character-create-v1-vectors.json) retains four literal positive preimages and now includes required negative cases; the [focused codec test](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java) exercises the production decoder against those fixtures and checks additional source contradictions. The current local run and its limits are recorded under [Validation and Proof](#validation-and-proof). This remains local-only receiver support: it does not establish a Game Session producer, authenticated source readback, Entity terminal or owner protections, or route activation, so GR-3.1 remains partial. The [canonical family schema](../../architecture/microservices/entity-management-service/character-create-action-schema.md) owns the contract details. @@ -28,7 +28,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - durable character, NPC, and item records plus bounded XP and NPC respawn-eligibility checks exist; Entity is the target persisted actor owner, but policy-aware entry, unified actor runtime, and complete respawn lifecycle do not. Passive `CHARACTER_CREATE/1` codec and authored-source projection receiving support is present. | `proven` - focused character, NPC, item/inventory, and passive character-action tests cover bounded records, lifecycle, and receiving seams, not PLAYER-01 owner protection or activation proof. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [NpcServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImpl.java); [ItemInstance.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ItemInstance.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql); [Entity Management proto](../../../protos/entity-management/v1/entity_management_service.proto); [CharacterCreateOperatorActionCodec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodec.java); [AuthoredInitialActorCoreProjection.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java) | [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [NpcServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/NpcServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [CharacterCreateOperatorActionCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Synthetic-ID risk, fixed RPG-shaped fields, published policy/descriptor/template resolution, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain unproven. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, and manually composed unregistered source services are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation: the current corrected Entity gate passes unit and physical PostgreSQL integration cases with zero failures/errors/skips, including the default combined manifest and actual-parent retained upgrade; executed counts and run attribution are recorded under Validation and Proof. Fresh rebuilt images pass both transport LOGIN/PLAY/LOOK using unchanged develop gameplay consumers. This is not authenticated canonical owner/admission replacement; fixture-created owner-resolved rows prove storage predicates only. See [Validation and Proof](#validation-and-proof). | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance, real caller/controller/execution replacement, production admission and runtime quarantine remain open, alongside policy/descriptor/template resolution, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID ingress bypass and remediation proof remain open. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Blank-`effectId` replay-ledger bypass and its ingress remediation remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - authored slot/body-layout compatibility and `WEAR`/`REMOVE` equipment binding are live; loadouts and lifecycle triggers are not. | `proven` - focused equipment service/controller and item-command tests cover slot compatibility and binding. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, and owner-validated cutover remapping remain target gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - typed actor-state evaluation, conditions, durable replay, and self-targeted `APPLY_ACTION_STATE` admission are live; general action resolution is not. | `proven` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover the bounded seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | @@ -113,6 +113,16 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Validation and Proof +- Historical passive-preparation baseline at `79fac839c5086571439e6e5e219eb58f2fa4f47f` on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c`: Entity executed 234 unit cases in the first recut run and 24 physical PostgreSQL integration cases in the final run, all with zero failures, errors or skips; units were up-to-date in the final run. Default combined V1/Saga1000–1002/Entity1003–1010 fresh history and actual-parent retained-data upgrades passed, preserving installed ranks, scripts, checksums and success. Account's 15 focused protection cases passed locally; its broader local 236-case integration run had two unavailable endpoint fixtures (PostgreSQL refusal and Redis host-port timeout), so that full local gate failed. The identical Account/Common/proto/build input scope at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` passed source Validation Account job 115335024215: 1,295 unit cases with four existing filesystem skips, and 240 integration cases with zero failures, errors or skips, including both unavailable local suites. Main verified its own Account artifact 11822625688 and matching inputs. Affected formatting, Checkstyle, SpotBugs and documentation checks passed; the final Account integration static/documentation gate passed in 28s. These Account results are historical and their detailed owner attribution is recorded in [Player Access and Session](./player-access-and-session.md#original-startsession-source-protection-storage). The source-built, run-owned fresh-bootstrap proof rebuilt jars/images and passed WebSocket and Telnet WORLDS/LOGIN/PLAY/LOOK after the configuration-only discovery correction and isolated native Docker client recovery. These baseline results preserve legacy behavior; authenticated canonical owner/caller/controller/execution replacement and production activation remain unproved. The complete donor `d215df3b6be4b6a1db29432a1e7ac83ba4f72d73` retains later runtime obligations. Current published-head CI/reviews remain separate; no GDS semantic or ordering closure is claimed. + +- Subsequent review corrections on develop `18f8063306c2ddb4337646de50b73619915a0e25` pass the full Entity gate: 236 unit cases executed in the first correction run and 26 physical PostgreSQL cases executed in the final gate, with zero failures, errors or skips. The new PostgreSQL proof checks Spring-proxy rejection without a caller-owned writable transaction and overlapping roster reads while preserving assignment writer exclusion. Both assignment digest paths use the same ordered encoder with literal `SHARED`/`ISOLATED` digest vectors, and run-owned capabilities admit release references through the documented 1,024-character bound. The canonical 79-leaf implementation-tracker check passes with actual migration file anchors. Account correction proof is recorded in [Player Access and Session](./player-access-and-session.md#original-startsession-source-protection-storage). These are bounded passive storage/source corrections; canonical runtime consumers and genuine owner admission remain open. + +- Latest additional-review correction on `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` source inputs: the locked Entity gate passed in 1m30s, freshly executing 237 unit and 28 physical PostgreSQL cases with zero failures, errors or skips; jOOQ was up-to-date. The new collision variant quarantines an assigned canonical actor while retaining its canonical tenant provenance, then proves that legacy character, inventory, equipment, friend, resource, condition and expiry paths still exclude it. Legitimate quarantined legacy rows with null canonical tenant provenance remain usable; canonical receipt and roster readers exclude the quarantined actor. Formatting, compilation, static and documentation checks passed. The manual-CI parent selector, missing-parent failure and event cases pass the checker self-test, Ruff, workflow lint and YAML lint. Current published-head CI, additional Hosted/CLI reviews and fresh packaged runtime remain separate; full local Compose is paused for resource lifecycle tooling. + +- Prior passive-preparation proof is the original legacy-bridge isolation correction: the full Entity gate passed with 237 unit and 27 physical PostgreSQL integration cases, zero failures, errors or skips. Account's latest 20-case correction proof is recorded in [Player Access and Session](./player-access-and-session.md#original-startsession-source-protection-storage). The colliding numeric-tenant fixture proves that canonical actors and their inventory, equipment, friend, resource and condition rows are hidden from legacy readers, guarded writes reject canonical stored parents even when a legacy parent is supplied, and expiry preserves canonical conditions. Ordinary legacy reads, inserts, updates, deletes and expiry remain usable; exact canonical UUID, receipt and roster reads remain usable. The inventory-bearing positive case also exposed and corrected a missing inventory-version projection. A fresh, uncached TCP proto-generation and Java-compilation proof passes; the earlier source Runtime compiler failure remains unreproduced and does not supply current packaged runtime proof. The earlier Hosted allocation completed; later User-requested rounds and new published-head CI remain separate. + +- Historical Stage 1 evidence, for its original runtime-enforcement boundary only: Stage 1 identity, quarantine, fail-closed consumer, and migration-configuration test anchors are linked below; historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded, and fixture-created `OWNER_RESOLVED` rows prove predicates only, not owner-backed runtime provenance. The exact 42-file stage1 source at `1b89f28e82ecdae237a9cb71d9324cb5e3437103` passed the local Entity gate with 209 unit and 12 integration tests, including 10 PostgreSQL-backed cases, zero failures/errors/skips, and successful formatting, jOOQ generation, service checks, link checking, and Markdown lint. The later `fe6da5dd3246b1479977fed8f0b434bb9857e909` carry has zero Entity-path intersection with the validated parent and adds no fresh-run claim. The byte-identical migration renumbering to V1003–V1005 passed the local full Entity gate on 2026-10-13 UTC: 13 PostgreSQL integration cases executed with zero failures, errors or skips, including the fresh default combined manifest and retained-row upgrade from the actual V1 plus Saga1000–1002 parent frontier. Applied parent versions, script paths, checksums, ranks and success records remain unchanged; the appended frontier is 1005 with no out-of-order migrations. The 211 unit cases retain the preceding executed-run attribution and were up-to-date in the final 50-second gate; jOOQ generation was also up-to-date. Formatting, Checkstyle, SpotBugs and documentation checks passed. Current published-head CI and positive runtime smoke remain separate obligations. Authenticated Game Session-to-Entity mTLS/network proof and live PLAY remain unrun. This is retained historical attribution, not proof of the current passive preparation. + - The integrated passive receiver review corrections on develop `b95aade1546a1d90fde3e884b14eef8190314864` passed `spotlessApply :common-platform-core:check -PfullCheck linkCheck lintMarkdown --continue` locally in 1m 38s (213 tasks). Common-platform-core executed 370 tests with zero failures, errors, or skips, including branding DELETE identity, strict command schema integers, exact policy/template revision provenance, and both owner-inventory mutation round trips and rejection cases. This focused run qualifies these passive corrections only; exact published-head CI remains separate and no producer, owner protection, terminal composition, or activation proof is claimed. - Passive `CHARACTER_CREATE/1` local reconstruction on develop `ec16942d236053494b4a8d94d94ef8a5a8be0d08`, retained in candidate `4c3318d07de70e74a60eaaf0a4754d4ac2a28f2d`: the locked `spotlessApply check -PfullCheck linkCheck lintMarkdown --continue` run passed in 3m27s (559 tasks: 324 executed, 195 cached, 40 up-to-date). Common-platform-core reports contain 360 tests with zero failures, errors, or skips; the allocation validator passed for 359 sources (356 allocated, three explicit exemptions). The final workflow/proof-status documentation checks passed in 8s. This proves local passive receiving support only; skipped Docker-backed suites receive no physical credit, and producer authentication, owner protections, Entity terminal composition, route activation, and current published-head CI remain separate obligations. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 1973b6f4de..a6c0c1f9c1 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,6 +10,28 @@ Game Session now carries a default-off source path for current route and publish The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. +### Original StartSession source-protection storage + +The bounded V1003 receiving cut, hardened by forward V1004, adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. The source-only V130 selected-owner reservation hook is outside this cut and remains a separate receiving obligation. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. + +The pre-review preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c` passed all 15 focused Account PostgreSQL cases with zero failures/errors/skips: 13 admission and two activation cases, including the default-location fresh 113-artifact manifest and unchanged actual 112-artifact parent upgrade. jOOQ generation, compilation, formatting, Checkstyle, integration SpotBugs and documentation checks pass. The broader local 236-case Account integration run had two unavailable endpoint fixtures and remains a failed local gate; identical Account/Common/proto/build inputs at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` pass the own Account source-CI artifact 11822625688 with 240 integration cases (zero failures, errors or skips) and 1,295 unit cases (zero failures or errors, four existing filesystem skips). Fresh rebuilt images also pass both unchanged legacy LOGIN/PLAY/LOOK transport baselines. These results qualify the bounded protection storage and existing behavior only. Those pre-review results did not exercise the activation acquisition guards. The corrected [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) and [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) stipulate upstream data while leaving the protection/source-writer guards enabled; they establish no genuine owner production, authenticated terminal settlement, continuous canonical admission, actor placement or region delivery. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). + +The subsequent Hosted/CLI correction on develop `18f8063306c2ddb4337646de50b73619915a0e25` executed 18 focused Account PostgreSQL cases with zero failures, errors or skips. Acquisition now rejects admission data that cannot satisfy immutable settlement bounds; committed activation fixtures run the acquisition, source-child and deferred-completeness guards. The proof includes the 256-source boundary, canonical Base64 and UTF-16 ordering, a complete activation tuple above 135,168 bytes, and settlement after lease expiry. Actual jOOQ generation, compilation, integration Checkstyle and SpotBugs, formatting and documentation checks passed. This corrects the bounded fixture proof; the older broad source-CI counts remain historical and do not qualify the changed SQL or establish genuine owner production. + +The acquisition/settlement alignment now applies one closed outer lifecycle validator to PREPARING acquisition and ACTIVE settlement, retaining opaque nested launch evidence exactly rather than duplicating its codec or authenticating World. Its final focused gate passes 22 physical PostgreSQL cases (18 admission and four activation), zero failures, errors or skips, in 1m29s: 40 malformed acquisition variants leave no protection/source rows or writer exclusion, while the 58 settlement negatives, retained V1003 upgrade/history/rows, valid ACTIVE and separate ABORTED release remain covered. The control-plane request bound reuses the existing UTF-16 helper. The first attempt failed before SQL in four Activation cases; one bounded retry established the intended red by accepting malformed PREPARING evidence. The subsequent green gate generated jOOQ and passed formatting, integration Checkstyle and SpotBugs. Migration-tip proof now checks all current resolved migrations and explicit V1003/V1004 presence while retaining the frozen 112-artifact parent; the isolated V1003-to-V1004 upgrade remains pinned. + +Exact-source cloud proof for the preceding published `02401d4df0276b04c7f0ff780441a050c4b72fc8` on develop `683c2a2b3417456a2eb5758401a9bc347e53e29a` passes 1,291 executed Account units (four additional defined cases skipped) and all 246 physical integration cases in Validation `38475212382`, job `115564246534`, JUnit artifact `11855135658`. Runtime `38475212357` executes both legacy WebSocket and Telnet WORLDS/LOGIN/PLAY/LOOK flows; its separate Smoke Gate fails on missing REST step metadata, with the tooling correction owned by Overseer. These results qualify that preceding SQL only, not this acquisition repair. The original failed local full run remains failed; newer exact-candidate CI and packaged proof remain required. + +The preceding review correction adds forward V1004 lifecycle integrity without rewriting V1003 or earlier applied migrations. The focused final run passed 21 physical PostgreSQL cases (18 admission and three activation), zero failures, errors or skips, in 1m15s. It proves the 114-artifact fresh combined manifest, actual V1002 receiving-parent upgrade, retained V1003 pending protection/source rows and unchanged prior migration ranks/checksums through V1004, closed ACTIVE evidence and 58 malformed carriers retaining writer exclusion, and exact ACTIVE/ABORTED release. jOOQ generation and formatting passed. The broader Account run executed 1,295 unit cases with zero failures/errors and four existing filesystem skips, and 246 integration cases with four failures: two stale manifest assertions, then PostgreSQL connection refusal and Redis fixture startup timeout. The manifest corrections pass in the focused 21-case run; both unavailable endpoint cases subsequently pass in a separate two-case physical retry on unchanged Account inputs. The original full run remains failed and the endpoint cause is unknown; these replacement results do not claim another unfiltered execution. Final integration Checkstyle/SpotBugs and documentation checks passed in 21 seconds. Current published-head CI remains separate, and full local Compose is paused. Upstream owner inputs remain stipulated; authenticated production and activation remain unproved. + +Forward [V1004.1](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql) rejects a COMMITTED settlement with a regressing World `lifecycleEpoch` or `rowVersion`. The corrected focused run passed all 22 physical PostgreSQL cases with zero failures, errors or skips in 1m40s, including the pinned V1003-to-V1004 historical upgrade, a separate V1004-to-V1004.1 comparison of prior migration ranks/checksums and retained pending-protection/source bytes and `xmin`, both counter decreases retaining writer exclusion, and a valid increased epoch with equal row version. The initial consolidated run failed one new fixture assertion because its proposed row-version decrease was equal to the retained zero; that failed result remains retained. The fixture now starts that case at row version one without changing the guard or other fixture defaults. Account integration static and formatting checks pass; jOOQ generation and the broader Account static/unit checks passed in the initial invocation (1,295 unit cases, four existing filesystem skips). Entity checks also passed with 237 unit and 28 integration cases. These are controlled storage fixtures, not authenticated World production or activation; published-head CI remains separate. + +Forward [V1004.2](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql) applies the existing closed PREPARING validator during COMMITTED settlement, covering protection rows legitimately retained by V1003 before V1004 acquisition validation. The focused consolidated run passed 24 physical PostgreSQL cases (18 admission and six activation) with zero failures, errors or skips in 1m58s. Controlled V1003 fixtures remove each counter or encode `lifecycleEpoch` with the wrong JSON type, then upgrade through V1004 and V1004.1 to V1004.2 and require SQLSTATE `23514` while preserving protection/source rows, bytes, `xmin`, history and source-writer exclusion. A separate V1004.1-to-V1004.2 fixture requires uppercase activation-request UUID spelling to fail acquisition with SQLSTATE `23514`, leave no protection or source-child rows, and leave the source writer unblocked. jOOQ generation, affected formatting and static checks passed, as did seven focused Entity selection unit cases after correcting their coverage name. These are storage-integrity proofs only; no authenticated World production or activation is claimed. + +Forward [V1004.3](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) closes the remaining acquisition gap for whitespace-bearing Base64 spellings in the tuple, projection, launch-read, and PREPARING lifecycle carriers. Its controlled PostgreSQL regression matrix covers newline, space, tab, and carriage return per field, requiring SQLSTATE `23514`, no retained protection or source children, and an unblocked source writer; the V1004.2-to-V1004.3 retained-row/history upgrade and all 16 rejection variants pass in the consolidated 3m55s gate. The gate runs 25 fresh Account PostgreSQL cases and full Entity proof of 237 unit and 29 PostgreSQL cases, all without failures, errors or skips. It also proves nullable condition expiry and resource values through the typed legacy INSERT-SELECT path, and passes Account jOOQ, affected static analysis, formatting and documentation checks. Manual-event Flyway self-tests and Ruff pass separately. This remains passive Account storage integrity; no authenticated World production, runtime activation, or full authenticated flow is established. + +The prior local Account check for the corrected V1003 candidate, `:account-service:spotlessApply :account-service:check -PfullCheck --continue`, passed in 11m 41s. Fresh XML records 18 admission and two activation physical PostgreSQL cases with zero failures, errors or skips; the two new admission methods exercise eight malformed-hold acquisition variants and both COMMITTED (no prior pointer to version 1) and ABORTED settlement release through framed Game Session owner-proof fixtures. The full Account integration run passed 245 cases with zero failures, errors or skips; 1,295 fresh unit cases had zero failures or errors and four existing filesystem skips. Actual jOOQ generation, compilation and static checks passed. The upstream data remains stipulated while Account protection and source-writer guards stay enabled: exact framed terminal-format success is fixture proof, not genuine authenticated owner production, continuous runtime admission or activation. Published-head CI for this candidate remains separate. + ### Entity character-creation denial The existing scalar-only Entity `CreateCharacter` RPC now returns `FAILED_PRECONDITION` before allocation for valid requests in shared and isolated scopes; the focused service test also confirms the malformed zero-account case remains `INVALID_ARGUMENT`. This is denial-only implementation and unit proof. The canonical Account producer, authenticated owner proof, exact catalog/admission-pointer evidence, Game Session and World protections, and Entity durable terminal composition remain missing, so character creation is unavailable under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity owner-protection contract](../../architecture/microservices/entity-management-service/api-contracts.md#character-creation-owner-protection). @@ -144,7 +166,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | -| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; V1004 validates COMMITTED lifecycle integrity only and does not authenticate World. Genuine owner acquisition and authenticated terminal-settlement producers remain open. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 926c303d4e..2b0b759038 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -364,8 +364,149 @@ for filename in ("ci.yml", "security.yml", "license-scan.yml", "codeql.yml"): raise SystemExit("CodeQL must retain its weekly full-analysis schedule") if workflow["jobs"]["codeql-gate"]["if"] != "${{ always() && github.event_name == 'pull_request' }}": raise SystemExit("CodeQL Gate must cover every PR base and remain PR-only") - if set(events) != expected_events or events["workflow_dispatch"] not in ("", {}): - raise SystemExit(f"{filename} must retain exactly its supported events and manual dispatch") + if set(events) != expected_events: + raise SystemExit(f"{filename} must retain exactly its supported events") + if filename == "ci.yml": + dispatch = events["workflow_dispatch"] + if not isinstance(dispatch, dict) or set(dispatch) != {"inputs"}: + raise SystemExit("ci.yml manual dispatch must define only its Flyway parent input") + inputs = dispatch["inputs"] + if not isinstance(inputs, dict) or set(inputs) != {"flyway_base_sha"}: + raise SystemExit("ci.yml manual dispatch must require exactly flyway_base_sha") + base_input = inputs["flyway_base_sha"] + if ( + not isinstance(base_input, dict) + or set(base_input) != {"description", "required", "type"} + or base_input["required"] != "true" + or base_input["type"] != "string" + or "full immutable commit sha" not in base_input["description"].lower() + ): + raise SystemExit("ci.yml flyway_base_sha must be a required string describing the immutable parent SHA") + elif events["workflow_dispatch"] not in ("", {}): + raise SystemExit(f"{filename} must retain an empty manual dispatch") +PYTHON + +# Every CI event must fetch its exact immutable Flyway parent with shallow history. +python3 - "$ci_path" <<'PYTHON' +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(encoding="utf-8"), Loader=yaml.BaseLoader) +job = workflow["jobs"]["flyway-migration-sanity-checks"] +steps = job["steps"] +fetch_steps = [step for step in steps if step.get("name") == "Fetch exact Flyway parent"] +if len(fetch_steps) != 1: + raise SystemExit("CI must have exactly one exact Flyway parent fetch step") +fetch = fetch_steps[0] +if "if" in fetch: + raise SystemExit("Flyway parent fetching must cover every event") +expected_base = ( + "${{ github.event_name == 'workflow_dispatch' && inputs.flyway_base_sha " + "|| github.event_name == 'pull_request' && github.event.pull_request.base.sha " + "|| github.event.before }}" +) +if fetch.get("env") != {"FLYWAY_BASE_SHA": expected_base, "FLYWAY_EVENT_NAME": "${{ github.event_name }}"}: + raise SystemExit("Flyway fetch and checker must use the same immutable event parent") +checkout_steps = [step for step in steps if str(step.get("uses", "")).startswith("actions/checkout@")] +if len(checkout_steps) != 1 or "fetch-depth" in checkout_steps[0].get("with", {}): + raise SystemExit("Flyway parent fetch must retain the default shallow checkout") +fetch_script = fetch.get("run", "") +for required in ( + '"$FLYWAY_EVENT_NAME" != "workflow_dispatch"', + '"$FLYWAY_BASE_SHA" == "0000000000000000000000000000000000000000"', + "^[[:xdigit:]]{40}$", + 'git cat-file -e "${FLYWAY_BASE_SHA}^{commit}"', + 'git fetch --no-tags --depth=1 origin "$FLYWAY_BASE_SHA"', + 'git rev-parse --verify "${FLYWAY_BASE_SHA}^{commit}"', +): + if required not in fetch_script: + raise SystemExit(f"Flyway parent fetch must validate and resolve the exact SHA: missing {required}") + +check_steps = [step for step in steps if step.get("name") == "🧪 Check Flyway Migration Versions"] +if len(check_steps) != 1: + raise SystemExit("CI must have exactly one Flyway version check step") +expected_base = ( + "${{ github.event_name == 'workflow_dispatch' && inputs.flyway_base_sha " + "|| github.event_name == 'pull_request' && github.event.pull_request.base.sha " + "|| github.event.before }}" +) +if check_steps[0].get("env", {}).get("FIREMUD_FLYWAY_BASE_REF") != expected_base: + raise SystemExit("Flyway version check must preserve dispatch, PR-base, and push-before parent selection") +# Exercise the actual YAML fetch script against a shallow checkout, rather than +# relying only on static command spelling or the checkout action's defaults. +checker = Path(sys.argv[1]).resolve().parents[2] / "dev-tools/validation/check-flyway-versions.py" +with tempfile.TemporaryDirectory(prefix="firemud-flyway-shallow-") as temporary: + fixture = Path(temporary) / "source" + fixture.mkdir() + def git_at(directory, *arguments): + return subprocess.run(["git", *arguments], cwd=directory, check=True, + capture_output=True, text=True).stdout.strip() + git_at(fixture, "init", "-q") + migration = fixture / "services/example-service/src/main/resources/db/migration" + migration.mkdir(parents=True) + (fixture / "services/example-service/build.gradle.kts").write_text("dependencies {}\n") + (migration / "V1__base.sql").write_text("-- base fixture\n") + git_at(fixture, "add", ".") + git_at(fixture, "-c", "user.name=Flyway fixture", "-c", "user.email=fixture@example.invalid", + "commit", "-qm", "base") + parent = git_at(fixture, "rev-parse", "HEAD") + (migration / "V2__forward.sql").write_text("-- forward fixture\n") + git_at(fixture, "add", ".") + git_at(fixture, "-c", "user.name=Flyway fixture", "-c", "user.email=fixture@example.invalid", + "commit", "-qm", "forward") + child = git_at(fixture, "rev-parse", "HEAD") + checkout = Path(temporary) / "checkout" + subprocess.run(["git", "clone", "--depth=1", fixture.as_uri(), str(checkout)], + check=True, capture_output=True, text=True) + if git_at(checkout, "rev-parse", "HEAD") != child: + raise SystemExit("shallow fixture selected the wrong immutable child") + environment = dict(os.environ) + for name in ("GITHUB_EVENT_PATH", "GITHUB_EVENT_NAME", "FIREMUD_FLYWAY_BASE_REF"): + environment.pop(name, None) + command = [sys.executable, str(checker), "--root", str(checkout), "--base-ref", parent] + missing = subprocess.run(command, env=environment, capture_output=True, text=True) + if missing.returncode == 0 or "immutable receiving parent commit is unavailable" not in missing.stderr: + raise SystemExit(f"shallow checkout did not demonstrate missing parent: {missing.stdout} {missing.stderr}") + for event_name in ("pull_request", "push", "workflow_dispatch"): + checkout = Path(temporary) / f"checkout-{event_name}" + subprocess.run(["git", "clone", "--depth=1", fixture.as_uri(), str(checkout)], + check=True, capture_output=True, text=True) + if git_at(checkout, "rev-parse", "HEAD") != child: + raise SystemExit(f"shallow fixture selected the wrong immutable child for {event_name}") + unavailable = subprocess.run(["git", "cat-file", "-e", f"{parent}^{{commit}}"], + cwd=checkout, capture_output=True, text=True) + if unavailable.returncode == 0: + raise SystemExit(f"immutable parent was already available before the {event_name} fetch") + event_command = [sys.executable, str(checker), "--root", str(checkout), "--base-ref", parent] + environment.update(FLYWAY_BASE_SHA=parent, FLYWAY_EVENT_NAME=event_name) + fetched = subprocess.run(["bash", "-euo", "pipefail", "-c", fetch_script], cwd=checkout, + env=environment, capture_output=True, text=True) + if fetched.returncode or git_at(checkout, "rev-parse", parent + "^{commit}") != parent: + raise SystemExit(f"exact parent fetch failed for {event_name}: {fetched.stderr}") + available = subprocess.run(event_command, env=environment, capture_output=True, text=True) + if available.returncode: + raise SystemExit(f"checker rejected exact fetched parent for {event_name}: {available.stdout} {available.stderr}") + fetched_command = event_command + available = subprocess.run(fetched_command, env=environment, capture_output=True, text=True) + if available.returncode: + raise SystemExit(f"checker rejected exact fetched parent: {available.stdout} {available.stderr}") + environment.update(FLYWAY_BASE_SHA="0" * 40, FLYWAY_EVENT_NAME="push") + sentinel = subprocess.run(["bash", "-euo", "pipefail", "-c", fetch_script], cwd=checkout, + env=environment, capture_output=True, text=True) + if sentinel.returncode: + raise SystemExit("new-branch sentinel must skip exact fetching") + environment["FLYWAY_EVENT_NAME"] = "workflow_dispatch" + sentinel = subprocess.run(["bash", "-euo", "pipefail", "-c", fetch_script], cwd=checkout, + env=environment, capture_output=True, text=True) + if sentinel.returncode == 0: + raise SystemExit("manual dispatch must reject the zero parent sentinel") + print("Shallow Flyway parent refusal, exact immutable fetch and event sentinel proof passed") + PYTHON # Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. diff --git a/dev-tools/validation/check-flyway-versions.py b/dev-tools/validation/check-flyway-versions.py index 4cc2303bb6..91f3f20330 100644 --- a/dev-tools/validation/check-flyway-versions.py +++ b/dev-tools/validation/check-flyway-versions.py @@ -3,26 +3,34 @@ import argparse import dataclasses +import json import os import re +import subprocess import sys import tempfile from pathlib import Path -VERSION_RE = re.compile(r"^V(?P[0-9]+(?:\.[0-9]+)*)__.+\.(?:java|sql)$") +VERSION_RE = re.compile(r"^V(?P[0-9]+(?:[._][0-9]+)*)__.+\.(?:java|sql)$") +MIGRATION_PATH_RE = re.compile(r"^services/([^/]+)/src/main/(?:resources|java)/db/migration/") +RUNTIME_DEPENDENCY_RE = re.compile( + r'(?:implementation|api|runtimeOnly)\s*\(\s*project\(\s*":([^\"]+)"' + r'|dependencies\.add\(\s*"(?:implementation|api|runtimeOnly)"\s*,\s*project\.project\(\s*":([^\"]+)"' +) +PLUGIN_RE = re.compile(r'(?:\bid|pluginManager\.apply)\(\s*"([^\"]+)"\s*\)') +Snapshot = dict[str, bytes] @dataclasses.dataclass(frozen=True) class MigrationFile: - path: Path - root: Path - project: Path + path: str + project: str version_text: str version_key: tuple[int, ...] def normalize_version(version_text: str) -> tuple[int, ...]: - parts = [int(part) for part in version_text.split(".")] + parts = [int(part) for part in re.split(r"[._]", version_text)] while len(parts) > 1 and parts[-1] == 0: parts.pop() return tuple(parts) @@ -32,93 +40,150 @@ def version_label(version_key: tuple[int, ...]) -> str: return ".".join(str(part) for part in version_key) -def project_label(project_root: Path, repo_root: Path) -> str: - return project_root.relative_to(repo_root).as_posix() - - -def discover_migration_files(repo_root: Path) -> list[MigrationFile]: - services_dir = repo_root / "services" - if not services_dir.is_dir(): - return [] - - discovered: list[MigrationFile] = [] - sql_paths = services_dir.glob("*/src/main/resources/db/migration/**/V*__*.sql") - java_paths = services_dir.glob("*/src/main/java/db/migration/**/V*__*.java") - for path in [*sql_paths, *java_paths]: - if not path.is_file(): - continue - rel_path = path.relative_to(repo_root).as_posix() - is_sql = "src/main/resources/db/migration" in rel_path - is_java = "src/main/java/db/migration" in rel_path - if not is_sql and not is_java: - continue - - match = VERSION_RE.match(path.name) - if match is None: - continue - - service_name = path.relative_to(repo_root).parts[1] - project_root = repo_root / "services" / service_name - if is_java: - java_root = project_root / "src/main/java/db/migration" - relative_parent = path.parent.relative_to(java_root) - logical_root = project_root / "src/main/resources/db/migration" / relative_parent - else: - logical_root = path.parent - version_text = match.group("version") - discovered.append( - MigrationFile( - path=path, - root=logical_root, - project=project_root, - version_text=version_text, - version_key=normalize_version(version_text), - ) - ) - +def relevant_path(path: str) -> bool: + return bool(MIGRATION_PATH_RE.match(path)) or ( + path.startswith("services/") + and (path.endswith("/build.gradle.kts") or re.search(r"/src/main/resources/application[^/]*\.ya?ml$", path)) + ) or (path.startswith("buildSrc/") and path.endswith((".kt", ".kts"))) + + +def current_snapshot(repo_root: Path) -> Snapshot: + paths = [*repo_root.glob("services/*/build.gradle.kts"), + *repo_root.glob("services/*/src/main/resources/application*.y*ml"), + *repo_root.glob("services/*/src/main/resources/db/migration/**/*"), + *repo_root.glob("services/*/src/main/java/db/migration/**/*"), + *repo_root.glob("buildSrc/**/*.kt"), *repo_root.glob("buildSrc/**/*.kts")] + return {path.relative_to(repo_root).as_posix(): path.read_bytes() for path in paths if path.is_file()} + + +def git(repo_root: Path, *args: str) -> bytes: + result = subprocess.run(["git", "-C", str(repo_root), *args], capture_output=True, check=False) + if result.returncode: + raise ValueError(result.stderr.decode().strip() or f"git {' '.join(args)} failed") + return result.stdout + + +def parent_snapshot(repo_root: Path, base_ref: str) -> Snapshot: + # A branch name can move while validation runs. Require the caller's pinned commit. + if not re.fullmatch(r"[0-9a-fA-F]{40}", base_ref): + raise ValueError("--base-ref must be a full immutable 40-character commit SHA") + try: + commit = git(repo_root, "rev-parse", "--verify", f"{base_ref}^{{commit}}").decode().strip() + except ValueError as error: + raise ValueError(f"immutable receiving parent commit is unavailable: {base_ref}; fetch that exact SHA") from error + if commit.lower() != base_ref.lower(): + raise ValueError("--base-ref must identify a commit directly") + paths = git(repo_root, "ls-tree", "-r", "--name-only", commit, "services", "buildSrc").decode().splitlines() + return {path: git(repo_root, "show", f"{commit}:{path}") for path in paths if relevant_path(path)} + + +def discover_migration_files(snapshot: Snapshot) -> list[MigrationFile]: + discovered = [] + for path in sorted(snapshot): + project_match = MIGRATION_PATH_RE.match(path) + version_match = VERSION_RE.match(Path(path).name) + if project_match and version_match: + text = version_match.group("version") + discovered.append(MigrationFile(path, project_match.group(1), text, normalize_version(text))) return discovered -def collect_issues(repo_root: Path) -> tuple[list[str], int, int]: - discovered = discover_migration_files(repo_root) - grouped: dict[Path, dict[Path, list[MigrationFile]]] = {} - for item in discovered: - grouped.setdefault(item.project, {}).setdefault(item.root, []).append(item) - - issues: list[str] = [] - for project_root in sorted(grouped, key=lambda path: path.relative_to(repo_root).as_posix()): - roots = grouped[project_root] - service_label = project_label(project_root, repo_root) - seen_versions: dict[tuple[int, ...], MigrationFile] = {} - highest_seen: tuple[int, ...] | None = None - for root in sorted( - roots, - key=lambda path: (len(path.relative_to(project_root).parts), path.relative_to(project_root).as_posix()), - ): - for item in sorted(roots[root], key=lambda migration: (migration.version_key, migration.path.name)): - existing = seen_versions.get(item.version_key) - if existing is not None: - issues.append( - f"{service_label} ({root.relative_to(project_root).as_posix()}): " - f"duplicate version V{item.version_text} in {item.path.relative_to(repo_root).as_posix()} " - f"also appears in {existing.path.relative_to(repo_root).as_posix()}" - ) - continue - - seen_versions[item.version_key] = item - - if highest_seen is not None and item.version_key <= highest_seen: - issues.append( - f"{service_label} ({root.relative_to(project_root).as_posix()}): " - f"version V{item.version_text} in {item.path.relative_to(repo_root).as_posix()} " - f"is out of order after V{version_label(highest_seen)}" - ) - continue - - if highest_seen is None or item.version_key > highest_seen: - highest_seen = item.version_key - - return issues, len(grouped), len(discovered) +def saga_adopters(snapshot: Snapshot) -> set[str]: + """Read existing runtime dependencies and composed convention plugins, not classifications. + + This follows the repository's literal Kotlin DSL wiring. Test dependencies are + deliberately excluded: they do not put Saga resources on startup classpaths. + """ + registration = snapshot.get("buildSrc/build.gradle.kts", b"").decode() + plugin_sources: dict[str, str] = {} + for plugin_id, class_name in re.findall( + r'id\s*=\s*"([^\"]+)"\s+implementationClass\s*=\s*"([^\"]+)"', registration + ): + path = "buildSrc/src/main/kotlin/" + class_name.replace(".", "/") + ".kt" + if path not in snapshot: + raise ValueError(f"missing convention source for {plugin_id}: {path}") + plugin_sources[plugin_id] = snapshot[path].decode() + + module_sources = {path.split("/")[1]: data.decode() for path, data in snapshot.items() + if re.fullmatch(r"services/[^/]+/build.gradle.kts", path)} + + def reaches_saga(source: str, visited: set[str]) -> bool: + for dependency in RUNTIME_DEPENDENCY_RE.findall(source): + module = next(part for part in dependency if part) + if module == "common-saga": + return True + key = "module:" + module + if (key not in visited and module in module_sources + and reaches_saga(module_sources[module], visited | {key})): + return True + for plugin in PLUGIN_RE.findall(source): + key = "plugin:" + plugin + if (key not in visited and plugin in plugin_sources + and reaches_saga(plugin_sources[plugin], visited | {key})): + return True + return False + + adopters = set() + for project, source in module_sources.items(): + # Flyway scans nested packages below db/migration, so the parent location + # exposes Saga resources too, even without a redundant explicit saga location. + locations = [data.decode() for path, data in snapshot.items() + if re.fullmatch(rf"services/{re.escape(project)}/src/main/resources/application[^/]*\.ya?ml", path)] + if (any(re.search(r"classpath:db/migration(?:/saga)?(?:[\s,\"']|$)", text) for text in locations) + and reaches_saga(source, {"module:" + project})): + adopters.add(project) + return adopters + + +def effective_sets(snapshot: Snapshot) -> tuple[dict[str, list[MigrationFile]], list[MigrationFile]]: + migrations = discover_migration_files(snapshot) + grouped: dict[str, list[MigrationFile]] = {} + for item in migrations: + grouped.setdefault(item.project, []).append(item) + shared = grouped.get("common-saga", []) + for adopter in saga_adopters(snapshot): + grouped.setdefault(adopter, []).extend(shared) + return grouped, migrations + + +def collect_issues(current: Snapshot, parent: Snapshot | None) -> tuple[list[str], int, int]: + grouped, migrations = effective_sets(current) + parent_grouped, parent_migrations = effective_sets(parent) if parent is not None else ({}, []) + issues = [] + for project, items in sorted(grouped.items()): + seen: dict[tuple[int, ...], MigrationFile] = {} + for item in items: + existing = seen.get(item.version_key) + if existing: + issues.append(f"services/{project}: duplicate version V{item.version_text} in {item.path} " + f"also appears in {existing.path}") + else: + seen[item.version_key] = item + + previous = parent_grouped.get(project, []) + previous_paths = {item.path for item in previous} + frontier = max((item.version_key for item in previous), default=None) + for item in items: + if parent is not None and item.path not in previous_paths and frontier is not None and item.version_key <= frontier: + issues.append(f"services/{project}: new migration {item.path} (V{item.version_text}) " + f"must exceed effective parent frontier V{version_label(frontier)}") + + # A shared migration remains in the raw repository even if a project stops + # loading it. Compare each project's effective history so removing either + # the runtime dependency or a Flyway location cannot silently drop it. + for project, previous in sorted(parent_grouped.items()): + current_paths = {item.path for item in grouped.get(project, [])} + for item in previous: + if item.path not in current_paths: + issues.append(f"services/{project}: historical effective migration no longer applied: {item.path}") + + # Treat parent histories conservatively as applied; never rewrite their names/checksums. + for item in parent_migrations: + if item.path not in current: + issues.append(f"historical migration removed or renamed: {item.path}") + elif parent is not None and current[item.path] != parent[item.path]: + issues.append(f"historical migration content changed: {item.path}") + return issues, len(grouped), len(migrations) def make_fixture(root: Path, relative_paths: list[str]) -> None: @@ -129,62 +194,209 @@ def make_fixture(root: Path, relative_paths: list[str]) -> None: def run_self_test() -> None: - with tempfile.TemporaryDirectory() as tmp: - repo_root = Path(tmp) - make_fixture( - repo_root, - [ - "services/clean-service/src/main/resources/db/migration/V1__init.sql", - "services/clean-service/src/main/java/db/migration/V2__next.java", - ], - ) - issues, _, _ = collect_issues(repo_root) - if issues: - raise AssertionError(f"clean fixture unexpectedly failed: {issues}") + local = "services/example-service/src/main/resources/db/migration/" + shared = "services/common-saga/src/main/resources/db/migration/saga/" + wiring = { + "services/example-service/build.gradle.kts": b'dependencies { implementation(project(":common-saga")) }', + "services/example-service/src/main/resources/application.yml": b'spring:\n flyway:\n locations: classpath:db/migration,classpath:db/migration/saga\n', + } + history = {**wiring, local + "V1__init.sql": b"-- local\n", shared + "V1002__saga.sql": b"-- shared\n"} + + def check(label: str, current: Snapshot, parent: Snapshot | None, expected: str | None) -> None: + issues, _, _ = collect_issues(current, parent) + if (expected is None and issues) or (expected is not None and not any(expected in issue for issue in issues)): + raise AssertionError(f"{label}: expected {expected!r}, got {issues}") + + check("unchanged legacy history", history, history, None) + check("duplicate-only without a base", history, None, None) + check("new low local", {**history, local + "V2__new.sql": b"-- new"}, history, "frontier V1002") + check("forward local", {**history, local + "V1003__new.sql": b"-- new"}, history, None) + + unadopted_parent = { + "services/example-service/build.gradle.kts": b"dependencies {}", + "services/example-service/src/main/resources/application.yml": + b"spring:\n flyway:\n locations: classpath:db/migration\n", + local + "V2000__init.sql": b"-- local\n", + shared + "V1000__saga_a.sql": b"-- shared a\n", + shared + "V1001__saga_b.sql": b"-- shared b\n", + shared + "V1002__saga_c.sql": b"-- shared c\n", + } + newly_adopted = { + **unadopted_parent, + "services/example-service/build.gradle.kts": wiring["services/example-service/build.gradle.kts"], + "services/example-service/src/main/resources/application.yml": + wiring["services/example-service/src/main/resources/application.yml"], + } + check("newly effective shared history below local frontier", newly_adopted, unadopted_parent, "frontier V2000") + check("unchanged non-adopter with raw shared history", unadopted_parent, unadopted_parent, None) + + forward_parent = {path: data for path, data in unadopted_parent.items() + if path != local + "V2000__init.sql"} + forward_parent[local + "V999__init.sql"] = b"-- local\n" + forward_adopted = { + **forward_parent, + "services/example-service/build.gradle.kts": wiring["services/example-service/build.gradle.kts"], + "services/example-service/src/main/resources/application.yml": + wiring["services/example-service/src/main/resources/application.yml"], + shared + "V1003__saga_forward.sql": b"-- forward shared\n", + } + check("newly effective shared history above local frontier", forward_adopted, forward_parent, None) + + test_only_parent = { + **unadopted_parent, + "services/example-service/src/main/resources/application.yml": wiring["services/example-service/src/main/resources/application.yml"], + } + test_only_forward = { + **test_only_parent, + "services/example-service/build.gradle.kts": b'testImplementation(project(":common-saga"))', + local + "V2001__forward.sql": b"-- new local\n", + } + check("test-only saga dependency does not adopt shared migrations", test_only_forward, test_only_parent, None) + + advanced = {**history, local + "V1005__later.sql": b"-- later"} + check("shared below adopter frontier", {**advanced, shared + "V1004__new.sql": b"-- new"}, advanced, "frontier V1005") + check("forward shared", {**advanced, shared + "V1006__new.sql": b"-- new"}, advanced, None) + check("combined duplicate", {**history, local + "V1002__duplicate.sql": b"-- dup"}, history, "duplicate version V1002") + check("normalized duplicate", {**history, local + "V1002_0__duplicate.sql": b"-- dup"}, history, "duplicate version V1002") + check("changed history", {**history, local + "V1__init.sql": b"-- rewritten"}, history, "content changed") + check("removed history", {path: data for path, data in history.items() if path != local + "V1__init.sql"}, history, "removed or renamed") + check("java/sql duplicate", {**history, "services/example-service/src/main/java/db/migration/V1__dup.java": b"// dup"}, history, "duplicate version V1") + + # Exercise the actual composed convention wiring and exclude test-only dependencies. + conventions = { + "buildSrc/build.gradle.kts": b'id = "base"\nimplementationClass = "example.Base"\nid = "composed"\nimplementationClass = "example.Composed"', + "buildSrc/src/main/kotlin/example/Base.kt": b'dependencies.add("implementation", project.project(":common-saga"))', + "buildSrc/src/main/kotlin/example/Composed.kt": b'pluginManager.apply("base")', + } + composed = {**history, **conventions, "services/example-service/build.gradle.kts": b'plugins { id("composed") }'} + check("composed runtime convention", {**composed, local + "V2__new.sql": b"-- new"}, composed, "frontier V1002") + test_only = {**history, "services/example-service/build.gradle.kts": b'testImplementation(project(":common-saga"))'} + check("test-only dependency", {**test_only, local + "V2__new.sql": b"-- new"}, test_only, None) + dependency_removed = {**history, "services/example-service/build.gradle.kts": b"dependencies {}"} + check("removed runtime dependency", dependency_removed, history, "historical effective migration no longer applied") + explicit_saga_location = {**history, "services/example-service/src/main/resources/application.yml": + b"spring:\n flyway:\n locations: classpath:db/migration/saga\n"} + location_removed = {**explicit_saga_location, "services/example-service/src/main/resources/application.yml": + b"spring:\n flyway:\n locations: classpath:db/migration/other\n"} + check("removed Flyway location", location_removed, explicit_saga_location, + "historical effective migration no longer applied") + second_local = "services/second-service/src/main/resources/db/migration/" + multiple = {**history, "services/second-service/build.gradle.kts": wiring["services/example-service/build.gradle.kts"], + "services/second-service/src/main/resources/application.yml": wiring["services/example-service/src/main/resources/application.yml"], + second_local + "V2000__later.sql": b"-- later"} + check("every adopter frontier", {**multiple, shared + "V1003__new.sql": b"-- new"}, multiple, "frontier V2000") + one_adopter_removed = {**multiple, "services/example-service/build.gradle.kts": b"dependencies {}"} + membership_issues, _, _ = collect_issues(one_adopter_removed, multiple) + if (not any("services/example-service: historical effective migration no longer applied" in issue + for issue in membership_issues) + or any("services/second-service:" in issue for issue in membership_issues)): + raise AssertionError(f"one adopter removal affected the wrong project histories: {membership_issues}") with tempfile.TemporaryDirectory() as tmp: - repo_root = Path(tmp) - make_fixture( - repo_root, - [ - "services/duplicate-service/src/main/resources/db/migration/V1__init.sql", - "services/duplicate-service/src/main/java/db/migration/V1__dup.java", - ], - ) - issues, _, _ = collect_issues(repo_root) - if not any("duplicate version V1" in issue for issue in issues): - raise AssertionError(f"duplicate fixture did not fail as expected: {issues}") + root = Path(tmp) + for path, data in history.items(): + target = root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + git(root, "init", "-q") + git(root, "add", ".") + git(root, "-c", "user.name=Flyway fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "history") + base = git(root, "rev-parse", "HEAD").decode().strip() + make_fixture(root, [local + "V2__new.sql"]) + check("immutable git parent and worktree addition", current_snapshot(root), parent_snapshot(root, base), "frontier V1002") + try: + parent_snapshot(root, "HEAD") + except ValueError: + pass + else: + raise AssertionError("mutable base ref was accepted") with tempfile.TemporaryDirectory() as tmp: - repo_root = Path(tmp) - make_fixture( - repo_root, - [ - "services/order-service/src/main/resources/db/migration/V2__init.sql", - "services/order-service/src/main/resources/db/migration/saga/V1__saga.sql", - ], - ) - issues, _, _ = collect_issues(repo_root) - if not any("out of order" in issue for issue in issues): - raise AssertionError(f"out-of-order fixture did not fail as expected: {issues}") + git(Path(tmp), "init", "-q") + event_path = Path(tmp) / "event.json" + sha = "1" * 40 + for event, expected in [({"pull_request": {"base": {"sha": sha}}}, sha), + ({"pull_request": {"base": None}}, None), + ({"pull_request": {"base": "invalid"}}, None), + ({"before": sha}, sha), ({"before": "0" * 40}, None), ({}, None)]: + event_path.write_text(json.dumps(event), encoding="utf-8") + if event_base_ref(str(event_path)) != expected: + raise AssertionError(f"unexpected event base for {event}") + manual_event = {"inputs": {"flyway_base_sha": sha}} + event_path.write_text(json.dumps(manual_event), encoding="utf-8") + if event_base_ref(str(event_path)) != sha: + raise AssertionError("manual dispatch base SHA was not selected") + + # CI passes push metadata through the environment; the explicit option + # must handle the same unborn-branch sentinel without reading Git history. + for explicit in (False, True): + environment = dict(os.environ) + environment.pop("GITHUB_EVENT_PATH", None) + environment.pop("GITHUB_EVENT_NAME", None) + environment["FIREMUD_FLYWAY_BASE_REF"] = "0" * 40 + command = [sys.executable, str(Path(__file__).resolve()), "--root", tmp] + if explicit: + command.extend(["--base-ref", "0" * 40]) + result = subprocess.run(command, check=False, env=environment, capture_output=True, text=True) + if result.returncode or "Parent frontier comparison" not in result.stdout: + raise AssertionError(f"unborn explicit={explicit}: {result.stdout} {result.stderr}") + + manual_environment = dict(os.environ) + manual_environment["FIREMUD_FLYWAY_BASE_REF"] = "1" * 40 + manual_environment["GITHUB_EVENT_NAME"] = "workflow_dispatch" + manual_environment["GITHUB_EVENT_PATH"] = str(event_path) + event_path.write_text(json.dumps({"inputs": {}}), encoding="utf-8") + result = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--root", tmp], + check=False, env=manual_environment, capture_output=True, text=True) + if result.returncode == 0 or "requires a full immutable" not in result.stderr: + raise AssertionError(f"manual dispatch without a base was accepted: {result.stdout} {result.stderr}") + + event_path.write_text(json.dumps({"inputs": {"flyway_base_sha": "not-a-sha"}}), encoding="utf-8") + result = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--root", tmp], + check=False, env=manual_environment, capture_output=True, text=True) + if result.returncode == 0 or "full immutable 40-character" not in result.stderr: + raise AssertionError(f"malformed manual dispatch base was accepted: {result.stdout} {result.stderr}") + + event_path.write_text(json.dumps({"inputs": {"flyway_base_sha": "0" * 40}}), encoding="utf-8") + result = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--root", tmp], + check=False, env=manual_environment, capture_output=True, text=True) + if result.returncode == 0 or "requires a full immutable" not in result.stderr: + raise AssertionError(f"zero-sentinel manual dispatch base was accepted: {result.stdout} {result.stderr}") + + event_path.write_text(json.dumps({"inputs": {"flyway_base_sha": "2" * 40}}), encoding="utf-8") + result = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--root", tmp], + check=False, env=manual_environment, capture_output=True, text=True) + if result.returncode == 0 or "immutable receiving parent commit is unavailable" not in result.stderr: + raise AssertionError(f"unavailable manual dispatch parent was accepted: {result.stdout} {result.stderr}") print("Flyway migration sanity checker self-test passed.") +def event_base_ref(event_path: str | None) -> str | None: + if not event_path: + return None + event = json.loads(Path(event_path).read_text(encoding="utf-8")) + pull_request = event.get("pull_request") + if isinstance(pull_request, dict): + base = pull_request.get("base") + return base.get("sha") if isinstance(base, dict) else None + inputs = event.get("inputs") + if isinstance(inputs, dict): + return inputs.get("flyway_base_sha") + before = event.get("before") + # A newly created branch has no parent history in the push event. + return before if before and before != "0" * 40 else None + + def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser(description="Check Flyway migration versions across FireMUD services.") - parser.add_argument( - "--root", - default=Path(os.environ.get("FIREMUD_REPO_ROOT", Path(__file__).resolve().parents[2])), - type=Path, - help="Repository root to scan. Defaults to the FireMUD checkout root.", - ) - parser.add_argument( - "--self-test", - action="store_true", - help="Run a small built-in validation suite against temporary fixtures.", - ) - return parser.parse_args() + parser = argparse.ArgumentParser(description="Check combined Flyway histories and forward-only additions against a pinned parent.") + parser.add_argument("--root", default=Path(os.environ.get("FIREMUD_REPO_ROOT", Path(__file__).resolve().parents[2])), type=Path, + help="Repository root to scan. Defaults to the FireMUD checkout root.") + parser.add_argument("--base-ref", default=os.environ.get("FIREMUD_FLYWAY_BASE_REF"), + help="Full immutable parent commit SHA; defaults to FIREMUD_FLYWAY_BASE_REF or GitHub event base metadata.") + parser.add_argument("--self-test", action="store_true", help="Run focused validation against temporary fixtures.") + args = parser.parse_args() + return args def main() -> int: @@ -192,18 +404,34 @@ def main() -> int: if args.self_test: run_self_test() return 0 - - repo_root = args.root.resolve() - issues, project_count, file_count = collect_issues(repo_root) + root = args.root.resolve() + try: + event_path = os.environ.get("GITHUB_EVENT_PATH") + if os.environ.get("GITHUB_EVENT_NAME") == "workflow_dispatch": + base_ref = event_base_ref(event_path) + if not base_ref or base_ref == "0" * 40: + raise ValueError("workflow_dispatch requires a full immutable Flyway base SHA input") + else: + base_ref = args.base_ref or event_base_ref(event_path) + # All input paths use GitHub's all-zero sentinel for a new branch. + if base_ref == "0" * 40: + base_ref = None + parent = parent_snapshot(root, base_ref) if base_ref else None + issues, project_count, file_count = collect_issues(current_snapshot(root), parent) + except (ValueError, OSError, TypeError) as error: + print(f"Flyway migration sanity check failed: {error}", file=sys.stderr) + return 1 if issues: print("Flyway migration sanity check failed:", file=sys.stderr) for issue in issues: print(f"- {issue}", file=sys.stderr) return 1 - - print( - f"Flyway migration sanity check passed: {project_count} migration sets, {file_count} versioned files." - ) + if base_ref: + print(f"Flyway migration sanity check passed: {project_count} migration sets, {file_count} versioned files; parent {base_ref}.") + else: + print(f"Flyway duplicate-version check passed: {project_count} migration sets, {file_count} versioned files. " + "Parent frontier comparison and history preservation checks unavailable without --base-ref " + "or FIREMUD_FLYWAY_BASE_REF (or GitHub event base metadata).") return 0 diff --git a/dev-tools/verify-fresh-bootstrap.sh b/dev-tools/verify-fresh-bootstrap.sh index ceb429951b..493f667272 100644 --- a/dev-tools/verify-fresh-bootstrap.sh +++ b/dev-tools/verify-fresh-bootstrap.sh @@ -55,7 +55,7 @@ if [[ -n "$FIREMUD_SMOKE_COMPOSE_SERVICES" ]]; then fi done <<<"$FIREMUD_SMOKE_COMPOSE_SERVICES" else - if ! compose_services_output="$(FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only docker compose "${COMPOSE_FILES[@]}" config --services)"; then + if ! compose_services_output="$(FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH=/tmp/firemud-compose-authored-world-source-config-only docker compose "${COMPOSE_FILES[@]}" config --services)"; then echo "Docker Compose service discovery failed." >&2 exit 1 fi diff --git a/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql b/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql new file mode 100644 index 0000000000..3c33b4a44c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql @@ -0,0 +1,1510 @@ +-- Additive receiving Account admission and activation source protections after the canonical +-- capture (V158), World participation (V159), original attempt (V160), and independent source +-- fence (V160.1) owners. No predecessor, retained row, checksum, or owner identity is rewritten. +-- Complete original tuple projection and the independent nested issuance-operation identity +-- are installed directly; this migration never installs the superseded scalar projection guard. +-- These storage/integrity boundaries do not register runtime authority or authenticate producers. + +-- Distinct Account source protection through original Game Session admission. World +-- settlement and original-attempt observation expiry never settle this participation. +-- These integrity guards do not authenticate a producer or Game Session terminal RPC. +CREATE TABLE account_start_session_admission_protections ( + protection_id UUID PRIMARY KEY CHECK (protection_id <> '00000000-0000-0000-0000-000000000000'::UUID), + protection_fence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE CHECK (protection_fence > 0), + control_plane_request_id VARCHAR(128) NOT NULL UNIQUE + REFERENCES account_start_session_authority_captures(control_plane_request_id) ON DELETE RESTRICT, + original_post_authorization_tuple BYTEA NOT NULL CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + account_redemption_projection BYTEA NOT NULL CHECK (octet_length(account_redemption_projection) BETWEEN 1 AND 262144), + game_session_owner_mutation_id UUID NOT NULL UNIQUE CHECK (game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_attempt_id UUID NOT NULL CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + original_lease_expires_at TIMESTAMPTZ NOT NULL CHECK (isfinite(original_lease_expires_at)), + account_world_participation_id UUID NOT NULL UNIQUE + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + target_namespace VARCHAR(63) NOT NULL CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + canonical_tenant_id UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id) ON DELETE RESTRICT, + canonical_game_instance_id UUID NOT NULL CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + capture_source_version BIGINT NOT NULL CHECK (capture_source_version > 0), + capture_source_fence BIGINT NOT NULL CHECK (capture_source_fence > 0), + capture_sha256 VARCHAR(64) NOT NULL CHECK (capture_sha256 ~ '^[0-9a-f]{64}$'), + world_admission_hold_identity_bytes BYTEA NOT NULL CHECK (octet_length(world_admission_hold_identity_bytes) BETWEEN 1 AND 65536), + request_binding_bytes BYTEA NOT NULL CHECK (octet_length(request_binding_bytes) BETWEEN 1 AND 786432), + request_binding_digest VARCHAR(71) NOT NULL + CHECK (request_binding_digest = 'sha256:' || encode(sha256(request_binding_bytes), 'hex')), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE account_start_session_admission_protection_sources ( + protection_id UUID NOT NULL REFERENCES account_start_session_admission_protections(protection_id) ON DELETE RESTRICT, + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (protection_id, source_key) +); +CREATE INDEX account_ss_admission_sources_by_key + ON account_start_session_admission_protection_sources(source_key, protection_id); + +CREATE TABLE account_start_session_admission_protection_settlements ( + protection_id UUID PRIMARY KEY REFERENCES account_start_session_admission_protections(protection_id) ON DELETE RESTRICT, + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 25165824), + terminal_digest VARCHAR(71) NOT NULL CHECK (terminal_digest = 'sha256:' || encode(sha256(terminal_bytes), 'hex')), + settled_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_admission_is_settled(protection_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT EXISTS (SELECT 1 FROM account_start_session_admission_protection_settlements + WHERE protection_id = protection_value) +$$; + +-- Called only after the owning writer has locked its canonical source-key set. This +-- shared addition preserves the independently assembled World and other owner guards. +CREATE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; + +-- Acquisition and settlement require the same exact World hold before a source +-- protection can become pending. Return the only valid committed next pointer. +CREATE FUNCTION account_ss_admission_canonical_hold_next_pointer( + original account_start_session_admission_protections +) RETURNS NUMERIC LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + hold_json JSONB; + hold_request_json JSONB; + canonical_hold TEXT; + canonical_hold_request TEXT; + prior_pointer NUMERIC; +BEGIN + hold_json := convert_from(original.world_admission_hold_identity_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(hold_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_json)) <> 5 + OR NOT (hold_json ?& ARRAY['schema', 'holdId', 'holdFence', 'holdBindingDigest', 'requestBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(hold_json) field + WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR hold_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is malformed' + USING ERRCODE = '23514'; + END IF; + IF (hold_json->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR (hold_json->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR hold_json->>'holdId' IS DISTINCT FROM (hold_json->>'holdId')::UUID::TEXT + OR hold_json->>'holdFence' IS DISTINCT FROM (hold_json->>'holdFence')::UUID::TEXT THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is nil' + USING ERRCODE = '23514'; + END IF; + hold_request_json := convert_from(decode(hold_json->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + IF regexp_replace(encode(decode(hold_json->>'requestBytesBase64', 'base64'), 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM hold_json->>'requestBytesBase64' + OR hold_json->>'holdBindingDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(decode(hold_json->>'requestBytesBase64', 'base64')), 'hex') + OR jsonb_typeof(hold_request_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json)) <> 2 + OR NOT (hold_request_json ?& ARRAY['schema', 'request']) + OR hold_request_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR jsonb_typeof(hold_request_json->'request') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json->'request')) <> 14 + OR NOT (hold_request_json->'request' ?& ARRAY[ + 'activeLifecycleEpoch', 'canonicalGameInstanceId', 'canonicalTenantId', + 'canonicalVersionId', 'expectedCatalogRevision', 'expectedPriorPointerVersion', + 'initialAdmissionOrigin', 'initialAdmissionRequestDigest', + 'initialAdmissionRequestId', 'playableStateNamespaceId', 'playableStateScope', + 'realmId', 'targetNamespace', 'worldSlug']) + OR hold_request_json->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace + OR hold_request_json->'request'->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT + OR hold_request_json->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'Original StartSession admission hold request differs from retained protection' + USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT 1 FROM jsonb_each(hold_request_json->'request') field + WHERE field.key <> 'expectedPriorPointerVersion' + AND jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') NOT IN ('string', 'null') THEN + RAISE EXCEPTION 'Original StartSession hold request fields have invalid JSON types' + USING ERRCODE = '23514'; + END IF; + canonical_hold_request := '{"request":{"activeLifecycleEpoch":' + || to_json(hold_request_json->'request'->>'activeLifecycleEpoch')::TEXT + || ',"canonicalGameInstanceId":' + || to_json(hold_request_json->'request'->>'canonicalGameInstanceId')::TEXT + || ',"canonicalTenantId":' + || to_json(hold_request_json->'request'->>'canonicalTenantId')::TEXT + || ',"canonicalVersionId":' + || to_json(hold_request_json->'request'->>'canonicalVersionId')::TEXT + || ',"expectedCatalogRevision":' + || to_json(hold_request_json->'request'->>'expectedCatalogRevision')::TEXT + || ',"expectedPriorPointerVersion":' + || CASE + WHEN jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') = 'null' + THEN 'null' + ELSE to_json(hold_request_json->'request'->>'expectedPriorPointerVersion')::TEXT + END + || ',"initialAdmissionOrigin":' + || to_json(hold_request_json->'request'->>'initialAdmissionOrigin')::TEXT + || ',"initialAdmissionRequestDigest":' + || to_json(hold_request_json->'request'->>'initialAdmissionRequestDigest')::TEXT + || ',"initialAdmissionRequestId":' + || to_json(hold_request_json->'request'->>'initialAdmissionRequestId')::TEXT + || ',"playableStateNamespaceId":' + || to_json(hold_request_json->'request'->>'playableStateNamespaceId')::TEXT + || ',"playableStateScope":' + || to_json(hold_request_json->'request'->>'playableStateScope')::TEXT + || ',"realmId":' + || to_json(hold_request_json->'request'->>'realmId')::TEXT + || ',"targetNamespace":' + || to_json(hold_request_json->'request'->>'targetNamespace')::TEXT + || ',"worldSlug":' + || to_json(hold_request_json->'request'->>'worldSlug')::TEXT + || '},"schema":"world-canonical-initial-admission-hold-request/v1"}'; + IF convert_to(canonical_hold_request, 'UTF8') IS DISTINCT FROM + decode(hold_json->>'requestBytesBase64', 'base64') THEN + RAISE EXCEPTION 'Original StartSession hold request is not canonical JSON' + USING ERRCODE = '23514'; + END IF; + canonical_hold := '{"holdBindingDigest":"' || (hold_json->>'holdBindingDigest') + || '","holdFence":"' || (hold_json->>'holdFence') + || '","holdId":"' || (hold_json->>'holdId') + || '","requestBytesBase64":"' || (hold_json->>'requestBytesBase64') + || '","schema":"world-canonical-initial-admission-hold-identity/v1"}'; + IF convert_to(canonical_hold, 'UTF8') IS DISTINCT FROM original.world_admission_hold_identity_bytes THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is not canonical' + USING ERRCODE = '23514'; + END IF; + + IF hold_request_json->'request'->>'initialAdmissionOrigin' = 'NO_PRIOR_POINTER' + AND hold_request_json->'request'->'expectedPriorPointerVersion' = 'null'::JSONB THEN + RETURN 1; + ELSIF hold_request_json->'request'->>'initialAdmissionOrigin' = 'EXPECT_CLOSED' + AND jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') = 'string' + AND hold_request_json->'request'->>'expectedPriorPointerVersion' ~ '^[1-9][0-9]{0,18}$' THEN + prior_pointer := (hold_request_json->'request'->>'expectedPriorPointerVersion')::NUMERIC; + IF prior_pointer >= 9223372036854775807 THEN + RAISE EXCEPTION 'Original StartSession pointer version cannot advance without overflow' + USING ERRCODE = '23514'; + END IF; + RETURN prior_pointer + 1; + ELSE + RAISE EXCEPTION 'Original StartSession hold has an invalid pointer precondition' + USING ERRCODE = '23514'; + END IF; +END; +$$; + +-- Account currentness must independently reconstruct the exact live original actor, +-- registry, signer and source capture before invoking this integrity boundary. SQL +-- validates retained bindings; neither a capture nor a historical observation grants +-- admission, and a gap requires the producer's fresh unchanged-source validation. +CREATE FUNCTION account_ss_admission_assert_current( + original account_start_session_admission_protections, + require_complete BOOLEAN +) RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + capture account_start_session_authority_captures%ROWTYPE; + world_parent account_start_session_world_participations%ROWTYPE; + observation account_start_session_world_original_attempt_evidence%ROWTYPE; + authorization_row account_start_session_operator_authorizations%ROWTYPE; + snapshot_value JSONB; + tuple_value JSONB; + request_value JSONB; + projection_value JSONB; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + keys TEXT[]; + previous_sort_key INTEGER[]; + current_sort_key INTEGER[]; + source_bytes_total BIGINT := 0; + canonical_request TEXT; +BEGIN + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_value->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM original.control_plane_request_id THEN + RAISE EXCEPTION 'Admission protection requires the exact original source snapshot' USING ERRCODE = '23514'; + END IF; + IF octet_length(capture.canonical_capture_bytes) NOT BETWEEN 1 AND 262144 + OR octet_length(capture.canonical_snapshot_bytes) NOT BETWEEN 1 AND 245760 + OR jsonb_typeof(snapshot_value->'sourceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_value->'sourceVector') NOT BETWEEN 1 AND 256 THEN + RAISE EXCEPTION 'Admission protection source capture exceeds settlement bounds' USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + IF jsonb_typeof(source_value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Admission protection source vector has a non-string member' USING ERRCODE = '23514'; + END IF; + source_bytes := decode(source_value #>> '{}', 'base64'); + source_bytes_total := source_bytes_total + octet_length(source_bytes); + IF octet_length(source_bytes) NOT BETWEEN 1 AND 131072 + OR source_bytes_total > 4194304 + OR regexp_replace(encode(source_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM source_value #>> '{}' THEN + RAISE EXCEPTION 'Admission protection source vector exceeds canonical settlement bounds' USING ERRCODE = '23514'; + END IF; + current_sort_key := account_publication_authorization_source_sort_key( + account_start_session_world_participation_source_key(source_bytes)); + IF previous_sort_key IS NOT NULL AND current_sort_key <= previous_sort_key THEN + RAISE EXCEPTION 'Admission protection source vector is duplicated or out of order' USING ERRCODE = '23514'; + END IF; + previous_sort_key := current_sort_key; + END LOOP; + keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(keys, snapshot_value); + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT world_parent FROM account_start_session_world_participations + WHERE participation_id = original.account_world_participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT observation FROM account_start_session_world_original_attempt_evidence + WHERE participation_id = original.account_world_participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = original.control_plane_request_id FOR UPDATE NOWAIT; + PERFORM protection_id FROM account_start_session_admission_protections + WHERE protection_id = original.protection_id FOR UPDATE NOWAIT; + -- Always check actual database time after every lock, including exact recovery. + IF original.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() + OR account_ss_admission_is_settled(original.protection_id) THEN + RAISE EXCEPTION 'Original StartSession admission protection is not current' + USING ERRCODE = '23514'; + END IF; + IF capture.source_version IS DISTINCT FROM original.capture_source_version + OR capture.source_fence IS DISTINCT FROM original.capture_source_fence + OR capture.canonical_sha256 IS DISTINCT FROM original.capture_sha256 + OR world_parent.participation_fence IS DISTINCT FROM original.account_world_participation_fence + OR world_parent.control_plane_request_id IS DISTINCT FROM original.control_plane_request_id + OR world_parent.original_post_authorization_tuple IS DISTINCT FROM original.original_post_authorization_tuple + OR world_parent.game_session_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR world_parent.game_session_owner_fence IS DISTINCT FROM original.game_session_owner_fence + OR world_parent.target_namespace IS DISTINCT FROM original.target_namespace + OR world_parent.canonical_tenant_id IS DISTINCT FROM original.canonical_tenant_id + OR world_parent.canonical_game_instance_id IS DISTINCT FROM original.canonical_game_instance_id + OR observation.target_namespace IS DISTINCT FROM original.target_namespace + OR observation.game_session_owner_mutation_id IS DISTINCT FROM original.game_session_owner_mutation_id + OR observation.game_session_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR observation.game_session_owner_fence IS DISTINCT FROM original.game_session_owner_fence + OR observation.original_lease_expires_at IS DISTINCT FROM original.original_lease_expires_at + OR authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM original.game_session_owner_fence + OR authorization_row.redemption_reference_fingerprint IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR authorization_row.redemption_authority_evidence_bundle IS DISTINCT FROM authorization_row.authority_evidence_bundle + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization_row.pre_authorization_tuple + OR capture.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence THEN + RAISE EXCEPTION 'Original StartSession admission protection differs from its retained owner bindings' + USING ERRCODE = '23514'; + END IF; + tuple_value := convert_from(original.original_post_authorization_tuple, 'UTF8')::JSONB; + IF tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + OR tuple_value->>'authorizationReferenceFingerprint' IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization_row.issuance_fence::TEXT + OR tuple_value->'authorityEvidenceBundle' IS DISTINCT FROM convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB THEN + RAISE EXCEPTION 'Admission tuple differs from original Account issuance' USING ERRCODE = '23514'; + END IF; + projection_value := convert_from(original.account_redemption_projection, 'UTF8')::JSONB; + IF original.account_redemption_projection IS DISTINCT FROM original.original_post_authorization_tuple + OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}' + IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT THEN + RAISE EXCEPTION 'Admission projection differs from complete original Account redemption' USING ERRCODE = '23514'; + END IF; + request_value := convert_from(original.request_binding_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request_value) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Admission request binding is not an object' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 10 + OR EXISTS (SELECT 1 FROM jsonb_each(request_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR request_value->>'schema' IS DISTINCT FROM 'account-start-session-admission-protection-request/v1' + OR request_value->>'originalPostAuthorizationTupleBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g') + OR request_value->>'accountRedemptionProjectionBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.account_redemption_projection, 'base64'), E'[\n\r]', '', 'g') + OR request_value->>'gameSessionOwnerMutationId' IS DISTINCT FROM original.game_session_owner_mutation_id::TEXT + OR request_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM original.game_session_owner_attempt_id::TEXT + OR request_value->>'gameSessionOwnerFence' IS DISTINCT FROM original.game_session_owner_fence::TEXT + OR request_value->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR request_value->>'accountWorldParticipationId' IS DISTINCT FROM original.account_world_participation_id::TEXT + OR request_value->>'accountWorldParticipationFence' IS DISTINCT FROM original.account_world_participation_fence::TEXT + OR request_value->>'worldAdmissionHoldIdentityBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') THEN + RAISE EXCEPTION 'Admission request binding differs from exact immutable selectors' USING ERRCODE = '23514'; + END IF; + canonical_request := '{"accountRedemptionProjectionBytesBase64":"' + || regexp_replace(encode(original.account_redemption_projection, 'base64'), E'[\n\r]', '', 'g') + || '","accountWorldParticipationFence":"' + || original.account_world_participation_fence::TEXT + || '","accountWorldParticipationId":"' + || original.account_world_participation_id::TEXT + || '","gameSessionOwnerAttemptId":"' + || original.game_session_owner_attempt_id::TEXT + || '","gameSessionOwnerFence":"' + || original.game_session_owner_fence::TEXT + || '","gameSessionOwnerMutationId":"' + || original.game_session_owner_mutation_id::TEXT + || '","originalLeaseExpiresAt":"' + || to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + || '","originalPostAuthorizationTupleBytesBase64":"' + || regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g') + || '","schema":"account-start-session-admission-protection-request/v1"' + || ',"worldAdmissionHoldIdentityBytesBase64":"' + || regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') + || '"}'; + IF octet_length(original.request_binding_bytes) NOT BETWEEN 1 AND 786432 + OR octet_length(original.world_admission_hold_identity_bytes) NOT BETWEEN 1 AND 65536 + OR convert_to(canonical_request, 'UTF8') IS DISTINCT FROM original.request_binding_bytes + OR original.request_binding_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(original.request_binding_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession admission request is not its exact canonical binding' + USING ERRCODE = '23514'; + END IF; + + PERFORM account_ss_admission_canonical_hold_next_pointer(original); + -- Original World source children remain immutable even when World has settled. + PERFORM account_start_session_world_participation_assert_sources(world_parent.participation_id, snapshot_value); + IF require_complete THEN + IF (SELECT count(*) FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id) <> jsonb_array_length(snapshot_value->'sourceVector') THEN + RAISE EXCEPTION 'Admission protection has incomplete or extra source children' USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + source_bytes := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(source_bytes); + IF NOT EXISTS (SELECT 1 FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id AND source_key = source_key_value + AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Admission source child differs from complete original capture' USING ERRCODE = '23514'; + END IF; + END LOOP; + END IF; + IF original.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession admission expiry elapsed during integrity validation' USING ERRCODE = '23514'; + END IF; +END; +$$; + +CREATE FUNCTION account_ss_admission_read_current_exact(protection_value UUID, fence_value BIGINT, request_value BYTEA) +RETURNS SETOF account_start_session_admission_protections LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE original account_start_session_admission_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_admission_protections + WHERE protection_id = protection_value AND protection_fence = fence_value; + IF original.request_binding_bytes IS DISTINCT FROM request_value THEN + RAISE EXCEPTION 'Original admission recovery binding differs' USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_admission_assert_current(original, TRUE); + RETURN NEXT original; +END; +$$; + +CREATE FUNCTION account_ss_admission_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'Admission protection must be created by its producer transaction' USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_admission_assert_current(NEW::account_start_session_admission_protections, FALSE); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_admission_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE producer BIGINT; +BEGIN + SELECT producer_xid INTO STRICT producer FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + IF producer IS DISTINCT FROM txid_current() + OR account_start_session_world_participation_source_key(NEW.source_evidence) IS DISTINCT FROM NEW.source_key THEN + RAISE EXCEPTION 'Admission sources must be exact same-producer children' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_admission_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE original account_start_session_admission_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + PERFORM account_ss_admission_assert_current(original, TRUE); + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_ss_admission_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession admission evidence is append-only' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_admission_validate BEFORE INSERT ON account_start_session_admission_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_insert_guard(); +CREATE TRIGGER account_ss_admission_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protections + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_sources_validate BEFORE INSERT ON account_start_session_admission_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_source_insert_guard(); +CREATE TRIGGER account_ss_admission_sources_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_sources_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protection_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE CONSTRAINT TRIGGER account_ss_admission_complete AFTER INSERT ON account_start_session_admission_protections + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_ss_admission_complete_guard(); +CREATE TRIGGER account_ss_admission_settlements_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +-- The authenticated exact Game Session terminal API is not yet composed. Reject every +-- settlement insertion until its sealed complete terminal binding guard replaces this +-- unpublished gate. An outcome assertion alone can never release source protection. +CREATE TRIGGER account_ss_admission_settlements_disabled BEFORE INSERT ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_settlements_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protection_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_draft_authorization_sources s$anchor$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled admission source-writer anchor'; + END IF; + EXECUTE replace(original, anchor, + E' PERFORM account_ss_admission_assert_no_pending(source_keys);\n' || anchor); +END; +$migration$; + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ FOR operation IN SELECT DISTINCT source.operation_id + FROM account_draft_authorization_changed_scopes changed$anchor$; +BEGIN + SELECT pg_get_functiondef('account_draft_authorization_source_change_guard()'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled admission source-change anchor'; + END IF; + EXECUTE replace(original, anchor, $guard$ PERFORM account_ss_admission_assert_no_pending( + ARRAY(SELECT source_key FROM account_draft_authorization_changed_scopes + WHERE change_id = OLD.change_id)); +$guard$ || anchor); +END; +$migration$; + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED'$anchor$; +BEGIN + SELECT pg_get_functiondef('account_hosted_terms_disclosure_handoff_guard()'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled admission disclosure anchor'; + END IF; + EXECUTE replace(original, anchor, $guard$ IF OLD.status IN ('PREPARED', 'AMBIGUOUS') AND NEW.status = 'DISPATCH_AUTHORIZED' THEN + PERFORM source_lock.source_key FROM account_draft_authorization_source_locks source_lock + JOIN (SELECT OLD.source_key AS source_key UNION + SELECT source_key FROM account_hosted_terms_disclosure_sources + WHERE handoff_id = OLD.handoff_id) exact_source USING (source_key) + ORDER BY account_publication_authorization_source_sort_key(source_lock.source_key) + FOR UPDATE OF source_lock NOWAIT; + PERFORM account_ss_admission_assert_no_pending(ARRAY( + SELECT OLD.source_key UNION SELECT source_key FROM account_hosted_terms_disclosure_sources + WHERE handoff_id = OLD.handoff_id)); + END IF; +$guard$ || anchor); +END; +$migration$; +-- [jooq ignore end] + + +-- Immutable Account settlement for the exact original Game Session admission proof. +-- This guard validates retained structure and integrity only. It does not authenticate +-- the remote producer; the internal Game Session client owns that provenance boundary. +-- [jooq ignore start] +CREATE FUNCTION account_ss_admission_settlement_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_admission_protections%ROWTYPE; + capture account_start_session_authority_captures%ROWTYPE; + existing account_start_session_admission_protection_settlements%ROWTYPE; + terminal_json JSONB; + evidence_json JSONB; + snapshot_json JSONB; + evidence_bytes BYTEA; + owner_proof_bytes BYTEA; + canonical_outer TEXT; + canonical_evidence TEXT; + canonical_request TEXT; + source_vector TEXT; + source_count BIGINT; + source_bytes_total BIGINT; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + previous_sort_key INTEGER[]; + current_sort_key INTEGER[]; + position_value INTEGER := 1; + frame_next_position INTEGER; + parsed BYTEA; + marker TEXT; + proof_schema TEXT; + proof_hold_bytes BYTEA; + proof_outcome TEXT; + pointer_marker TEXT; + pointer_text TEXT; + audit_marker TEXT; + audit_text TEXT; + digest_marker TEXT; + proof_digest TEXT; + abort_value TEXT; + terminal_marker TEXT; + terminal_at_text TEXT; + terminal_stem TEXT; + expected_pointer NUMERIC; +BEGIN + SELECT * INTO STRICT original + FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + + IF NEW.outcome NOT IN ('COMMITTED', 'ABORTED') + OR NEW.terminal_bytes IS NULL + OR octet_length(NEW.terminal_bytes) NOT BETWEEN 1 AND 25165824 + OR NEW.terminal_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') THEN + RAISE EXCEPTION 'Malformed original StartSession admission settlement' + USING ERRCODE = '23514'; + END IF; + + -- Reconstructing the complete outer object makes duplicate keys, alternate escaping, + -- trailing input, and non-RFC8785 ordering fail byte-for-byte. + terminal_json := convert_from(NEW.terminal_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(terminal_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(terminal_json)) <> 3 + OR NOT (terminal_json ?& ARRAY[ + 'schema', 'canonicalAccountProtectionEvidenceBytesBase64', + 'canonicalGameSessionOwnerProofBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(terminal_json) field + WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR terminal_json->>'schema' IS DISTINCT FROM + 'account-start-session-admission-protection-settlement/v1' THEN + RAISE EXCEPTION 'Original StartSession admission settlement is not the closed envelope' + USING ERRCODE = '23514'; + END IF; + evidence_bytes := decode(terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64', 'base64'); + owner_proof_bytes := decode(terminal_json->>'canonicalGameSessionOwnerProofBytesBase64', 'base64'); + IF octet_length(evidence_bytes) NOT BETWEEN 1 AND 8388608 + OR octet_length(owner_proof_bytes) NOT BETWEEN 1 AND 66048 + OR regexp_replace(encode(evidence_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64' + OR regexp_replace(encode(owner_proof_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM terminal_json->>'canonicalGameSessionOwnerProofBytesBase64' THEN + RAISE EXCEPTION 'Original StartSession admission settlement has invalid canonical Base64' + USING ERRCODE = '23514'; + END IF; + canonical_outer := '{"canonicalAccountProtectionEvidenceBytesBase64":"' + || (terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64') + || '","canonicalGameSessionOwnerProofBytesBase64":"' + || (terminal_json->>'canonicalGameSessionOwnerProofBytesBase64') + || '","schema":"account-start-session-admission-protection-settlement/v1"}'; + IF convert_to(canonical_outer, 'UTF8') IS DISTINCT FROM NEW.terminal_bytes THEN + RAISE EXCEPTION 'Original StartSession admission settlement is not canonical JSON' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT capture + FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id; + IF capture.source_version IS DISTINCT FROM original.capture_source_version + OR capture.source_fence IS DISTINCT FROM original.capture_source_fence + OR capture.canonical_sha256 IS DISTINCT FROM original.capture_sha256 + OR octet_length(capture.canonical_capture_bytes) NOT BETWEEN 1 AND 262144 + OR octet_length(capture.canonical_snapshot_bytes) NOT BETWEEN 1 AND 245760 + OR capture.canonical_sha256 IS DISTINCT FROM + encode(sha256(capture.canonical_capture_bytes), 'hex') + OR capture.snapshot_sha256 IS DISTINCT FROM + encode(sha256(capture.canonical_snapshot_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession admission capture differs from retained protection' + USING ERRCODE = '23514'; + END IF; + + -- The immutable Account request is a closed ten-string object. Rebuild its canonical + -- representation from the retained parent so the settlement cannot bind a projection. + canonical_request := '{"accountRedemptionProjectionBytesBase64":"' + || regexp_replace(encode(original.account_redemption_projection, 'base64'), E'[\n\r]', '', 'g') + || '","accountWorldParticipationFence":"' + || original.account_world_participation_fence::TEXT + || '","accountWorldParticipationId":"' + || original.account_world_participation_id::TEXT + || '","gameSessionOwnerAttemptId":"' + || original.game_session_owner_attempt_id::TEXT + || '","gameSessionOwnerFence":"' + || original.game_session_owner_fence::TEXT + || '","gameSessionOwnerMutationId":"' + || original.game_session_owner_mutation_id::TEXT + || '","originalLeaseExpiresAt":"' + || to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + || '","originalPostAuthorizationTupleBytesBase64":"' + || regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g') + || '","schema":"account-start-session-admission-protection-request/v1"' + || ',"worldAdmissionHoldIdentityBytesBase64":"' + || regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') + || '"}'; + IF octet_length(original.request_binding_bytes) NOT BETWEEN 1 AND 786432 + OR octet_length(original.world_admission_hold_identity_bytes) NOT BETWEEN 1 AND 65536 + OR convert_to(canonical_request, 'UTF8') IS DISTINCT FROM original.request_binding_bytes + OR original.request_binding_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(original.request_binding_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession admission request is not its exact canonical binding' + USING ERRCODE = '23514'; + END IF; + + snapshot_json := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_json->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_json->>'controlPlaneRequestId' IS DISTINCT FROM original.control_plane_request_id + OR jsonb_typeof(snapshot_json->'sourceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_json->'sourceVector') NOT BETWEEN 1 AND 256 THEN + RAISE EXCEPTION 'Original StartSession admission source capture is incomplete' + USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO source_count + FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id; + SELECT COALESCE(sum(octet_length(source_evidence)), 0) INTO source_bytes_total + FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id; + IF source_count IS DISTINCT FROM jsonb_array_length(snapshot_json->'sourceVector')::BIGINT + OR source_bytes_total > 4194304 THEN + RAISE EXCEPTION 'Original StartSession admission source children are incomplete' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_json->'sourceVector') LOOP + IF jsonb_typeof(source_value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Original StartSession source vector has a non-string member' + USING ERRCODE = '23514'; + END IF; + source_bytes := decode(source_value #>> '{}', 'base64'); + IF octet_length(source_bytes) NOT BETWEEN 1 AND 131072 + OR regexp_replace(encode(source_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM source_value #>> '{}' THEN + RAISE EXCEPTION 'Original StartSession source vector has noncanonical bytes' + USING ERRCODE = '23514'; + END IF; + source_key_value := account_start_session_world_participation_source_key(source_bytes); + current_sort_key := account_publication_authorization_source_sort_key(source_key_value); + IF previous_sort_key IS NOT NULL AND current_sort_key <= previous_sort_key THEN + RAISE EXCEPTION 'Original StartSession source vector is duplicated or out of order' + USING ERRCODE = '23514'; + END IF; + previous_sort_key := current_sort_key; + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_admission_protection_sources source + WHERE source.protection_id = original.protection_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Original StartSession source child differs from its immutable capture' + USING ERRCODE = '23514'; + END IF; + END LOOP; + + SELECT string_agg( + '"' || regexp_replace(encode(source.source_evidence, 'base64'), E'[\n\r]', '', 'g') || '"', + ',' ORDER BY account_publication_authorization_source_sort_key(source.source_key)) + INTO source_vector + FROM account_start_session_admission_protection_sources source + WHERE source.protection_id = original.protection_id; + canonical_evidence := '{"accountProtectionFence":"' || original.protection_fence::TEXT + || '","accountProtectionId":"' || original.protection_id::TEXT + || '","originalSourceCaptureReferenceBytesBase64":"' + || regexp_replace(encode(capture.canonical_capture_bytes, 'base64'), E'[\n\r]', '', 'g') + || '","originalSourceCaptureReferenceSha256":"' || capture.canonical_sha256 + || '","requestBytesBase64":"' + || regexp_replace(encode(original.request_binding_bytes, 'base64'), E'[\n\r]', '', 'g') + || '","schema":"account-start-session-admission-protection-evidence/v1"' + || ',"sourceEvidenceVector":[' || source_vector || ']}'; + IF convert_to(canonical_evidence, 'UTF8') IS DISTINCT FROM evidence_bytes THEN + RAISE EXCEPTION 'Original StartSession admission evidence differs from its full retained binding' + USING ERRCODE = '23514'; + END IF; + + expected_pointer := account_ss_admission_canonical_hold_next_pointer(original); + + -- The actual Game Session codec frames the hold and seven terminal fields. Do not treat + -- its opaque terminal proof digest as permission; only the exact COMMITTED/ABORTED shape + -- below may settle this immutable Account binding. + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + proof_schema := convert_from(parsed, 'UTF8'); + position_value := frame_next_position; + SELECT frame.frame_value, frame.next_position INTO proof_hold_bytes, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + proof_outcome := convert_from(parsed, 'UTF8'); + + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + pointer_marker := convert_from(parsed, 'UTF8'); + IF pointer_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + pointer_text := convert_from(parsed, 'UTF8'); + ELSIF pointer_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal pointer frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + audit_marker := convert_from(parsed, 'UTF8'); + IF audit_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + audit_text := convert_from(parsed, 'UTF8'); + ELSIF audit_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal audit frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + digest_marker := convert_from(parsed, 'UTF8'); + IF digest_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + proof_digest := convert_from(parsed, 'UTF8'); + ELSIF digest_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal digest frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + abort_value := convert_from(parsed, 'UTF8'); + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + terminal_marker := convert_from(parsed, 'UTF8'); + IF terminal_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + terminal_at_text := convert_from(parsed, 'UTF8'); + ELSIF terminal_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal timestamp frame is malformed' USING ERRCODE = '23514'; + END IF; + IF position_value <> octet_length(owner_proof_bytes) + 1 + OR proof_schema IS DISTINCT FROM 'game-session-canonical-initial-admission-owner-proof/v1' + OR proof_hold_bytes IS DISTINCT FROM original.world_admission_hold_identity_bytes + OR proof_digest IS NULL OR proof_digest !~ '^sha256:[0-9a-f]{64}$' + OR terminal_at_text IS NULL + OR terminal_at_text !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{3}|\.[0-9]{6}|\.[0-9]{9})?Z$' + OR terminal_at_text ~ '\.000Z$' + OR terminal_at_text ~ '\.[0-9]{3}000Z$' + OR terminal_at_text ~ '\.[0-9]{6}000Z$' + OR abort_value NOT IN ('true', 'false') THEN + RAISE EXCEPTION 'Original StartSession owner proof is malformed or differs from its hold' + USING ERRCODE = '23514'; + END IF; + -- Validate the calendar/time stem separately. Casting the complete fraction to + -- TIMESTAMPTZ would round nanoseconds to PostgreSQL microseconds and could silently + -- accept noncanonical Java Instant text; the exact frame bytes remain authoritative. + terminal_stem := to_char( + substring(terminal_at_text FROM 1 FOR 19)::TIMESTAMP WITHOUT TIME ZONE, + 'YYYY-MM-DD"T"HH24:MI:SS'); + IF terminal_stem IS DISTINCT FROM substring(terminal_at_text FROM 1 FOR 19) THEN + RAISE EXCEPTION 'Original StartSession owner proof timestamp stem is not normalized' + USING ERRCODE = '23514'; + END IF; + IF proof_outcome = 'COMMITTED' THEN + IF pointer_marker IS DISTINCT FROM 'PRESENT' + OR pointer_text IS NULL OR pointer_text !~ '^[1-9][0-9]{0,18}$' + OR audit_marker IS DISTINCT FROM 'PRESENT' + OR audit_text IS NULL OR audit_text !~ '^[1-9][0-9]{0,18}$' + OR abort_value IS DISTINCT FROM 'false' THEN + RAISE EXCEPTION 'Committed Game Session terminal proof has invalid outcome fields' + USING ERRCODE = '23514'; + END IF; + IF pointer_text::NUMERIC IS DISTINCT FROM expected_pointer THEN + RAISE EXCEPTION 'Committed Game Session terminal proof does not name the exact next pointer' + USING ERRCODE = '23514'; + END IF; + PERFORM audit_text::BIGINT; + IF NEW.outcome IS DISTINCT FROM 'COMMITTED' THEN + RAISE EXCEPTION 'Account settlement outcome differs from Game Session owner proof' + USING ERRCODE = '23514'; + END IF; + ELSIF proof_outcome = 'ABORTED' THEN + IF pointer_marker IS DISTINCT FROM 'ABSENT' + OR audit_marker IS DISTINCT FROM 'ABSENT' + OR abort_value IS DISTINCT FROM 'true' + OR NEW.outcome IS DISTINCT FROM 'ABORTED' THEN + RAISE EXCEPTION 'Aborted Game Session terminal proof lacks positive durable exclusion' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'Pending or unsupported Game Session owner proof cannot settle protection' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO existing + FROM account_start_session_admission_protection_settlements + WHERE protection_id = NEW.protection_id; + IF FOUND AND (existing.outcome IS DISTINCT FROM NEW.outcome + OR existing.terminal_bytes IS DISTINCT FROM NEW.terminal_bytes + OR existing.terminal_digest IS DISTINCT FROM NEW.terminal_digest) THEN + RAISE EXCEPTION 'Original StartSession admission terminal settlement conflicts with its first receipt' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +DROP TRIGGER account_ss_admission_settlements_disabled + ON account_start_session_admission_protection_settlements; +CREATE TRIGGER account_ss_admission_settlements_validate + BEFORE INSERT ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_settlement_insert_guard(); +-- [jooq ignore end] + + +-- Distinct Account-owned source protection through the exact original World activation. +-- This is immutable storage only: it authenticates no owner and has no release or +-- settlement path. A future exact ACTIVE/ABORTED terminal contract must add that separately. +CREATE TABLE account_start_session_activation_protections ( + activation_protection_id UUID PRIMARY KEY DEFAULT gen_random_uuid() + CHECK (activation_protection_id <> '00000000-0000-0000-0000-000000000000'::UUID), + activation_protection_fence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE + CHECK (activation_protection_fence > 0), + control_plane_request_id VARCHAR(128) NOT NULL UNIQUE + REFERENCES account_start_session_authority_captures(control_plane_request_id) ON DELETE RESTRICT, + account_world_participation_id UUID NOT NULL UNIQUE + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + original_post_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + account_redemption_projection BYTEA NOT NULL + CHECK (octet_length(account_redemption_projection) BETWEEN 1 AND 262144), + game_session_owner_mutation_id UUID NOT NULL UNIQUE + CHECK (game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_attempt_id UUID NOT NULL + CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + original_lease_expires_at TIMESTAMPTZ NOT NULL CHECK (isfinite(original_lease_expires_at)), + target_namespace VARCHAR(63) NOT NULL + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + canonical_tenant_id UUID NOT NULL + REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id) ON DELETE RESTRICT, + canonical_game_instance_id UUID NOT NULL + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + world_activation_request_id UUID NOT NULL + CHECK (world_activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_launch_read_evidence BYTEA NOT NULL + CHECK (octet_length(game_session_launch_read_evidence) BETWEEN 1 AND 42991616), + world_preparing_evidence BYTEA NOT NULL + CHECK (octet_length(world_preparing_evidence) BETWEEN 1 AND 67108864), + capture_source_version BIGINT NOT NULL CHECK (capture_source_version > 0), + capture_source_fence BIGINT NOT NULL CHECK (capture_source_fence > 0), + capture_sha256 VARCHAR(64) NOT NULL CHECK (capture_sha256 ~ '^[0-9a-f]{64}$'), + capture_reference_bytes BYTEA NOT NULL + CHECK (octet_length(capture_reference_bytes) BETWEEN 1 AND 262144), + capture_reference_sha256 VARCHAR(64) NOT NULL + CHECK (capture_reference_sha256 ~ '^[0-9a-f]{64}$'), + operation_identity_bytes BYTEA NOT NULL + CHECK (octet_length(operation_identity_bytes) BETWEEN 1 AND 150994944), + operation_identity_digest VARCHAR(71) NOT NULL UNIQUE + CHECK (operation_identity_digest = 'sha256:' || encode(sha256(operation_identity_bytes), 'hex')), + request_binding_bytes BYTEA NOT NULL + CHECK (octet_length(request_binding_bytes) BETWEEN 1 AND 150994944), + request_binding_digest VARCHAR(71) NOT NULL + CHECK (request_binding_digest = 'sha256:' || encode(sha256(request_binding_bytes), 'hex')), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + acquired_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK (isfinite(acquired_at) AND acquired_at < original_lease_expires_at), + CHECK (capture_sha256 = capture_reference_sha256) +); + +CREATE TABLE account_start_session_activation_protection_sources ( + activation_protection_id UUID NOT NULL + REFERENCES account_start_session_activation_protections(activation_protection_id) ON DELETE RESTRICT, + source_key VARCHAR(2048) NOT NULL + CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048) + REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (activation_protection_id, source_key) +); +CREATE INDEX account_ss_activation_sources_by_key + ON account_start_session_activation_protection_sources(source_key, activation_protection_id); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_activation_assert_current( + request_bytes BYTEA, + operation_bytes BYTEA, + operation_digest TEXT, + require_complete BOOLEAN +) RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + capture account_start_session_authority_captures%ROWTYPE; + world_parent account_start_session_world_participations%ROWTYPE; + observation account_start_session_world_original_attempt_evidence%ROWTYPE; + authorization_row account_start_session_operator_authorizations%ROWTYPE; + retained account_start_session_activation_protections%ROWTYPE; + snapshot_value JSONB; + request_value JSONB; + tuple_value JSONB; + projection_value JSONB; + preparing_value JSONB; + preparing_request JSONB; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + tuple_bytes BYTEA; + projection_bytes BYTEA; + preparing_bytes BYTEA; + control_request_id TEXT; + requested_participation_id UUID; + keys TEXT[]; + retained_found BOOLEAN := FALSE; +BEGIN + IF octet_length(request_bytes) NOT BETWEEN 1 AND 150994944 + OR octet_length(operation_bytes) NOT BETWEEN 1 AND 150994944 + OR operation_digest IS DISTINCT FROM 'sha256:' || encode(sha256(operation_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession activation request or operation identity is invalid' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(request_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request_value) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 12 + OR NOT (request_value ?& ARRAY[ + 'schema', 'originalPostAuthorizationTupleBytesBase64', + 'accountRedemptionProjectionBytesBase64', 'gameSessionOwnerMutationId', + 'gameSessionOwnerAttemptId', 'gameSessionOwnerFence', 'originalLeaseExpiresAt', + 'accountWorldParticipationId', 'accountWorldParticipationFence', + 'gameSessionLaunchReadEvidenceBytesBase64', 'worldActivationRequestId', + 'preparingEvidenceBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(request_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR request_value->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' THEN + RAISE EXCEPTION 'Original StartSession activation request has an unsupported shape' + USING ERRCODE = '23514'; + END IF; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + tuple_value := convert_from(tuple_bytes, 'UTF8')::JSONB; + control_request_id := tuple_value->>'controlPlaneRequestId'; + requested_participation_id := (request_value->>'accountWorldParticipationId')::UUID; + + -- Source-key locks are acquired in the canonical V129 order before any retained owner, + -- World or activation-protection row is locked. + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_value->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM control_request_id THEN + RAISE EXCEPTION 'Activation protection requires the exact original Account source snapshot' + USING ERRCODE = '23514'; + END IF; + keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(keys, snapshot_value); + + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT world_parent FROM account_start_session_world_participations + WHERE account_start_session_world_participations.participation_id = requested_participation_id + FOR UPDATE NOWAIT; + SELECT * INTO STRICT observation FROM account_start_session_world_original_attempt_evidence + WHERE participation_id = world_parent.participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO retained FROM account_start_session_activation_protections + WHERE account_start_session_activation_protections.control_plane_request_id = control_request_id + FOR UPDATE NOWAIT; + retained_found := FOUND; + + preparing_value := convert_from(preparing_bytes, 'UTF8')::JSONB; + preparing_request := preparing_value->'request'; + projection_value := convert_from(projection_bytes, 'UTF8')::JSONB; + IF request_value->>'gameSessionOwnerMutationId' IS DISTINCT FROM observation.game_session_owner_mutation_id::TEXT + OR request_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM observation.game_session_owner_attempt_id::TEXT + OR request_value->>'gameSessionOwnerFence' IS DISTINCT FROM observation.game_session_owner_fence::TEXT + OR request_value->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(observation.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR request_value->>'accountWorldParticipationId' IS DISTINCT FROM world_parent.participation_id::TEXT + OR request_value->>'accountWorldParticipationFence' IS DISTINCT FROM world_parent.participation_fence::TEXT + OR world_parent.control_plane_request_id IS DISTINCT FROM control_request_id + OR world_parent.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR world_parent.game_session_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR world_parent.game_session_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + OR observation.target_namespace IS DISTINCT FROM world_parent.target_namespace + OR NOT EXISTS ( + SELECT 1 FROM account_start_session_world_participation_settlements settlement + WHERE settlement.participation_id = world_parent.participation_id + AND settlement.outcome = 'COMMITTED') + OR preparing_value->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR preparing_value->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR preparing_request->>'controlPlaneRequestId' IS DISTINCT FROM control_request_id + OR preparing_request->>'targetNamespace' IS DISTINCT FROM world_parent.target_namespace + OR preparing_request->>'canonicalTenantId' IS DISTINCT FROM world_parent.canonical_tenant_id::TEXT + OR preparing_request->>'canonicalGameInstanceId' IS DISTINCT FROM world_parent.canonical_game_instance_id::TEXT + OR capture.source_version <= 0 OR capture.source_fence <= 0 THEN + RAISE EXCEPTION 'Activation protection differs from committed original World preparation or attempt' + USING ERRCODE = '23514'; + END IF; + + -- Retain the original Account issuance/redemption tuple and complete projection exactly. + IF capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') + OR capture.snapshot_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_snapshot_bytes), 'hex') + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization_row.pre_authorization_tuple + OR capture.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence + OR authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + OR authorization_row.redemption_reference_fingerprint IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR authorization_row.redemption_authority_evidence_bundle IS DISTINCT FROM authorization_row.authority_evidence_bundle + OR tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + OR tuple_value->>'authorizationReferenceFingerprint' IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization_row.issuance_fence::TEXT + OR tuple_value->'authorityEvidenceBundle' IS DISTINCT FROM convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB + OR projection_bytes IS DISTINCT FROM tuple_bytes + OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}' + IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT + OR capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection differs from original Account redemption or capture' + USING ERRCODE = '23514'; + END IF; + + IF retained_found AND ( + retained.operation_identity_bytes IS DISTINCT FROM operation_bytes + OR retained.operation_identity_digest IS DISTINCT FROM operation_digest + OR retained.account_world_participation_id IS DISTINCT FROM world_parent.participation_id + OR retained.account_world_participation_fence IS DISTINCT FROM world_parent.participation_fence) THEN + RAISE EXCEPTION 'Original StartSession activation protection conflicts with its immutable binding' + USING ERRCODE = '23514'; + END IF; + + -- The typed Common carrier validates the closed Game Session STARTING result and exact + -- World PREPARING evidence. SQL independently checks finite original authority only after + -- all canonical source and owner/protection row locks have completed. + IF observation.original_lease_expires_at IS DISTINCT FROM + (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR observation.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession activation protection lease is stale or expired' + USING ERRCODE = '23514'; + END IF; + + PERFORM account_start_session_world_participation_assert_sources(world_parent.participation_id, snapshot_value); + IF require_complete THEN + IF (SELECT count(*) FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id) + <> jsonb_array_length(snapshot_value->'sourceVector') THEN + RAISE EXCEPTION 'Activation protection has incomplete or extra source children' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + source_bytes := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(source_bytes); + IF NOT EXISTS (SELECT 1 FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id + AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Activation protection source child differs from original capture' + USING ERRCODE = '23514'; + END IF; + END LOOP; + END IF; +END; +$$; + +CREATE FUNCTION account_ss_activation_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + request_value JSONB; + tuple_bytes BYTEA; + projection_bytes BYTEA; + launch_bytes BYTEA; + preparing_bytes BYTEA; +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() + OR NEW.capture_sha256 IS DISTINCT FROM encode(sha256(NEW.capture_reference_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection must retain its producer capture transaction and digest' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(NEW.request_binding_bytes, 'UTF8')::JSONB; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + launch_bytes := decode(request_value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + IF NEW.control_plane_request_id IS DISTINCT FROM + (convert_from(tuple_bytes, 'UTF8')::JSONB->>'controlPlaneRequestId') + OR NEW.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR NEW.account_redemption_projection IS DISTINCT FROM projection_bytes + OR NEW.game_session_owner_mutation_id IS DISTINCT FROM (request_value->>'gameSessionOwnerMutationId')::UUID + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM (request_value->>'gameSessionOwnerAttemptId')::UUID + OR NEW.game_session_owner_fence IS DISTINCT FROM (request_value->>'gameSessionOwnerFence')::BIGINT + OR NEW.original_lease_expires_at IS DISTINCT FROM (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR NEW.account_world_participation_id IS DISTINCT FROM (request_value->>'accountWorldParticipationId')::UUID + OR NEW.account_world_participation_fence IS DISTINCT FROM (request_value->>'accountWorldParticipationFence')::BIGINT + OR NEW.world_activation_request_id IS DISTINCT FROM (request_value->>'worldActivationRequestId')::UUID + OR NEW.game_session_launch_read_evidence IS DISTINCT FROM launch_bytes + OR NEW.world_preparing_evidence IS DISTINCT FROM preparing_bytes + OR NEW.request_binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.request_binding_bytes), 'hex') + OR NEW.operation_identity_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.operation_identity_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection does not retain its exact canonical request fields' + USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_activation_assert_current( + NEW.request_binding_bytes, NEW.operation_identity_bytes, NEW.operation_identity_digest, FALSE); + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_authority_captures capture + WHERE capture.control_plane_request_id = NEW.control_plane_request_id + AND capture.source_version = NEW.capture_source_version + AND capture.source_fence = NEW.capture_source_fence + AND capture.canonical_sha256 = NEW.capture_sha256 + AND capture.canonical_capture_bytes = NEW.capture_reference_bytes + AND NEW.target_namespace = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'targetNamespace') + AND NEW.canonical_tenant_id = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'tenantId')::UUID + AND NEW.canonical_game_instance_id = (convert_from(preparing_bytes, 'UTF8')::JSONB + ->'request'->>'canonicalGameInstanceId')::UUID + AND NEW.capture_reference_sha256 = encode(sha256(NEW.capture_reference_bytes), 'hex')) THEN + RAISE EXCEPTION 'Activation protection capture or target differs from the exact current request' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE producer BIGINT; +BEGIN + SELECT producer_xid INTO STRICT producer FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + IF producer IS DISTINCT FROM txid_current() + OR account_start_session_world_participation_source_key(NEW.source_evidence) IS DISTINCT FROM NEW.source_key THEN + RAISE EXCEPTION 'Activation protection sources must be exact same-producer children' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE original account_start_session_activation_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + PERFORM account_ss_activation_assert_current( + original.request_binding_bytes, original.operation_identity_bytes, + original.operation_identity_digest, TRUE); + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_ss_activation_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation protection is immutable and has no settlement path' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_activation_validate BEFORE INSERT ON account_start_session_activation_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_insert_guard(); +CREATE TRIGGER account_ss_activation_immutable BEFORE UPDATE OR DELETE ON account_start_session_activation_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_no_truncate BEFORE TRUNCATE ON account_start_session_activation_protections + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_sources_validate BEFORE INSERT ON account_start_session_activation_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_source_insert_guard(); +CREATE TRIGGER account_ss_activation_sources_immutable BEFORE UPDATE OR DELETE ON account_start_session_activation_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_sources_no_truncate BEFORE TRUNCATE ON account_start_session_activation_protection_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE CONSTRAINT TRIGGER account_ss_activation_complete AFTER INSERT ON account_start_session_activation_protections + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_ss_activation_complete_guard(); + +-- Existing assembled source-writer guards call this helper after locking their canonical +-- source keys. Keep every admission check installed above and add the permanently pending activation rows. +CREATE OR REPLACE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; + PERFORM protection.activation_protection_id + FROM account_start_session_activation_protections protection + JOIN account_start_session_activation_protection_sources source + ON source.activation_protection_id = protection.activation_protection_id + WHERE source.source_key = ANY(source_keys) + ORDER BY protection.activation_protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession activation protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; +-- [jooq ignore end] + + +-- Append-only resolution of the distinct original StartSession activation source protection. +-- Only an exact authenticated World ACTIVE or fenced ABORTED terminal receipt may be recorded; +-- expiry, missing World state, timeout, generic close, and absence are not terminal outcomes. +CREATE TABLE account_start_session_activation_protection_settlements ( + activation_protection_id UUID PRIMARY KEY + REFERENCES account_start_session_activation_protections(activation_protection_id) ON DELETE RESTRICT, + activation_protection_fence BIGINT NOT NULL CHECK (activation_protection_fence > 0), + world_activation_request_id UUID NOT NULL + CHECK (world_activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + world_activation_fence BIGINT NOT NULL CHECK (world_activation_fence > 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + account_protection_evidence_bytes BYTEA NOT NULL + CHECK (octet_length(account_protection_evidence_bytes) BETWEEN 1 AND 209715264), + terminal_bytes BYTEA NOT NULL + CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 805306368), + terminal_digest VARCHAR(71) NOT NULL + CHECK (terminal_digest = 'sha256:' || encode(sha256(terminal_bytes), 'hex')), + settled_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() + CHECK (isfinite(settled_at)) +); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_activation_settlement_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_activation_protections%ROWTYPE; + terminal JSONB; + protection_evidence JSONB; + protection_request JSONB; + protection_request_bytes BYTEA; + result_value JSONB; + result_bytes BYTEA; + result_request_bytes BYTEA; + preparing_bytes BYTEA; + preparing_value JSONB; + preparing_request JSONB; + expected_preparing JSONB; + expected_activation_request JSONB; + expected_source_vector JSONB; + source_count BIGINT; + evidence_base64 TEXT; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + terminal := convert_from(NEW.terminal_bytes, 'UTF8')::JSONB; + evidence_base64 := replace(replace(encode(NEW.account_protection_evidence_bytes, 'base64'), E'\n', ''), E'\r', ''); + protection_evidence := convert_from(NEW.account_protection_evidence_bytes, 'UTF8')::JSONB; + protection_request_bytes := decode(protection_evidence->>'requestBytesBase64', 'base64'); + protection_request := convert_from(protection_request_bytes, 'UTF8')::JSONB; + preparing_bytes := decode(protection_request->>'preparingEvidenceBytesBase64', 'base64'); + preparing_value := convert_from(preparing_bytes, 'UTF8')::JSONB; + preparing_request := preparing_value->'request'; + expected_preparing := jsonb_set( + preparing_value, '{request}', preparing_request - 'readRequestId', FALSE); + expected_activation_request := jsonb_build_object( + 'schema', 'world-canonical-instance-activation-request/v1', + 'activationRequestId', original.world_activation_request_id::TEXT, + 'preparingEvidence', expected_preparing); + result_bytes := decode(terminal->>'activationResultBytesBase64', 'base64'); + result_value := convert_from(result_bytes, 'UTF8')::JSONB; + result_request_bytes := decode(result_value->>'requestBytesBase64', 'base64'); + SELECT count(*) INTO source_count + FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = original.activation_protection_id; + SELECT COALESCE( + jsonb_agg( + to_jsonb(replace(replace(encode(source.source_evidence, 'base64'), E'\n', ''), E'\r', '')) + ORDER BY account_publication_authorization_source_sort_key(source.source_key)), + '[]'::JSONB) + INTO expected_source_vector + FROM account_start_session_activation_protection_sources source + WHERE source.activation_protection_id = original.activation_protection_id; + IF NEW.activation_protection_fence IS DISTINCT FROM original.activation_protection_fence + OR NEW.world_activation_request_id IS DISTINCT FROM original.world_activation_request_id + OR NEW.terminal_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') + OR jsonb_typeof(protection_evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(protection_evidence)) <> 8 + OR NOT (protection_evidence ?& ARRAY[ + 'schema', 'requestBytesBase64', 'accountProtectionId', 'accountProtectionFence', + 'acquiredAt', 'originalSourceCaptureReferenceBytesBase64', + 'originalSourceCaptureReferenceSha256', 'sourceEvidenceVector']) + OR protection_evidence->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-evidence/v1' + OR protection_evidence->>'accountProtectionId' IS DISTINCT FROM original.activation_protection_id::TEXT + OR protection_evidence->>'accountProtectionFence' IS DISTINCT FROM original.activation_protection_fence::TEXT + OR protection_evidence->>'acquiredAt' IS DISTINCT FROM + to_char(original.acquired_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR protection_evidence->>'requestBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.request_binding_bytes, 'base64'), E'\n', ''), E'\r', '') + OR protection_request_bytes IS DISTINCT FROM original.request_binding_bytes + OR jsonb_typeof(protection_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(protection_request)) <> 12 + OR NOT (protection_request ?& ARRAY[ + 'schema', 'originalPostAuthorizationTupleBytesBase64', + 'accountRedemptionProjectionBytesBase64', 'gameSessionOwnerMutationId', + 'gameSessionOwnerAttemptId', 'gameSessionOwnerFence', 'originalLeaseExpiresAt', + 'accountWorldParticipationId', 'accountWorldParticipationFence', + 'gameSessionLaunchReadEvidenceBytesBase64', 'worldActivationRequestId', + 'preparingEvidenceBytesBase64']) + OR protection_request->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' + OR decode(protection_request->>'originalPostAuthorizationTupleBytesBase64', 'base64') + IS DISTINCT FROM original.original_post_authorization_tuple + OR decode(protection_request->>'accountRedemptionProjectionBytesBase64', 'base64') + IS DISTINCT FROM original.account_redemption_projection + OR protection_request->>'gameSessionOwnerMutationId' + IS DISTINCT FROM original.game_session_owner_mutation_id::TEXT + OR protection_request->>'gameSessionOwnerAttemptId' + IS DISTINCT FROM original.game_session_owner_attempt_id::TEXT + OR protection_request->>'gameSessionOwnerFence' + IS DISTINCT FROM original.game_session_owner_fence::TEXT + OR protection_request->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR protection_request->>'accountWorldParticipationId' + IS DISTINCT FROM original.account_world_participation_id::TEXT + OR protection_request->>'accountWorldParticipationFence' + IS DISTINCT FROM original.account_world_participation_fence::TEXT + OR decode(protection_request->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64') + IS DISTINCT FROM original.game_session_launch_read_evidence + OR protection_request->>'worldActivationRequestId' IS DISTINCT FROM original.world_activation_request_id::TEXT + OR protection_request->>'preparingEvidenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.world_preparing_evidence, 'base64'), E'\n', ''), E'\r', '') + OR protection_evidence->>'originalSourceCaptureReferenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.capture_reference_bytes, 'base64'), E'\n', ''), E'\r', '') + OR protection_evidence->>'originalSourceCaptureReferenceSha256' IS DISTINCT FROM + encode(sha256(original.capture_reference_bytes), 'hex') + OR original.capture_reference_sha256 IS DISTINCT FROM + encode(sha256(original.capture_reference_bytes), 'hex') + OR jsonb_typeof(protection_evidence->'sourceEvidenceVector') IS DISTINCT FROM 'array' + OR source_count <= 0 + OR jsonb_array_length(protection_evidence->'sourceEvidenceVector') IS DISTINCT FROM source_count + OR protection_evidence->'sourceEvidenceVector' IS DISTINCT FROM expected_source_vector + OR EXISTS ( + SELECT 1 FROM account_start_session_activation_protection_sources source + WHERE source.activation_protection_id = original.activation_protection_id + AND account_start_session_world_participation_source_key(source.source_evidence) + IS DISTINCT FROM source.source_key) + OR jsonb_typeof(terminal) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(terminal)) <> 8 + OR NOT (terminal ?& ARRAY[ + 'schema', 'activationRequestId', 'accountProtectionId', 'accountProtectionFence', + 'worldActivationFence', 'accountProtectionEvidenceBytesBase64', + 'activationResultBytesBase64', 'activationResultSha256']) + OR terminal->>'schema' IS DISTINCT FROM 'world-original-start-session-activation-terminal-evidence/v1' + OR terminal->>'activationRequestId' IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR terminal->>'accountProtectionId' IS DISTINCT FROM NEW.activation_protection_id::TEXT + OR terminal->>'accountProtectionFence' IS DISTINCT FROM NEW.activation_protection_fence::TEXT + OR terminal->>'worldActivationFence' IS DISTINCT FROM NEW.world_activation_fence::TEXT + OR terminal->>'accountProtectionEvidenceBytesBase64' IS DISTINCT FROM evidence_base64 + OR terminal->>'activationResultSha256' IS DISTINCT FROM encode(sha256(result_bytes), 'hex') + OR result_value IS NULL + OR jsonb_typeof(result_value) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(result_value)) <> 8 + OR NOT (result_value ?& ARRAY[ + 'schema', 'activationRequestId', 'requestDigest', 'requestBytesBase64', + 'preparingEvidenceBytesBase64', 'outcome', 'terminalCode', + 'lifecycleEvidenceBytesBase64']) + OR result_value->>'schema' IS DISTINCT FROM 'world-canonical-instance-activation-result/v1' + OR result_value->>'activationRequestId' IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR result_value->>'requestDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(result_request_bytes), 'hex') + OR convert_from(result_request_bytes, 'UTF8')::JSONB IS DISTINCT FROM expected_activation_request + OR result_value->>'requestBytesBase64' IS DISTINCT FROM + replace(replace(encode(result_request_bytes, 'base64'), E'\n', ''), E'\r', '') + OR result_value->>'preparingEvidenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.world_preparing_evidence, 'base64'), E'\n', ''), E'\r', '') + OR result_value->>'outcome' IS DISTINCT FROM NEW.outcome + OR (NEW.outcome = 'COMMITTED' AND result_value->'terminalCode' IS DISTINCT FROM 'null'::JSONB) + OR (NEW.outcome = 'ABORTED' + AND (jsonb_typeof(result_value->'terminalCode') IS DISTINCT FROM 'string' + OR length(result_value->>'terminalCode') = 0)) THEN + RAISE EXCEPTION 'Activation settlement must retain the exact terminal receipt for its protection' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_settlement_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation settlement is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_activation_settlement_validate + BEFORE INSERT ON account_start_session_activation_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_settlement_insert_guard(); +CREATE TRIGGER account_ss_activation_settlement_immutable + BEFORE UPDATE OR DELETE ON account_start_session_activation_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_settlement_no_mutation(); +CREATE TRIGGER account_ss_activation_settlement_no_truncate + BEFORE TRUNCATE ON account_start_session_activation_protection_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_settlement_no_mutation(); + +CREATE OR REPLACE FUNCTION account_ss_activation_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation protection is immutable; terminal settlement is separate and append-only' + USING ERRCODE = '23514'; +END; +$$; + +-- Preserve the admission-protection branch and settle activation source guards only when an +-- exact terminal receipt exists. Existing V129 source writers already call this shared function. +CREATE OR REPLACE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; + + PERFORM protection.activation_protection_id + FROM account_start_session_activation_protections protection + JOIN account_start_session_activation_protection_sources source + ON source.activation_protection_id = protection.activation_protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT EXISTS ( + SELECT 1 FROM account_start_session_activation_protection_settlements settlement + WHERE settlement.activation_protection_id = protection.activation_protection_id) + ORDER BY protection.activation_protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession activation protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql b/services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql new file mode 100644 index 0000000000..dd40ebe6bc --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql @@ -0,0 +1,59 @@ +-- Preserve V1004's closed ACTIVE lifecycle validation while requiring World-owned counters +-- to advance monotonically from the retained PREPARING evidence. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_ss_activation_settlement_lifecycle_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_activation_protections%ROWTYPE; + result_value JSONB; + lifecycle_base64 TEXT; + lifecycle_bytes BYTEA; + lifecycle JSONB; + preparing JSONB; +BEGIN + IF NEW.outcome <> 'COMMITTED' THEN + RETURN NEW; + END IF; + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + result_value := convert_from(decode( + convert_from(NEW.terminal_bytes, 'UTF8')::JSONB->>'activationResultBytesBase64', + 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(result_value->'lifecycleEvidenceBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Committed activation settlement requires ACTIVE lifecycle evidence' + USING ERRCODE = '23514'; + END IF; + lifecycle_base64 := result_value->>'lifecycleEvidenceBytesBase64'; + lifecycle_bytes := decode(lifecycle_base64, 'base64'); + IF regexp_replace(encode(lifecycle_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM lifecycle_base64 THEN + RAISE EXCEPTION 'Committed activation lifecycle Base64 must be canonical' + USING ERRCODE = '23514'; + END IF; + lifecycle := account_ss_activation_validate_lifecycle(lifecycle_bytes, 'ACTIVE'); + preparing := convert_from(original.world_preparing_evidence, 'UTF8')::JSONB; + IF preparing->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' THEN + RAISE EXCEPTION 'Committed activation requires retained PREPARING owner evidence' + USING ERRCODE = '23514'; + END IF; + IF (lifecycle->>'lifecycleEpoch')::NUMERIC < (preparing->>'lifecycleEpoch')::NUMERIC + OR (lifecycle->>'rowVersion')::NUMERIC < (preparing->>'rowVersion')::NUMERIC THEN + RAISE EXCEPTION 'Committed activation lifecycle counters cannot regress' + USING ERRCODE = '23514'; + END IF; + -- Only status, counters and the read observation identity may change during activation. + IF lifecycle - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + IS DISTINCT FROM preparing - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + OR (lifecycle->'request') - 'readRequestId' + IS DISTINCT FROM (preparing->'request') - 'readRequestId' THEN + RAISE EXCEPTION 'Committed activation lifecycle differs from retained PREPARING binding' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +EXCEPTION WHEN invalid_text_representation OR character_not_in_repertoire OR numeric_value_out_of_range + OR invalid_parameter_value THEN + RAISE EXCEPTION 'Committed activation lifecycle encoding or scalar is invalid' + USING ERRCODE = '23514'; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql b/services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql new file mode 100644 index 0000000000..c489fa81e5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql @@ -0,0 +1,119 @@ +-- Apply V1004's existing closed PREPARING lifecycle validator to retained protections before +-- comparing their counters, preserving V1004.1's ACTIVE and monotonic settlement checks. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_ss_activation_settlement_lifecycle_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_activation_protections%ROWTYPE; + result_value JSONB; + lifecycle_base64 TEXT; + lifecycle_bytes BYTEA; + lifecycle JSONB; + preparing JSONB; +BEGIN + IF NEW.outcome <> 'COMMITTED' THEN + RETURN NEW; + END IF; + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + result_value := convert_from(decode( + convert_from(NEW.terminal_bytes, 'UTF8')::JSONB->>'activationResultBytesBase64', + 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(result_value->'lifecycleEvidenceBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Committed activation settlement requires ACTIVE lifecycle evidence' + USING ERRCODE = '23514'; + END IF; + lifecycle_base64 := result_value->>'lifecycleEvidenceBytesBase64'; + lifecycle_bytes := decode(lifecycle_base64, 'base64'); + IF regexp_replace(encode(lifecycle_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM lifecycle_base64 THEN + RAISE EXCEPTION 'Committed activation lifecycle Base64 must be canonical' + USING ERRCODE = '23514'; + END IF; + lifecycle := account_ss_activation_validate_lifecycle(lifecycle_bytes, 'ACTIVE'); + preparing := account_ss_activation_validate_lifecycle( + original.world_preparing_evidence, 'PREPARING'); + IF (lifecycle->>'lifecycleEpoch')::NUMERIC < (preparing->>'lifecycleEpoch')::NUMERIC + OR (lifecycle->>'rowVersion')::NUMERIC < (preparing->>'rowVersion')::NUMERIC THEN + RAISE EXCEPTION 'Committed activation lifecycle counters cannot regress' + USING ERRCODE = '23514'; + END IF; + -- Only status, counters and the read observation identity may change during activation. + IF lifecycle - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + IS DISTINCT FROM preparing - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + OR (lifecycle->'request') - 'readRequestId' + IS DISTINCT FROM (preparing->'request') - 'readRequestId' THEN + RAISE EXCEPTION 'Committed activation lifecycle differs from retained PREPARING binding' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +EXCEPTION WHEN invalid_text_representation OR character_not_in_repertoire OR numeric_value_out_of_range + OR invalid_parameter_value THEN + RAISE EXCEPTION 'Committed activation lifecycle encoding or scalar is invalid' + USING ERRCODE = '23514'; +END; +$$; +-- [jooq ignore end] + +-- Keep activation-request UUID spelling canonical at the existing Account protection boundary. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_ss_activation_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + request_value JSONB; + tuple_bytes BYTEA; + projection_bytes BYTEA; + launch_bytes BYTEA; + preparing_bytes BYTEA; +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() + OR NEW.capture_sha256 IS DISTINCT FROM encode(sha256(NEW.capture_reference_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection must retain its producer capture transaction and digest' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(NEW.request_binding_bytes, 'UTF8')::JSONB; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + launch_bytes := decode(request_value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + IF NEW.control_plane_request_id IS DISTINCT FROM + (convert_from(tuple_bytes, 'UTF8')::JSONB->>'controlPlaneRequestId') + OR NEW.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR NEW.account_redemption_projection IS DISTINCT FROM projection_bytes + OR NEW.game_session_owner_mutation_id IS DISTINCT FROM (request_value->>'gameSessionOwnerMutationId')::UUID + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM (request_value->>'gameSessionOwnerAttemptId')::UUID + OR NEW.game_session_owner_fence IS DISTINCT FROM (request_value->>'gameSessionOwnerFence')::BIGINT + OR NEW.original_lease_expires_at IS DISTINCT FROM (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR NEW.account_world_participation_id IS DISTINCT FROM (request_value->>'accountWorldParticipationId')::UUID + OR NEW.account_world_participation_fence IS DISTINCT FROM (request_value->>'accountWorldParticipationFence')::BIGINT + OR (request_value->>'worldActivationRequestId') IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR NEW.game_session_launch_read_evidence IS DISTINCT FROM launch_bytes + OR NEW.world_preparing_evidence IS DISTINCT FROM preparing_bytes + OR NEW.request_binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.request_binding_bytes), 'hex') + OR NEW.operation_identity_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.operation_identity_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection does not retain its exact canonical request fields' + USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_activation_assert_current( + NEW.request_binding_bytes, NEW.operation_identity_bytes, NEW.operation_identity_digest, FALSE); + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_authority_captures capture + WHERE capture.control_plane_request_id = NEW.control_plane_request_id + AND capture.source_version = NEW.capture_source_version + AND capture.source_fence = NEW.capture_source_fence + AND capture.canonical_sha256 = NEW.capture_sha256 + AND capture.canonical_capture_bytes = NEW.capture_reference_bytes + AND NEW.target_namespace = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'targetNamespace') + AND NEW.canonical_tenant_id = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'tenantId')::UUID + AND NEW.canonical_game_instance_id = (convert_from(preparing_bytes, 'UTF8')::JSONB + ->'request'->>'canonicalGameInstanceId')::UUID + AND NEW.capture_reference_sha256 = encode(sha256(NEW.capture_reference_bytes), 'hex')) THEN + RAISE EXCEPTION 'Activation protection capture or target differs from the exact current request' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql b/services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql new file mode 100644 index 0000000000..793342c4b9 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql @@ -0,0 +1,73 @@ +-- Require the existing protection fields to retain their canonical Base64 spellings at acquisition. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_ss_activation_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + request_value JSONB; + tuple_bytes BYTEA; + projection_bytes BYTEA; + launch_bytes BYTEA; + preparing_bytes BYTEA; +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() + OR NEW.capture_sha256 IS DISTINCT FROM encode(sha256(NEW.capture_reference_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection must retain its producer capture transaction and digest' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(NEW.request_binding_bytes, 'UTF8')::JSONB; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + launch_bytes := decode(request_value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + IF regexp_replace(encode(tuple_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM request_value->>'originalPostAuthorizationTupleBytesBase64' + OR regexp_replace(encode(projection_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM request_value->>'accountRedemptionProjectionBytesBase64' + OR regexp_replace(encode(launch_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM request_value->>'gameSessionLaunchReadEvidenceBytesBase64' + OR regexp_replace(encode(preparing_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM request_value->>'preparingEvidenceBytesBase64' THEN + RAISE EXCEPTION 'Activation protection Base64 fields must use canonical encodings' + USING ERRCODE = '23514'; + END IF; + IF NEW.control_plane_request_id IS DISTINCT FROM + (convert_from(tuple_bytes, 'UTF8')::JSONB->>'controlPlaneRequestId') + OR NEW.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR NEW.account_redemption_projection IS DISTINCT FROM projection_bytes + OR NEW.game_session_owner_mutation_id IS DISTINCT FROM (request_value->>'gameSessionOwnerMutationId')::UUID + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM (request_value->>'gameSessionOwnerAttemptId')::UUID + OR NEW.game_session_owner_fence IS DISTINCT FROM (request_value->>'gameSessionOwnerFence')::BIGINT + OR NEW.original_lease_expires_at IS DISTINCT FROM (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR NEW.account_world_participation_id IS DISTINCT FROM (request_value->>'accountWorldParticipationId')::UUID + OR NEW.account_world_participation_fence IS DISTINCT FROM (request_value->>'accountWorldParticipationFence')::BIGINT + OR (request_value->>'worldActivationRequestId') IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR NEW.game_session_launch_read_evidence IS DISTINCT FROM launch_bytes + OR NEW.world_preparing_evidence IS DISTINCT FROM preparing_bytes + OR NEW.request_binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.request_binding_bytes), 'hex') + OR NEW.operation_identity_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.operation_identity_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection does not retain its exact canonical request fields' + USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_activation_assert_current( + NEW.request_binding_bytes, NEW.operation_identity_bytes, NEW.operation_identity_digest, FALSE); + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_authority_captures capture + WHERE capture.control_plane_request_id = NEW.control_plane_request_id + AND capture.source_version = NEW.capture_source_version + AND capture.source_fence = NEW.capture_source_fence + AND capture.canonical_sha256 = NEW.capture_sha256 + AND capture.canonical_capture_bytes = NEW.capture_reference_bytes + AND NEW.target_namespace = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'targetNamespace') + AND NEW.canonical_tenant_id = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'tenantId')::UUID + AND NEW.canonical_game_instance_id = (convert_from(preparing_bytes, 'UTF8')::JSONB + ->'request'->>'canonicalGameInstanceId')::UUID + AND NEW.capture_reference_sha256 = encode(sha256(NEW.capture_reference_bytes), 'hex')) THEN + RAISE EXCEPTION 'Activation protection capture or target differs from the exact current request' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql b/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql new file mode 100644 index 0000000000..5d4a0ed361 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql @@ -0,0 +1,394 @@ +-- Validate closed PREPARING lifecycle evidence before acquiring a source protection, +-- and closed ACTIVE evidence before accepting COMMITTED settlement. Preserve V1003's +-- source/owner lock order, completeness, terminal, outcome and immutable binding fences. +-- This integrity guard does not authenticate World or duplicate its nested launch-binding codec: +-- launch binding and all immutable lifecycle values remain exactly the retained owner values. +-- [jooq ignore start] +CREATE FUNCTION account_ss_activation_validate_lifecycle( + lifecycle_bytes BYTEA, + expected_status TEXT +) RETURNS JSONB LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + lifecycle JSONB; + request_value JSONB; + field_name TEXT; + region RECORD; + uuid_pattern CONSTANT TEXT := '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; + nil_uuid CONSTANT TEXT := '00000000-0000-0000-0000-000000000000'; +BEGIN + -- Check before JSONB normalizes duplicate keys, including duplicates in nested objects. + IF NOT (convert_from(lifecycle_bytes, 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'Activation lifecycle requires unique closed JSON object keys' + USING ERRCODE = '23514'; + END IF; + -- JSON preserves the number spelling that JSONB may normalize (for example 1e0). + IF (convert_from(lifecycle_bytes, 'UTF8')::JSON->'request'->'schemaVersion')::TEXT + IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Activation lifecycle schemaVersion must be the integral JSON number 1' + USING ERRCODE = '23514'; + END IF; + lifecycle := convert_from(lifecycle_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(lifecycle) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Activation lifecycle must be a closed object' + USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 12 + OR NOT (lifecycle ?& ARRAY[ + 'schema', 'request', 'launchBindingBytesBase64', 'startLocation', + 'runtimeRoomInstanceId', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion', + 'captureId', 'graphSha256', 'preparationInputDigest', 'operationalRegionAssignments']) + OR lifecycle->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR lifecycle->>'lifecycleStatus' IS DISTINCT FROM expected_status + OR jsonb_typeof(lifecycle->'request') IS DISTINCT FROM 'object' + OR jsonb_typeof(lifecycle->'startLocation') IS DISTINCT FROM 'object' + OR jsonb_typeof(lifecycle->'operationalRegionAssignments') IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Activation lifecycle must be closed owner evidence for the expected status' + USING ERRCODE = '23514'; + END IF; + FOREACH field_name IN ARRAY ARRAY[ + 'schema', 'launchBindingBytesBase64', 'runtimeRoomInstanceId', 'lifecycleStatus', + 'lifecycleEpoch', 'rowVersion', 'captureId', 'graphSha256', 'preparationInputDigest'] LOOP + IF jsonb_typeof(lifecycle->field_name) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Activation lifecycle scalar must be a string: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + FOREACH field_name IN ARRAY ARRAY['runtimeRoomInstanceId', 'lifecycleEpoch', 'rowVersion'] LOOP + IF lifecycle->>field_name !~ '^(0|[1-9][0-9]*)$' + OR (lifecycle->>field_name)::NUMERIC > 9223372036854775807 + OR (field_name <> 'rowVersion' AND (lifecycle->>field_name)::NUMERIC = 0) THEN + RAISE EXCEPTION 'Activation lifecycle counter is invalid: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF lifecycle->>'captureId' !~ uuid_pattern OR lifecycle->>'captureId' = nil_uuid + OR lifecycle->>'graphSha256' !~ '^[0-9a-f]{64}$' + OR lifecycle->>'preparationInputDigest' !~ '^sha256:[0-9a-f]{64}$' + OR length(lifecycle->>'launchBindingBytesBase64') = 0 + OR regexp_replace(encode(decode(lifecycle->>'launchBindingBytesBase64', 'base64'), + 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM lifecycle->>'launchBindingBytesBase64' THEN + RAISE EXCEPTION 'Activation lifecycle identities or retained launch bytes are invalid' + USING ERRCODE = '23514'; + END IF; + request_value := lifecycle->'request'; + IF (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 14 + OR NOT (request_value ?& ARRAY[ + 'schemaVersion', 'readRequestId', 'targetNamespace', 'canonicalTenantId', 'worldSlug', + 'canonicalGameInstanceId', 'playableStateNamespaceId', 'playableStateScope', + 'publicProduction', 'controlPlaneRequestId', 'canonicalVersionId', + 'expectedDescriptorRequestDigest', 'expectedDescriptorResultDigest', + 'expectedReleaseAttestationDigest']) + OR jsonb_typeof(request_value->'schemaVersion') IS DISTINCT FROM 'number' + OR request_value->>'schemaVersion' IS DISTINCT FROM '1' + OR request_value->'publicProduction' IS DISTINCT FROM 'true'::JSONB + OR request_value->>'playableStateScope' IS DISTINCT FROM 'SHARED' THEN + RAISE EXCEPTION 'Activation lifecycle request must have the complete closed shape' + USING ERRCODE = '23514'; + END IF; + FOREACH field_name IN ARRAY ARRAY[ + 'readRequestId', 'targetNamespace', 'canonicalTenantId', 'worldSlug', + 'canonicalGameInstanceId', 'playableStateNamespaceId', 'playableStateScope', + 'controlPlaneRequestId', 'canonicalVersionId', 'expectedDescriptorRequestDigest', + 'expectedDescriptorResultDigest', 'expectedReleaseAttestationDigest'] LOOP + IF jsonb_typeof(request_value->field_name) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Activation lifecycle request scalar must be a string: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + FOREACH field_name IN ARRAY ARRAY[ + 'readRequestId', 'canonicalTenantId', 'canonicalGameInstanceId', + 'playableStateNamespaceId', 'canonicalVersionId'] LOOP + IF request_value->>field_name !~ uuid_pattern OR request_value->>field_name = nil_uuid THEN + RAISE EXCEPTION 'Activation lifecycle request UUID is invalid: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + FOREACH field_name IN ARRAY ARRAY[ + 'expectedDescriptorRequestDigest', 'expectedDescriptorResultDigest', + 'expectedReleaseAttestationDigest'] LOOP + IF request_value->>field_name !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Activation lifecycle request digest is invalid: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF length(request_value->>'targetNamespace') NOT BETWEEN 1 AND 63 + OR request_value->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + OR octet_length(request_value->>'worldSlug') NOT BETWEEN 1 AND 120 + OR request_value->>'worldSlug' !~ '^[a-z0-9]+(-[a-z0-9]+)*$' + OR cardinality(account_publication_authorization_source_sort_key( + request_value->>'controlPlaneRequestId')) NOT BETWEEN 1 AND 128 + OR request_value->>'controlPlaneRequestId' ~ '^[[:space:]]*$' THEN + RAISE EXCEPTION 'Activation lifecycle request text is invalid' + USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(lifecycle->'startLocation')) <> 3 + OR NOT (lifecycle->'startLocation' ?& ARRAY['tenantId', 'versionId', 'roomTemplateId']) THEN + RAISE EXCEPTION 'Activation lifecycle start location must be closed' + USING ERRCODE = '23514'; + END IF; + FOREACH field_name IN ARRAY ARRAY['tenantId', 'versionId', 'roomTemplateId'] LOOP + IF jsonb_typeof(lifecycle->'startLocation'->field_name) IS DISTINCT FROM 'string' + OR lifecycle->'startLocation'->>field_name !~ uuid_pattern + OR lifecycle->'startLocation'->>field_name = nil_uuid THEN + RAISE EXCEPTION 'Activation lifecycle start location UUID is invalid: %', field_name + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF (SELECT count(*) FROM jsonb_object_keys(lifecycle->'operationalRegionAssignments')) = 0 + OR (SELECT count(*) FROM jsonb_each(lifecycle->'operationalRegionAssignments')) + <> (SELECT count(DISTINCT value) FROM jsonb_each(lifecycle->'operationalRegionAssignments')) THEN + RAISE EXCEPTION 'Activation lifecycle requires distinct operational region assignments' + USING ERRCODE = '23514'; + END IF; + FOR region IN SELECT key, value FROM jsonb_each(lifecycle->'operationalRegionAssignments') LOOP + IF region.key !~ uuid_pattern OR region.key = nil_uuid + OR jsonb_typeof(region.value) IS DISTINCT FROM 'string' + OR region.value #>> '{}' !~ uuid_pattern OR region.value #>> '{}' = nil_uuid + OR region.key = region.value #>> '{}' THEN + RAISE EXCEPTION 'Activation lifecycle region assignment is invalid' + USING ERRCODE = '23514'; + END IF; + END LOOP; + RETURN lifecycle; +EXCEPTION WHEN invalid_text_representation OR character_not_in_repertoire OR numeric_value_out_of_range + OR invalid_parameter_value THEN + RAISE EXCEPTION 'Activation lifecycle encoding or scalar is invalid' + USING ERRCODE = '23514'; +END; +$$; + +CREATE OR REPLACE FUNCTION account_ss_activation_assert_current( + request_bytes BYTEA, + operation_bytes BYTEA, + operation_digest TEXT, + require_complete BOOLEAN +) RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + capture account_start_session_authority_captures%ROWTYPE; + world_parent account_start_session_world_participations%ROWTYPE; + observation account_start_session_world_original_attempt_evidence%ROWTYPE; + authorization_row account_start_session_operator_authorizations%ROWTYPE; + retained account_start_session_activation_protections%ROWTYPE; + snapshot_value JSONB; + request_value JSONB; + tuple_value JSONB; + projection_value JSONB; + preparing_value JSONB; + preparing_request JSONB; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + tuple_bytes BYTEA; + projection_bytes BYTEA; + preparing_bytes BYTEA; + control_request_id TEXT; + requested_participation_id UUID; + keys TEXT[]; + retained_found BOOLEAN := FALSE; +BEGIN + IF octet_length(request_bytes) NOT BETWEEN 1 AND 150994944 + OR octet_length(operation_bytes) NOT BETWEEN 1 AND 150994944 + OR operation_digest IS DISTINCT FROM 'sha256:' || encode(sha256(operation_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession activation request or operation identity is invalid' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(request_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request_value) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 12 + OR NOT (request_value ?& ARRAY[ + 'schema', 'originalPostAuthorizationTupleBytesBase64', + 'accountRedemptionProjectionBytesBase64', 'gameSessionOwnerMutationId', + 'gameSessionOwnerAttemptId', 'gameSessionOwnerFence', 'originalLeaseExpiresAt', + 'accountWorldParticipationId', 'accountWorldParticipationFence', + 'gameSessionLaunchReadEvidenceBytesBase64', 'worldActivationRequestId', + 'preparingEvidenceBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(request_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR request_value->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' THEN + RAISE EXCEPTION 'Original StartSession activation request has an unsupported shape' + USING ERRCODE = '23514'; + END IF; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + PERFORM account_ss_activation_validate_lifecycle(preparing_bytes, 'PREPARING'); + tuple_value := convert_from(tuple_bytes, 'UTF8')::JSONB; + control_request_id := tuple_value->>'controlPlaneRequestId'; + requested_participation_id := (request_value->>'accountWorldParticipationId')::UUID; + + -- Source-key locks are acquired in the canonical V129 order before any retained owner, + -- World or activation-protection row is locked. + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_value->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM control_request_id THEN + RAISE EXCEPTION 'Activation protection requires the exact original Account source snapshot' + USING ERRCODE = '23514'; + END IF; + keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(keys, snapshot_value); + + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT world_parent FROM account_start_session_world_participations + WHERE account_start_session_world_participations.participation_id = requested_participation_id + FOR UPDATE NOWAIT; + SELECT * INTO STRICT observation FROM account_start_session_world_original_attempt_evidence + WHERE participation_id = world_parent.participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO retained FROM account_start_session_activation_protections + WHERE account_start_session_activation_protections.control_plane_request_id = control_request_id + FOR UPDATE NOWAIT; + retained_found := FOUND; + + preparing_value := convert_from(preparing_bytes, 'UTF8')::JSONB; + preparing_request := preparing_value->'request'; + projection_value := convert_from(projection_bytes, 'UTF8')::JSONB; + IF request_value->>'gameSessionOwnerMutationId' IS DISTINCT FROM observation.game_session_owner_mutation_id::TEXT + OR request_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM observation.game_session_owner_attempt_id::TEXT + OR request_value->>'gameSessionOwnerFence' IS DISTINCT FROM observation.game_session_owner_fence::TEXT + OR request_value->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(observation.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR request_value->>'accountWorldParticipationId' IS DISTINCT FROM world_parent.participation_id::TEXT + OR request_value->>'accountWorldParticipationFence' IS DISTINCT FROM world_parent.participation_fence::TEXT + OR world_parent.control_plane_request_id IS DISTINCT FROM control_request_id + OR world_parent.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR world_parent.game_session_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR world_parent.game_session_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + OR observation.target_namespace IS DISTINCT FROM world_parent.target_namespace + OR NOT EXISTS ( + SELECT 1 FROM account_start_session_world_participation_settlements settlement + WHERE settlement.participation_id = world_parent.participation_id + AND settlement.outcome = 'COMMITTED') + OR preparing_value->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR preparing_value->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR preparing_request->>'controlPlaneRequestId' IS DISTINCT FROM control_request_id + OR preparing_request->>'targetNamespace' IS DISTINCT FROM world_parent.target_namespace + OR preparing_request->>'canonicalTenantId' IS DISTINCT FROM world_parent.canonical_tenant_id::TEXT + OR preparing_request->>'canonicalGameInstanceId' IS DISTINCT FROM world_parent.canonical_game_instance_id::TEXT + OR capture.source_version <= 0 OR capture.source_fence <= 0 THEN + RAISE EXCEPTION 'Activation protection differs from committed original World preparation or attempt' + USING ERRCODE = '23514'; + END IF; + + -- Retain the original Account issuance/redemption tuple and complete projection exactly. + IF capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') + OR capture.snapshot_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_snapshot_bytes), 'hex') + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization_row.pre_authorization_tuple + OR capture.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence + OR authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + OR authorization_row.redemption_reference_fingerprint IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR authorization_row.redemption_authority_evidence_bundle IS DISTINCT FROM authorization_row.authority_evidence_bundle + OR tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + OR tuple_value->>'authorizationReferenceFingerprint' IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization_row.issuance_fence::TEXT + OR tuple_value->'authorityEvidenceBundle' IS DISTINCT FROM convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB + OR projection_bytes IS DISTINCT FROM tuple_bytes + OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}' + IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT + OR capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection differs from original Account redemption or capture' + USING ERRCODE = '23514'; + END IF; + + IF retained_found AND ( + retained.operation_identity_bytes IS DISTINCT FROM operation_bytes + OR retained.operation_identity_digest IS DISTINCT FROM operation_digest + OR retained.account_world_participation_id IS DISTINCT FROM world_parent.participation_id + OR retained.account_world_participation_fence IS DISTINCT FROM world_parent.participation_fence) THEN + RAISE EXCEPTION 'Original StartSession activation protection conflicts with its immutable binding' + USING ERRCODE = '23514'; + END IF; + + -- The typed Common carrier validates the closed Game Session STARTING result and exact + -- World PREPARING evidence. SQL independently checks finite original authority only after + -- all canonical source and owner/protection row locks have completed. + IF observation.original_lease_expires_at IS DISTINCT FROM + (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR observation.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession activation protection lease is stale or expired' + USING ERRCODE = '23514'; + END IF; + + PERFORM account_start_session_world_participation_assert_sources(world_parent.participation_id, snapshot_value); + IF require_complete THEN + IF (SELECT count(*) FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id) + <> jsonb_array_length(snapshot_value->'sourceVector') THEN + RAISE EXCEPTION 'Activation protection has incomplete or extra source children' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + source_bytes := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(source_bytes); + IF NOT EXISTS (SELECT 1 FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id + AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Activation protection source child differs from original capture' + USING ERRCODE = '23514'; + END IF; + END LOOP; + END IF; +END; +$$; + +CREATE FUNCTION account_ss_activation_settlement_lifecycle_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_activation_protections%ROWTYPE; + result_value JSONB; + lifecycle_base64 TEXT; + lifecycle_bytes BYTEA; + lifecycle JSONB; + preparing JSONB; +BEGIN + IF NEW.outcome <> 'COMMITTED' THEN + RETURN NEW; + END IF; + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + result_value := convert_from(decode( + convert_from(NEW.terminal_bytes, 'UTF8')::JSONB->>'activationResultBytesBase64', + 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(result_value->'lifecycleEvidenceBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Committed activation settlement requires ACTIVE lifecycle evidence' + USING ERRCODE = '23514'; + END IF; + lifecycle_base64 := result_value->>'lifecycleEvidenceBytesBase64'; + lifecycle_bytes := decode(lifecycle_base64, 'base64'); + IF regexp_replace(encode(lifecycle_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM lifecycle_base64 THEN + RAISE EXCEPTION 'Committed activation lifecycle Base64 must be canonical' + USING ERRCODE = '23514'; + END IF; + lifecycle := account_ss_activation_validate_lifecycle(lifecycle_bytes, 'ACTIVE'); + preparing := convert_from(original.world_preparing_evidence, 'UTF8')::JSONB; + IF preparing->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' THEN + RAISE EXCEPTION 'Committed activation requires retained PREPARING owner evidence' + USING ERRCODE = '23514'; + END IF; + -- Only status, counters and the read observation identity may change during activation. + IF lifecycle - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + IS DISTINCT FROM preparing - ARRAY['request', 'lifecycleStatus', 'lifecycleEpoch', 'rowVersion'] + OR (lifecycle->'request') - 'readRequestId' + IS DISTINCT FROM (preparing->'request') - 'readRequestId' THEN + RAISE EXCEPTION 'Committed activation lifecycle differs from retained PREPARING binding' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +EXCEPTION WHEN invalid_text_representation OR character_not_in_repertoire OR numeric_value_out_of_range + OR invalid_parameter_value THEN + RAISE EXCEPTION 'Committed activation lifecycle encoding or scalar is invalid' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_activation_settlement_validate_lifecycle + BEFORE INSERT ON account_start_session_activation_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_settlement_lifecycle_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java new file mode 100644 index 0000000000..c8996a6624 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -0,0 +1,1953 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** + * Runs V1003/V1004/V1004.1/V1004.2/V1004.3 against the actual Account PostgreSQL schema and + * assembled source-writer guard. The integrity and currentness fixtures seed related owner rows + * with upstream producer triggers disabled. Protection acquisition, child completeness, settlement + * and source-writer guards remain enabled; they prove SQL currentness/exclusion/immutability only, + * not authenticated activation-protection production. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionActivationProtectionPostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() throws Exception { + Fixture fixture = fixture("1003"); + CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(10), 135500, 1L); + byte[] requestBinding = current.requestBytes(); + Map request = readJson(requestBinding); + UUID activationRequestId = UUID.fromString((String) request.get("worldActivationRequestId")); + byte[] preparingEvidence = + Base64.getDecoder().decode((String) request.get("preparingEvidenceBytesBase64")); + byte[] captureReference = bytes("{}"); + String operationDigest = current.operationIdentityDigest(); + assertThat( + Base64.getDecoder() + .decode((String) request.get("accountRedemptionProjectionBytesBase64")) + .length) + .isGreaterThan(135168) + .isLessThanOrEqualTo(262144); + acquireProtection(fixture, current); + var sources = + fixture + .dsl() + .fetch( + "SELECT source_key, source_evidence FROM account_start_session_activation_protection_sources " + + "ORDER BY account_publication_authorization_source_sort_key(source_key)"); + assertThat(sources).hasSize(2); + String sourceKey = sources.get(0).get("source_key", String.class); + byte[][] sourceEvidenceBytes = + sources.stream() + .map(row -> row.get("source_evidence", byte[].class)) + .toArray(byte[][]::new); + + var stored = + fixture + .dsl() + .fetchSingle( + "SELECT activation_protection_id, activation_protection_fence, acquired_at " + + "FROM account_start_session_activation_protections " + + "WHERE operation_identity_digest = ?", + operationDigest); + UUID id = stored.get("activation_protection_id", UUID.class); + assertThat(id).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(stored.get("activation_protection_fence", Long.class)).isPositive(); + assertThat(stored.get("acquired_at", OffsetDateTime.class)).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_activation_protections " + + "SET acquired_at = acquired_at " + + "WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("immutable; terminal settlement is separate"); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(" + + "ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_regprocedure('account_ss_activation_settlement_lifecycle_guard()')::TEXT") + .get(0, String.class)) + .isNull(); + String retainedHistoryQuery = + "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1004' ORDER BY installed_rank"; + var installedHistory = fixture.dsl().fetch(retainedHistoryQuery).getValues(0, String.class); + String protectionRowsQuery = + "SELECT jsonb_build_object('row', to_jsonb(p), 'xmin', p.xmin::TEXT)::TEXT FROM " + + "account_start_session_activation_protections p ORDER BY activation_protection_id"; + String sourceRowsQuery = + "SELECT jsonb_build_object('row', to_jsonb(s), 'xmin', s.xmin::TEXT)::TEXT FROM " + + "account_start_session_activation_protection_sources s ORDER BY activation_protection_id, source_key"; + var pendingRows = fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class); + var retainedSources = fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class); + assertThat(pendingRows).hasSize(1); + assertThat(retainedSources).hasSize(2); + + Flyway upgrade = activationFlyway(fixture.dataSource(), "1004"); + assertThat(upgrade.migrate().migrationsExecuted).isEqualTo(1); + upgrade.validate(); + assertThat(fixture.dsl().fetch(retainedHistoryQuery).getValues(0, String.class)) + .isEqualTo(installedHistory); + assertThat(fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class)) + .isEqualTo(pendingRows); + assertThat(fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class)) + .isEqualTo(retainedSources); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT max(version::int) FROM flyway_schema_history WHERE version ~ '^[0-9]+$'") + .get(0, Integer.class)) + .isEqualTo(1004); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_regprocedure('account_ss_activation_settlement_lifecycle_guard()')::TEXT") + .get(0, String.class)) + .isNotNull(); + + String preCounterUpgradeHistoryQuery = + "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1004.1' ORDER BY installed_rank"; + var preCounterUpgradeHistory = + fixture.dsl().fetch(preCounterUpgradeHistoryQuery).getValues(0, String.class); + Flyway monotonicUpgrade = activationFlyway(fixture.dataSource(), "1004.1"); + assertThat(monotonicUpgrade.migrate().migrationsExecuted).isEqualTo(1); + monotonicUpgrade.validate(); + assertThat(fixture.dsl().fetch(preCounterUpgradeHistoryQuery).getValues(0, String.class)) + .isEqualTo(preCounterUpgradeHistory); + assertThat(fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class)) + .isEqualTo(pendingRows); + assertThat(fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class)) + .isEqualTo(retainedSources); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_regprocedure('account_ss_activation_settlement_lifecycle_guard()')::TEXT") + .get(0, String.class)) + .isNotNull(); + + String preRetainedLifecycleUpgradeHistoryQuery = + "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1004.2' ORDER BY installed_rank"; + var preRetainedLifecycleUpgradeHistory = + fixture.dsl().fetch(preRetainedLifecycleUpgradeHistoryQuery).getValues(0, String.class); + Flyway retainedLifecycleUpgrade = activationFlyway(fixture.dataSource(), "1004.2"); + assertThat(retainedLifecycleUpgrade.migrate().migrationsExecuted).isEqualTo(1); + retainedLifecycleUpgrade.validate(); + assertThat( + fixture.dsl().fetch(preRetainedLifecycleUpgradeHistoryQuery).getValues(0, String.class)) + .isEqualTo(preRetainedLifecycleUpgradeHistory); + assertThat(fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class)) + .isEqualTo(pendingRows); + assertThat(fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class)) + .isEqualTo(retainedSources); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT to_regprocedure('account_ss_activation_settlement_lifecycle_guard()')::TEXT") + .get(0, String.class)) + .isNotNull(); + + String preCanonicalCarrierUpgradeHistoryQuery = + "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1004.3' ORDER BY installed_rank"; + var preCanonicalCarrierUpgradeHistory = + fixture.dsl().fetch(preCanonicalCarrierUpgradeHistoryQuery).getValues(0, String.class); + Flyway canonicalCarrierUpgrade = activationFlyway(fixture.dataSource(), "1004.3"); + assertThat(canonicalCarrierUpgrade.migrate().migrationsExecuted).isEqualTo(1); + canonicalCarrierUpgrade.validate(); + assertThat( + fixture.dsl().fetch(preCanonicalCarrierUpgradeHistoryQuery).getValues(0, String.class)) + .isEqualTo(preCanonicalCarrierUpgradeHistory); + assertThat(fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class)) + .isEqualTo(pendingRows); + assertThat(fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class)) + .isEqualTo(retainedSources); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT to_regprocedure('account_ss_activation_insert_guard()')::TEXT") + .get(0, String.class)) + .isNotNull(); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT max(version::numeric) FROM flyway_schema_history WHERE version ~ '^[0-9]+(\\.[0-9]+)?$'") + .get(0, java.math.BigDecimal.class)) + .isEqualByComparingTo("1004.3"); + + fixture + .dsl() + .fetch( + "SELECT pg_sleep(GREATEST(0, EXTRACT(EPOCH FROM (?::timestamptz - clock_timestamp()))))", + current.expiryText()); + + // This SQL receipt retains a typed closed ACTIVE lifecycle fixture. Upstream owner rows remain + // stipulated; this is storage integrity proof, not authenticated World production. + // The original lease has expired before settlement insertion. + OffsetDateTime retainedAcquiredAt = stored.get("acquired_at", OffsetDateTime.class); + long protectionFence = stored.get("activation_protection_fence", Long.class); + byte[] accountEvidenceBytes = + accountEvidence( + id, + protectionFence, + retainedAcquiredAt, + requestBinding, + captureReference, + sourceEvidenceBytes); + byte[] activationResultBytes = + activationResult(activationRequestId, preparingEvidence, "COMMITTED"); + + Map validResult = readJson(activationResultBytes); + byte[] activeBytes = + Base64.getDecoder().decode((String) validResult.get("lifecycleEvidenceBytesBase64")); + java.util.List invalidLifecycleCarriers = new java.util.ArrayList<>(); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(bytes("synthetic ACTIVE"))); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(bytes("{"))); + invalidLifecycleCarriers.add( + Base64.getEncoder().encodeToString(new byte[] {(byte) 0xc3, 0x28})); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(bytes("null"))); + String activeJson = new String(activeBytes, StandardCharsets.UTF_8); + for (String schemaVersion : new String[] {"1.0", "1e0", "1e+0"}) { + byte[] invalidVersion = + bytes(activeJson.replace("\"schemaVersion\":1", "\"schemaVersion\":" + schemaVersion)); + assertThatThrownBy(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(invalidVersion)) + .isInstanceOf(IllegalArgumentException.class); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(invalidVersion)); + } + for (String duplicate : + new String[] { + activeJson.replace("\"schema\":", "\"schema\":\"wrong/v1\",\"schema\":"), + activeJson.replace( + "\"lifecycleStatus\":", "\"lifecycleStatus\":\"PREPARING\",\"lifecycleStatus\":"), + activeJson.replace("\"schemaVersion\":1", "\"schemaVersion\":0,\"schemaVersion\":1") + }) { + byte[] duplicateBytes = bytes(duplicate); + assertThatThrownBy(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(duplicateBytes)) + .isInstanceOf(IllegalArgumentException.class); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(duplicateBytes)); + } + invalidLifecycleCarriers.add("%%%"); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(activeBytes) + "\n"); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(bytes("[]"))); + for (String field : + new String[] { + "schema", + "lifecycleStatus", + "lifecycleEpoch", + "rowVersion", + "runtimeRoomInstanceId", + "captureId", + "graphSha256", + "preparationInputDigest", + "launchBindingBytesBase64", + "startLocation", + "operationalRegionAssignments", + "request" + }) { + Map missing = readJson(activeBytes); + missing.remove(field); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(jsonBytes(missing))); + Map wrongType = readJson(activeBytes); + wrongType.put(field, 1); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(jsonBytes(wrongType))); + } + for (Map.Entry change : + Map.ofEntries( + Map.entry("schema", "wrong/v1"), + Map.entry("lifecycleStatus", "PREPARING"), + Map.entry("lifecycleEpoch", "0"), + Map.entry("rowVersion", "01"), + Map.entry("runtimeRoomInstanceId", "9223372036854775808"), + Map.entry("captureId", UUID.randomUUID().toString()), + Map.entry("graphSha256", "a".repeat(64)), + Map.entry("preparationInputDigest", "sha256:" + "a".repeat(64)), + Map.entry("launchBindingBytesBase64", "e30="), + Map.entry("startLocation", Map.of()), + Map.entry("operationalRegionAssignments", Map.of()), + Map.entry("extra", true)) + .entrySet()) { + Map changed = readJson(activeBytes); + changed.put(change.getKey(), change.getValue()); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(jsonBytes(changed))); + } + for (String field : + new String[] { + "canonicalGameInstanceId", + "controlPlaneRequestId", + "readRequestId", + "schemaVersion", + "publicProduction", + "extra" + }) { + Map changed = readJson(activeBytes); + @SuppressWarnings("unchecked") + Map changedLifecycleRequest = (Map) changed.get("request"); + changedLifecycleRequest.put( + field, + "canonicalGameInstanceId".equals(field) ? UUID.randomUUID().toString() : "changed"); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(jsonBytes(changed))); + } + for (String status : new String[] {"FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED"}) { + Map changed = readJson(activeBytes); + changed.put("lifecycleStatus", status); + invalidLifecycleCarriers.add(Base64.getEncoder().encodeToString(jsonBytes(changed))); + } + for (String carrier : invalidLifecycleCarriers) { + Map invalidResult = readJson(activationResultBytes); + invalidResult.put("lifecycleEvidenceBytesBase64", carrier); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes, + jsonBytes(invalidResult)); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + } + + for (Map.Entry regressingCounter : + Map.of("lifecycleEpoch", "2", "rowVersion", "0").entrySet()) { + String assertionDescription = + "Committed ACTIVE lifecycle must reject a decrease in " + regressingCounter.getKey(); + Map regressingLifecycle = readJson(activeBytes); + regressingLifecycle.put(regressingCounter.getKey(), regressingCounter.getValue()); + Map regressingResult = readJson(activationResultBytes); + regressingResult.put( + "lifecycleEvidenceBytesBase64", + Base64.getEncoder().encodeToString(jsonBytes(regressingLifecycle))); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes, + jsonBytes(regressingResult), + "COMMITTED", + assertionDescription); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + } + + Map invalidTerminalCode = readJson(activationResultBytes); + invalidTerminalCode.put("terminalCode", "FENCED_ABORT"); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes, + jsonBytes(invalidTerminalCode)); + Map invalidOutcome = readJson(activationResultBytes); + invalidOutcome.put("outcome", "ABORTED"); + invalidOutcome.put("terminalCode", "FENCED_ABORT"); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes, + jsonBytes(invalidOutcome)); + + Map changedCapture = readJson(accountEvidenceBytes); + byte[] wrongCapture = bytes("substituted capture reference"); + changedCapture.put( + "originalSourceCaptureReferenceBytesBase64", + Base64.getEncoder().encodeToString(wrongCapture)); + changedCapture.put("originalSourceCaptureReferenceSha256", hash(wrongCapture)); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedCapture), + activationResultBytes); + + Map changedRequest = readJson(accountEvidenceBytes); + changedRequest.put( + "requestBytesBase64", + Base64.getEncoder().encodeToString(bytes("{\"schema\":\"substituted-request/v1\"}"))); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedRequest), + activationResultBytes); + + Map changedSources = readJson(accountEvidenceBytes); + changedSources.put( + "sourceEvidenceVector", + java.util.List.of(Base64.getEncoder().encodeToString(bytes("substituted source")))); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedSources), + activationResultBytes); + + byte[] terminalBytes = + terminalBytes( + id, protectionFence, activationRequestId, accountEvidenceBytes, activationResultBytes); + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + id, + "activation_protection_fence", + protectionFence, + "world_activation_request_id", + activationRequestId, + "world_activation_fence", + 29L, + "outcome", + "COMMITTED", + "account_protection_evidence_bytes", + accountEvidenceBytes, + "terminal_bytes", + terminalBytes, + "terminal_digest", + "sha256:" + hash(terminalBytes))); + + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_activation_protection_settlements " + + "SET outcome = outcome WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("activation settlement is immutable"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "DELETE FROM account_start_session_activation_protection_settlements " + + "WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("activation settlement is immutable"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "TRUNCATE account_start_session_activation_protection_settlements"))) + .hasMessageContaining("activation settlement is immutable"); + + for (String guard : + new String[] { + "account_control_ui_hold_required_sources(text[])", + "account_draft_authorization_source_change_guard()", + "account_hosted_terms_disclosure_handoff_guard()" + }) { + String guardDefinition = + fixture + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", guard) + .get(0, String.class); + assertThat(guardDefinition) + .contains("account_ss_admission_assert_no_pending") + .contains("account_start_session_world_participations"); + } + String pendingProtectionDefinition = + fixture + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef('account_ss_admission_assert_no_pending(text[])'::regprocedure)") + .get(0, String.class); + assertThat(pendingProtectionDefinition) + .contains("account_start_session_admission_protection_sources") + .contains("account_ss_admission_is_settled") + .contains("account_start_session_activation_protection_settlements"); + } + + @Test + void retainedMalformedPreparingLifecycleCannotSettleAfterV1004_2Upgrade() throws Exception { + for (String malformedCounter : + List.of("missing lifecycleEpoch", "missing rowVersion", "numeric lifecycleEpoch")) { + Fixture fixture = fixture("1003"); + CurrentnessCase valid = currentnessCase(fixture, Instant.now().plusSeconds(120)); + Map request = readJson(valid.requestBytes()); + byte[] validPreparingBytes = + Base64.getDecoder().decode((String) request.get("preparingEvidenceBytesBase64")); + Map malformedPreparing = readJson(validPreparingBytes); + if (malformedCounter.startsWith("missing ")) { + malformedPreparing.remove(malformedCounter.substring("missing ".length())); + } else { + malformedPreparing.put("lifecycleEpoch", 3); + } + byte[] malformedPreparingBytes = jsonBytes(malformedPreparing); + assertThatThrownBy( + () -> WorldCanonicalInstanceLifecycleEvidence.fromStored(malformedPreparingBytes)) + .as("retained PREPARING evidence with %s is not a closed lifecycle", malformedCounter) + .isInstanceOf(IllegalArgumentException.class); + request.put( + "preparingEvidenceBytesBase64", + Base64.getEncoder().encodeToString(malformedPreparingBytes)); + CurrentnessCase malformed = + new CurrentnessCase( + jsonBytes(request), + valid.operationIdentityBytes(), + valid.operationIdentityDigest(), + valid.ownerAttemptId(), + valid.expiryText()); + + // V1003 admitted this exact structurally bound PREPARING carrier. The later migrations + // preserve it and harden settlement; this does not represent authenticated World creation. + acquireProtection(fixture, malformed); + var stored = + fixture + .dsl() + .fetchSingle( + "SELECT activation_protection_id, activation_protection_fence, acquired_at, " + + "world_preparing_evidence FROM account_start_session_activation_protections"); + UUID protectionId = stored.get("activation_protection_id", UUID.class); + long protectionFence = stored.get("activation_protection_fence", Long.class); + assertThat(stored.get("world_preparing_evidence", byte[].class)) + .isEqualTo(malformedPreparingBytes); + OffsetDateTime acquiredAt = stored.get("acquired_at", OffsetDateTime.class); + String sourceKey = + fixture + .dsl() + .fetchSingle( + "SELECT source_key FROM account_start_session_activation_protection_sources " + + "ORDER BY source_key LIMIT 1") + .get("source_key", String.class); + String protectionRowsQuery = + "SELECT jsonb_build_object('row', to_jsonb(p), 'xmin', p.xmin::TEXT)::TEXT FROM " + + "account_start_session_activation_protections p ORDER BY activation_protection_id"; + String sourceRowsQuery = + "SELECT jsonb_build_object('row', to_jsonb(s), 'xmin', s.xmin::TEXT)::TEXT FROM " + + "account_start_session_activation_protection_sources s " + + "ORDER BY activation_protection_id, source_key"; + var pendingRows = fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class); + var retainedSources = fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class); + assertThat(pendingRows).hasSize(1); + assertThat(retainedSources).hasSize(2); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + + Flyway v1004 = activationFlyway(fixture.dataSource(), "1004"); + assertThat(v1004.migrate().migrationsExecuted).isEqualTo(1); + v1004.validate(); + Flyway v1004_1 = activationFlyway(fixture.dataSource(), "1004.1"); + assertThat(v1004_1.migrate().migrationsExecuted).isEqualTo(1); + v1004_1.validate(); + String previousHistoryQuery = + "SELECT installed_rank || ':' || version || ':' || script || ':' " + + "|| checksum || ':' || success FROM flyway_schema_history " + + "WHERE version IS NOT NULL AND version <> '1004.2' ORDER BY installed_rank"; + var previousHistory = fixture.dsl().fetch(previousHistoryQuery).getValues(0, String.class); + Flyway v1004_2 = activationFlyway(fixture.dataSource(), "1004.2"); + assertThat(v1004_2.migrate().migrationsExecuted).isEqualTo(1); + v1004_2.validate(); + assertThat(fixture.dsl().fetch(previousHistoryQuery).getValues(0, String.class)) + .isEqualTo(previousHistory); + assertThat(fixture.dsl().fetch(protectionRowsQuery).getValues(0, String.class)) + .isEqualTo(pendingRows); + assertThat(fixture.dsl().fetch(sourceRowsQuery).getValues(0, String.class)) + .isEqualTo(retainedSources); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT world_preparing_evidence FROM account_start_session_activation_protections") + .get(0, byte[].class)) + .isEqualTo(malformedPreparingBytes); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + + UUID activationRequestId = UUID.fromString((String) request.get("worldActivationRequestId")); + byte[][] sourceEvidenceBytes = + fixture + .dsl() + .fetch( + "SELECT source_evidence FROM account_start_session_activation_protection_sources " + + "ORDER BY account_publication_authorization_source_sort_key(source_key)") + .stream() + .map(row -> row.get("source_evidence", byte[].class)) + .toArray(byte[][]::new); + byte[] evidence = + accountEvidence( + protectionId, + protectionFence, + acquiredAt, + malformed.requestBytes(), + bytes("{}"), + sourceEvidenceBytes); + byte[] result = activationResult(activationRequestId, malformedPreparingBytes, "COMMITTED"); + assertSettlementInsertRejected( + fixture, + protectionId, + protectionFence, + activationRequestId, + evidence, + result, + "COMMITTED", + "V1004.2 must reject retained PREPARING evidence with " + malformedCounter); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + } + } + + @Test + void noncanonicalActivationRequestUuidCannotAcquireProtectionOrBlockSourceWriters() + throws Exception { + Fixture fixture = fixture("1004.1"); + Flyway upgrade = activationFlyway(fixture.dataSource(), "1004.2"); + assertThat(upgrade.migrate().migrationsExecuted).isEqualTo(1); + upgrade.validate(); + + CurrentnessCase valid = currentnessCase(fixture, Instant.now().plusSeconds(120)); + Map request = readJson(valid.requestBytes()); + String uppercaseActivationId = + UUID.fromString("abcdefab-cdef-4abc-8def-abcdefabcdef").toString().toUpperCase(Locale.ROOT); + request.put("worldActivationRequestId", uppercaseActivationId); + CurrentnessCase noncanonical = + new CurrentnessCase( + jsonBytes(request), + valid.operationIdentityBytes(), + valid.operationIdentityDigest(), + valid.ownerAttemptId(), + valid.expiryText()); + + assertThatThrownBy(() -> acquireProtection(fixture, noncanonical)) + .as("activation request UUID spelling must match canonical PostgreSQL UUID text") + .isInstanceOf(RuntimeException.class) + .hasMessageContaining( + "Activation protection does not retain its exact canonical request fields") + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); + assertThat(fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) + .isZero(); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_sources"))) + .isZero(); + String sourceKey = + fixture + .dsl() + .fetchSingle( + "SELECT source_key FROM account_start_session_world_participation_sources " + + "ORDER BY source_key LIMIT 1") + .get("source_key", String.class); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); + } + + @Test + void noncanonicalActivationBase64CarriersCannotAcquireProtectionOrBlockSourceWriters() + throws Exception { + Map whitespaceVariants = new LinkedHashMap<>(); + whitespaceVariants.put("newline", '\n'); + whitespaceVariants.put("space", ' '); + whitespaceVariants.put("tab", '\t'); + whitespaceVariants.put("carriage return", '\r'); + Map carrierFields = new LinkedHashMap<>(); + carrierFields.put("tuple", "originalPostAuthorizationTupleBytesBase64"); + carrierFields.put("projection", "accountRedemptionProjectionBytesBase64"); + carrierFields.put("launch read", "gameSessionLaunchReadEvidenceBytesBase64"); + carrierFields.put("PREPARING lifecycle", "preparingEvidenceBytesBase64"); + + for (Map.Entry carrier : carrierFields.entrySet()) { + for (Map.Entry whitespace : whitespaceVariants.entrySet()) { + Fixture fixture = fixture("1004.2"); + Flyway upgrade = activationFlyway(fixture.dataSource(), "1004.3"); + assertThat(upgrade.migrate().migrationsExecuted).isEqualTo(1); + upgrade.validate(); + + CurrentnessCase valid = currentnessCase(fixture, Instant.now().plusSeconds(120)); + Map request = readJson(valid.requestBytes()); + String canonicalBase64 = (String) request.get(carrier.getValue()); + request.put( + carrier.getValue(), + canonicalBase64.substring(0, 4) + whitespace.getValue() + canonicalBase64.substring(4)); + CurrentnessCase noncanonical = + new CurrentnessCase( + jsonBytes(request), + valid.operationIdentityBytes(), + valid.operationIdentityDigest(), + valid.ownerAttemptId(), + valid.expiryText()); + + assertThatThrownBy(() -> acquireProtection(fixture, noncanonical)) + .as( + "%s Base64 carrier with %s must be rejected before protection acquisition", + carrier.getKey(), whitespace.getKey()) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining( + "Activation protection Base64 fields must use canonical encodings") + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); + assertThat( + fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) + .isZero(); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_sources"))) + .isZero(); + String sourceKey = + fixture + .dsl() + .fetchSingle( + "SELECT source_key FROM account_start_session_world_participation_sources " + + "ORDER BY source_key LIMIT 1") + .get("source_key", String.class); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); + } + } + } + + @Test + void malformedPreparingLifecycleCannotAcquireProtectionOrBlockSourceWriters() throws Exception { + Fixture fixture = fixture(); + CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(120)); + Map request = readJson(current.requestBytes()); + byte[] preparingBytes = + Base64.getDecoder().decode((String) request.get("preparingEvidenceBytesBase64")); + java.util.List malformed = new java.util.ArrayList<>(); + Map extraOuter = readJson(preparingBytes); + extraOuter.put("extra", true); + malformed.add(jsonBytes(extraOuter)); + for (String field : + new String[] { + "launchBindingBytesBase64", + "startLocation", + "runtimeRoomInstanceId", + "lifecycleEpoch", + "rowVersion", + "captureId", + "graphSha256", + "preparationInputDigest", + "operationalRegionAssignments" + }) { + Map missing = readJson(preparingBytes); + missing.remove(field); + malformed.add(jsonBytes(missing)); + Map wrongType = readJson(preparingBytes); + wrongType.put(field, 1); + malformed.add(jsonBytes(wrongType)); + } + for (Map.Entry change : + Map.ofEntries( + Map.entry("runtimeRoomInstanceId", "0"), + Map.entry("lifecycleEpoch", "01"), + Map.entry("rowVersion", "9223372036854775808"), + Map.entry("captureId", "00000000-0000-0000-0000-000000000000"), + Map.entry("graphSha256", "invalid"), + Map.entry("preparationInputDigest", "invalid"), + Map.entry("launchBindingBytesBase64", "%%%"), + Map.entry("startLocation", Map.of()), + Map.entry("operationalRegionAssignments", Map.of())) + .entrySet()) { + Map changed = readJson(preparingBytes); + changed.put(change.getKey(), change.getValue()); + malformed.add(jsonBytes(changed)); + } + for (Map.Entry change : + Map.ofEntries( + Map.entry("extra", true), + Map.entry("publicProduction", false), + Map.entry("playableStateScope", "ISOLATED"), + Map.entry("schemaVersion", 2), + Map.entry("readRequestId", "00000000-0000-0000-0000-000000000000"), + Map.entry("worldSlug", "INVALID"), + Map.entry("expectedDescriptorRequestDigest", "invalid"), + Map.entry("canonicalVersionId", 1)) + .entrySet()) { + Map changed = readJson(preparingBytes); + @SuppressWarnings("unchecked") + Map changedRequest = (Map) changed.get("request"); + changedRequest.put(change.getKey(), change.getValue()); + malformed.add(jsonBytes(changed)); + } + String preparingJson = new String(preparingBytes, StandardCharsets.UTF_8); + for (String value : + new String[] { + preparingJson.replace("\"schemaVersion\":1", "\"schemaVersion\":1e0"), + preparingJson.replace("\"schemaVersion\":1", "\"schemaVersion\":1e+0"), + preparingJson.replace("\"schemaVersion\":1", "\"schemaVersion\":0,\"schemaVersion\":1") + }) { + malformed.add(bytes(value)); + } + Map oversizedRequestId = readJson(preparingBytes); + @SuppressWarnings("unchecked") + Map oversizedLifecycleRequest = + (Map) oversizedRequestId.get("request"); + // 128 Unicode code points occupy 129 Java UTF-16 units. + oversizedLifecycleRequest.put("controlPlaneRequestId", "a".repeat(127) + "\uD83D\uDE00"); + byte[] oversizedRequestIdBytes = jsonBytes(oversizedRequestId); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_validate_lifecycle(?, 'PREPARING')", + oversizedRequestIdBytes))) + .hasMessageContaining("Activation lifecycle request text is invalid"); + malformed.add(oversizedRequestIdBytes); + String sourceKey = + fixture + .dsl() + .fetchSingle( + "SELECT source_key FROM account_start_session_world_participation_sources ORDER BY source_key LIMIT 1") + .get(0, String.class); + for (byte[] invalidPreparing : malformed) { + assertThatThrownBy(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(invalidPreparing)) + .isInstanceOf(IllegalArgumentException.class); + Map changedRequest = readJson(current.requestBytes()); + changedRequest.put( + "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(invalidPreparing)); + CurrentnessCase changed = + new CurrentnessCase( + jsonBytes(changedRequest), + current.operationIdentityBytes(), + current.operationIdentityDigest(), + current.ownerAttemptId(), + current.expiryText()); + assertThatThrownBy(() -> acquireProtection(fixture, changed)) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) + postgresFailure = postgresFailure.getCause(); + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> + assertThat(sqlFailure.getSQLState()) + .as(sqlFailure.getMessage()) + .isEqualTo("23514")); + }); + assertThat( + fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) + .isZero(); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_sources"))) + .isZero(); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); + } + acquireProtection(fixture, current); + assertThat(fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) + .isEqualTo(1); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + } + + @Test + void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() throws Exception { + Fixture fixture = fixture(); + CurrentnessCase valid = currentnessCase(fixture, Instant.now().plusSeconds(60)); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + valid.requestBytes(), + valid.operationIdentityBytes(), + valid.operationIdentityDigest())); + + Map changedProjectionRequest = + JSON.readValue(valid.requestBytes(), new tools.jackson.core.type.TypeReference<>() {}); + byte[] originalTuple = + Base64.getDecoder() + .decode( + (String) changedProjectionRequest.get("originalPostAuthorizationTupleBytesBase64")); + byte[] differentSpelling = + (" " + new String(originalTuple, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8); + changedProjectionRequest.put( + "accountRedemptionProjectionBytesBase64", + Base64.getEncoder().encodeToString(differentSpelling)); + byte[] changedProjection = jsonBytes(changedProjectionRequest); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + changedProjection, + valid.operationIdentityBytes(), + valid.operationIdentityDigest()))) + .hasMessageContaining( + "Activation protection differs from original Account redemption or capture"); + + byte[] changedAttempt = + activationRequest(valid, UUID.randomUUID().toString(), valid.expiryText(), "PREPARING"); + assertCurrentnessRejected(fixture, changedAttempt, valid.operationIdentityBytes()); + + byte[] changedWorldState = + activationRequest(valid, valid.ownerAttemptId().toString(), valid.expiryText(), "ACTIVE"); + assertCurrentnessRejected(fixture, changedWorldState, valid.operationIdentityBytes()); + + Fixture expiredFixture = fixture(); + CurrentnessCase expired = currentnessCase(expiredFixture, Instant.now().minusSeconds(1)); + assertCurrentnessRejected( + expiredFixture, expired.requestBytes(), expired.operationIdentityBytes()); + } + + @Test + void abortedSettlementPreservesTerminalCodeFenceWithoutRequiringActiveLifecycle() + throws Exception { + Fixture fixture = fixture(); + CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(60)); + acquireProtection(fixture, current); + var stored = + fixture + .dsl() + .fetchSingle( + "SELECT activation_protection_id, activation_protection_fence, acquired_at " + + "FROM account_start_session_activation_protections"); + UUID id = stored.get("activation_protection_id", UUID.class); + long fence = stored.get("activation_protection_fence", Long.class); + Map request = readJson(current.requestBytes()); + UUID activationId = UUID.fromString((String) request.get("worldActivationRequestId")); + var sources = + fixture + .dsl() + .fetch( + "SELECT source_key, source_evidence FROM " + + "account_start_session_activation_protection_sources " + + "ORDER BY account_publication_authorization_source_sort_key(source_key)"); + byte[] evidence = + accountEvidence( + id, + fence, + stored.get("acquired_at", OffsetDateTime.class), + current.requestBytes(), + bytes("{}"), + sources.stream() + .map(row -> row.get("source_evidence", byte[].class)) + .toArray(byte[][]::new)); + Map result = + readJson( + activationResult( + activationId, + Base64.getDecoder().decode((String) request.get("preparingEvidenceBytesBase64")), + "ABORTED")); + result.put("lifecycleEvidenceBytesBase64", null); + result.put("terminalCode", ""); + assertSettlementInsertRejected( + fixture, id, fence, activationId, evidence, jsonBytes(result), "ABORTED"); + result.put("terminalCode", null); + assertSettlementInsertRejected( + fixture, id, fence, activationId, evidence, jsonBytes(result), "ABORTED"); + result.put("terminalCode", "FENCED_ABORT"); + byte[] terminal = terminalBytes(id, fence, activationId, evidence, jsonBytes(result)); + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + id, + "activation_protection_fence", + fence, + "world_activation_request_id", + activationId, + "world_activation_fence", + 29L, + "outcome", + "ABORTED", + "account_protection_evidence_bytes", + evidence, + "terminal_bytes", + terminal, + "terminal_digest", + "sha256:" + hash(terminal))); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sources.get(0).get("source_key", String.class))); + } + + private static void assertSettlementInsertRejected( + Fixture fixture, + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes) { + assertSettlementInsertRejected( + fixture, + protectionId, + protectionFence, + activationRequestId, + protectionEvidenceBytes, + activationResultBytes, + "COMMITTED"); + } + + private static void assertSettlementInsertRejected( + Fixture fixture, + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes, + String outcome) { + assertSettlementInsertRejected( + fixture, + protectionId, + protectionFence, + activationRequestId, + protectionEvidenceBytes, + activationResultBytes, + outcome, + "Invalid activation settlement must be rejected"); + } + + private static void assertSettlementInsertRejected( + Fixture fixture, + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes, + String outcome, + String assertionDescription) { + byte[] terminalBytes = + terminalBytes( + protectionId, + protectionFence, + activationRequestId, + protectionEvidenceBytes, + activationResultBytes); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + protectionId, + "activation_protection_fence", + protectionFence, + "world_activation_request_id", + activationRequestId, + "world_activation_fence", + 29L, + "outcome", + outcome, + "account_protection_evidence_bytes", + protectionEvidenceBytes, + "terminal_bytes", + terminalBytes, + "terminal_digest", + "sha256:" + hash(terminalBytes)))) + .as(assertionDescription) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> + assertThat(sqlFailure.getSQLState()) + .as(sqlFailure.getMessage()) + .isEqualTo("23514")); + }); + } + + private static byte[] accountEvidence( + UUID protectionId, + long protectionFence, + OffsetDateTime acquiredAt, + byte[] requestBytes, + byte[] captureReference, + byte[]... sourceEvidence) + throws Exception { + Map value = new LinkedHashMap<>(); + value.put("schema", "account-start-session-activation-protection-evidence/v1"); + value.put("requestBytesBase64", Base64.getEncoder().encodeToString(requestBytes)); + value.put("accountProtectionId", protectionId.toString()); + value.put("accountProtectionFence", Long.toString(protectionFence)); + value.put("acquiredAt", timestamp(acquiredAt)); + value.put( + "originalSourceCaptureReferenceBytesBase64", + Base64.getEncoder().encodeToString(captureReference)); + value.put("originalSourceCaptureReferenceSha256", hash(captureReference)); + value.put( + "sourceEvidenceVector", + java.util.Arrays.stream(sourceEvidence).map(Base64.getEncoder()::encodeToString).toList()); + return jsonBytes(value); + } + + private static byte[] accountEvidenceBytes(Map value) throws Exception { + return jsonBytes(value); + } + + private static byte[] activationResult( + UUID activationRequestId, byte[] preparingEvidence, String outcome) throws Exception { + Map active = readJson(preparingEvidence); + active.put("lifecycleStatus", "ACTIVE"); + active.put("lifecycleEpoch", "4"); + active.put("rowVersion", "1"); + @SuppressWarnings("unchecked") + Map activeRequest = (Map) active.get("request"); + activeRequest.put("readRequestId", UUID.randomUUID().toString()); + byte[] activeBytes = jsonBytes(active); + assertThat(WorldCanonicalInstanceLifecycleEvidence.fromStored(activeBytes).lifecycleStatus()) + .isEqualTo("ACTIVE"); + Map preparing = readJson(preparingEvidence); + @SuppressWarnings("unchecked") + Map lifecycleRequest = (Map) preparing.get("request"); + lifecycleRequest.remove("readRequestId"); + Map activationRequest = new LinkedHashMap<>(); + activationRequest.put("schema", "world-canonical-instance-activation-request/v1"); + activationRequest.put("activationRequestId", activationRequestId.toString()); + activationRequest.put("preparingEvidence", preparing); + byte[] activationRequestBytes = jsonBytes(activationRequest); + + Map result = new LinkedHashMap<>(); + result.put("schema", "world-canonical-instance-activation-result/v1"); + result.put("activationRequestId", activationRequestId.toString()); + result.put("requestDigest", "sha256:" + hash(activationRequestBytes)); + result.put("requestBytesBase64", Base64.getEncoder().encodeToString(activationRequestBytes)); + result.put( + "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(preparingEvidence)); + result.put("outcome", outcome); + result.put("terminalCode", "COMMITTED".equals(outcome) ? null : "FENCED_ABORT"); + result.put("lifecycleEvidenceBytesBase64", Base64.getEncoder().encodeToString(activeBytes)); + return jsonBytes(result); + } + + private static byte[] terminalBytes( + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes) { + Map terminal = new LinkedHashMap<>(); + terminal.put("schema", "world-original-start-session-activation-terminal-evidence/v1"); + terminal.put("activationRequestId", activationRequestId.toString()); + terminal.put("accountProtectionId", protectionId.toString()); + terminal.put("accountProtectionFence", Long.toString(protectionFence)); + terminal.put("worldActivationFence", "29"); + terminal.put( + "accountProtectionEvidenceBytesBase64", + Base64.getEncoder().encodeToString(protectionEvidenceBytes)); + terminal.put( + "activationResultBytesBase64", Base64.getEncoder().encodeToString(activationResultBytes)); + terminal.put("activationResultSha256", hash(activationResultBytes)); + try { + return jsonBytes(terminal); + } catch (Exception impossible) { + throw new IllegalStateException("Synthetic terminal receipt must be canonical", impossible); + } + } + + private static Map readJson(byte[] bytes) throws Exception { + return JSON.readValue(bytes, new tools.jackson.core.type.TypeReference<>() {}); + } + + private static String timestamp(OffsetDateTime value) { + return DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") + .withZone(ZoneOffset.UTC) + .format(value.toInstant()); + } + + private static void assertCurrentnessRejected( + Fixture fixture, byte[] requestBytes, byte[] operationIdentityBytes) { + String operationDigest = "sha256:" + hash(operationIdentityBytes); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + requestBytes, + operationIdentityBytes, + operationDigest))) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> + assertThat(sqlFailure.getSQLState()) + .as(sqlFailure.getMessage()) + .isEqualTo("23514")); + }); + } + + private static CurrentnessCase currentnessCase(Fixture fixture, Instant originalLease) + throws Exception { + return currentnessCase(fixture, originalLease, 0); + } + + private static CurrentnessCase currentnessCase( + Fixture fixture, Instant originalLease, int padding) throws Exception { + return currentnessCase(fixture, originalLease, padding, 0L); + } + + private static CurrentnessCase currentnessCase( + Fixture fixture, Instant originalLease, int padding, long rowVersion) throws Exception { + WorldCanonicalInstanceLifecycleEvidence lifecycle = + AuthoringFixtures.lifecycleEvidence("PREPARING", 3L); + UUID tenantId = lifecycle.request().canonicalTenantId(); + UUID gameInstanceId = lifecycle.request().canonicalGameInstanceId(); + UUID participationId = UUID.randomUUID(); + UUID ownerMutationId = UUID.randomUUID(); + UUID ownerAttemptId = UUID.randomUUID(); + UUID activationRequestId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID issuanceOperationId = UUID.randomUUID(); + long ownerFence = 11L; + long issuanceFence = 9L; + long sourceVersion = 13L; + long sourceFence = 17L; + String requestId = lifecycle.request().controlPlaneRequestId(); + String fingerprint = "arfp/v1/activation-test/" + "a".repeat(64); + OffsetDateTime dbNow = + fixture.dsl().fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class); + Instant normalizedNow = dbNow.toInstant().truncatedTo(ChronoUnit.MICROS); + Instant normalizedLease = originalLease.truncatedTo(ChronoUnit.MICROS); + Instant issuedAt = normalizedNow.minusSeconds(10); + Instant redeemedAt = normalizedNow.minusSeconds(5); + Instant referenceExpiry = normalizedNow.plusSeconds(180); + Instant responseExpiry = normalizedNow.plusSeconds(220); + String expiryText = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") + .withZone(ZoneOffset.UTC) + .format(normalizedLease); + + Map preAuthorizationValue = + Map.of( + "scope", + Map.of("targetNamespace", "test", "tenantId", tenantId.toString()), + "fixturePadding", + "x".repeat(Math.min(6000, padding))); + byte[] preAuthorization = jsonBytes(preAuthorizationValue); + Map bundleValue = + Map.of( + "issuanceOperationIdentity", + Map.of("issuanceOperationId", issuanceOperationId.toString()), + "fixturePadding", + "x".repeat(padding - Math.min(6000, padding))); + byte[] authorityBundle = jsonBytes(bundleValue); + byte[] tuple = + jsonBytes( + Map.of( + "controlPlaneRequestId", + requestId, + "preAuthorizationReservationTuple", + preAuthorizationValue, + "authorizationReferenceFingerprint", + fingerprint, + "issuanceFence", + Long.toString(issuanceFence), + "authorityEvidenceBundle", + bundleValue)); + // Current-use integrity preserves the complete stipulated original tuple without scalarizing + // it. + byte[] projection = tuple.clone(); + // Java String ordering is UTF-16: the supplementary key precedes the BMP private-use key. + var sourceEvidence = + java.util.List.of( + new SourceEvidence( + SourceKind.HOSTED_TERMS, + tenantId + "-terms-\uD800\uDC00", + "2", + "17", + null, + null, + bytes("supplementary source")), + new SourceEvidence( + SourceKind.HOSTED_TERMS, + tenantId + "-terms-\uE000", + "2", + "17", + null, + null, + bytes("BMP source"))); + byte[] snapshot = + jsonBytes( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + requestId, + "sourceVector", + sourceEvidence.stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList())); + byte[] captureReference = bytes("{}"); + String captureDigest = hash(captureReference); + String snapshotDigest = hash(snapshot); + byte[] attemptBytes = bytes("synthetic-current-original-attempt"); + String preparationInput = "{}"; + String preparationDigest = "sha256:" + hash(bytes(preparationInput)); + + byte[] worldPreparing = + new WorldCanonicalInstanceLifecycleEvidence( + lifecycle.request(), + lifecycle.launchBinding(), + lifecycle.startLocation(), + lifecycle.runtimeRoomInstanceId(), + "PREPARING", + lifecycle.lifecycleEpoch(), + rowVersion, + lifecycle.captureId(), + lifecycle.graphSha256(), + preparationDigest, + lifecycle.operationalRegionAssignments()) + .canonicalBytes(); + byte[] launchRead = bytes("synthetic exact STARTING read"); + byte[] operationIdentity = bytes("activation operation identity"); + String operationDigest = "sha256:" + hash(operationIdentity); + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceEvidence.get(0).key()); + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceEvidence.get(1).key()); + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + insert( + fixture.dsl(), + "account_canonical_tenant_identity_claims", + "canonical_tenant_id", + tenantId, + "identity_kind", + "APPROVED_RETAINED", + "source_operation_id", + UUID.randomUUID(), + "source_account_legacy_tenant_id", + 1L, + "source_target_namespace", + "test", + "source_game_row_id", + 1L, + "source_game_tenant_key", + tenantId.toString()); + insert( + fixture.dsl(), + "account_start_session_authority_captures", + "control_plane_request_id", + requestId, + "account_uuid", + accountId, + "tenant_uuid", + tenantId, + "target_owner", + "game-session-service", + "logging_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "pre_authorization_tuple", + preAuthorization, + "mutation_digest", + "c".repeat(64), + "control_ui_operation_id", + UUID.randomUUID(), + "control_ui_token_jti", + UUID.randomUUID(), + "control_ui_token_hash", + "d".repeat(64), + "control_ui_signer_receipt_sha256", + "e".repeat(64), + "issuance_fence", + issuanceFence, + "issuance_fence_source_version", + sourceVersion, + "captured_at", + OffsetDateTime.ofInstant( + normalizedNow.truncatedTo(ChronoUnit.MILLIS), ZoneOffset.UTC), + "snapshot_sha256", + snapshotDigest, + "canonical_snapshot_bytes", + snapshot, + "source_version", + sourceVersion, + "source_fence", + sourceFence, + "linearization", + "19", + "canonical_sha256", + captureDigest, + "canonical_capture_bytes", + captureReference); + insert( + fixture.dsl(), + "account_start_session_operator_authorizations", + "control_plane_request_id", + requestId, + "pre_authorization_tuple", + preAuthorization, + "mutation_digest", + "c".repeat(64), + "issuance_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "issuance_operation_id", + issuanceOperationId, + "issuance_fence", + issuanceFence, + "bundle_version", + "authorityEvidenceBundle/v1", + "bundle_source_version", + Long.toString(sourceVersion), + "bundle_source_fence", + Long.toString(sourceFence), + "bundle_linearization", + "19", + "authority_evidence_bundle", + authorityBundle, + "authorization_reference_fingerprint", + fingerprint, + "encrypted_response_envelope", + bytes("synthetic response"), + "issued_at", + OffsetDateTime.ofInstant(issuedAt, ZoneOffset.UTC), + "reference_expires_at", + OffsetDateTime.ofInstant(referenceExpiry, ZoneOffset.UTC), + "response_envelope_expires_at", + OffsetDateTime.ofInstant(responseExpiry, ZoneOffset.UTC), + "status", + "REDEEMED", + "redemption_redeemer_workload_uri", + "spiffe://firemud/ns/test/sa/game-session-service", + "redemption_owner_attempt_id", + ownerAttemptId, + "redemption_owner_fence", + ownerFence, + "redeemed_at", + OffsetDateTime.ofInstant(redeemedAt, ZoneOffset.UTC), + "redemption_reference_fingerprint", + fingerprint, + "redemption_authority_evidence_bundle", + authorityBundle); + insert( + fixture.dsl(), + "account_start_session_world_participations", + "participation_id", + participationId, + "control_plane_request_id", + requestId, + "original_post_authorization_tuple", + tuple, + "target_namespace", + "test", + "canonical_tenant_id", + tenantId, + "canonical_game_instance_id", + gameInstanceId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + ownerFence, + "preparation_input_json", + preparationInput, + "preparation_input_digest", + preparationDigest); + for (SourceEvidence source : sourceEvidence) { + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + participationId, + "source_key", + source.key(), + "source_evidence", + source.canonicalBytes()); + } + insert( + fixture.dsl(), + "account_start_session_world_original_attempt_evidence", + "participation_id", + participationId, + "target_namespace", + "test", + "game_session_owner_mutation_id", + ownerMutationId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + ownerFence, + "original_lease_expires_at", + OffsetDateTime.ofInstant(normalizedLease, ZoneOffset.UTC), + "original_response_bytes", + attemptBytes, + "original_response_digest", + "sha256:" + hash(attemptBytes)); + insert( + fixture.dsl(), + "account_start_session_world_participation_settlements", + "participation_id", + participationId, + "outcome", + "COMMITTED", + "world_execution_fence", + 3L, + "terminal_bytes", + bytes("synthetic committed preparation"), + "terminal_digest", + "sha256:" + hash(bytes("synthetic committed preparation"))); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + byte[] requestBytes = + activationRequest( + tuple, + projection, + ownerMutationId, + ownerAttemptId, + ownerFence, + expiryText, + participationId, + fixture + .dsl() + .fetchSingle( + "SELECT participation_fence FROM account_start_session_world_participations " + + "WHERE participation_id = ?", + participationId) + .get("participation_fence", Long.class), + launchRead, + activationRequestId, + worldPreparing); + return new CurrentnessCase( + requestBytes, operationIdentity, operationDigest, ownerAttemptId, expiryText); + } + + private static void acquireProtection(Fixture fixture, CurrentnessCase current) { + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture + .dsl() + .execute( + """ + INSERT INTO account_start_session_activation_protections( + control_plane_request_id, account_world_participation_id, account_world_participation_fence, + original_post_authorization_tuple, account_redemption_projection, + game_session_owner_mutation_id, game_session_owner_attempt_id, game_session_owner_fence, + original_lease_expires_at, target_namespace, canonical_tenant_id, canonical_game_instance_id, + world_activation_request_id, game_session_launch_read_evidence, world_preparing_evidence, + capture_source_version, capture_source_fence, capture_sha256, + capture_reference_bytes, capture_reference_sha256, operation_identity_bytes, + operation_identity_digest, request_binding_bytes, request_binding_digest) + SELECT w.control_plane_request_id, w.participation_id, w.participation_fence, + w.original_post_authorization_tuple, w.original_post_authorization_tuple, + o.game_session_owner_mutation_id, o.game_session_owner_attempt_id, o.game_session_owner_fence, + o.original_lease_expires_at, w.target_namespace, w.canonical_tenant_id, w.canonical_game_instance_id, + (r.value->>'worldActivationRequestId')::uuid, + decode(r.value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'), + decode(r.value->>'preparingEvidenceBytesBase64', 'base64'), + c.source_version, c.source_fence, c.canonical_sha256, + c.canonical_capture_bytes, c.canonical_sha256, ?, ?, ?, ? + FROM account_start_session_world_participations w + JOIN account_start_session_world_original_attempt_evidence o USING(participation_id) + JOIN account_start_session_authority_captures c USING(control_plane_request_id) + CROSS JOIN (SELECT convert_from(?::bytea, 'UTF8')::jsonb AS value) r + WHERE w.participation_id = (r.value->>'accountWorldParticipationId')::uuid + """, + current.operationIdentityBytes(), + current.operationIdentityDigest(), + current.requestBytes(), + "sha256:" + hash(current.requestBytes()), + current.requestBytes()); + fixture + .dsl() + .execute( + """ + INSERT INTO account_start_session_activation_protection_sources( + activation_protection_id, source_key, source_evidence) + SELECT p.activation_protection_id, s.source_key, s.source_evidence + FROM account_start_session_activation_protections p + JOIN account_start_session_world_participation_sources s + ON s.participation_id = p.account_world_participation_id + WHERE p.operation_identity_digest = ? + """, + current.operationIdentityDigest()); + }); + } + + private static byte[] activationRequest( + CurrentnessCase current, String ownerAttemptId, String expiry, String worldStatus) + throws Exception { + Map root = + JSON.readValue(current.requestBytes(), new tools.jackson.core.type.TypeReference<>() {}); + root.put("gameSessionOwnerAttemptId", ownerAttemptId); + root.put("originalLeaseExpiresAt", expiry); + byte[] preparing = + Base64.getDecoder().decode((String) root.get("preparingEvidenceBytesBase64")); + Map world = + JSON.readValue(preparing, new tools.jackson.core.type.TypeReference<>() {}); + world.put("lifecycleStatus", worldStatus); + root.put("preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(jsonBytes(world))); + return jsonBytes(root); + } + + private static byte[] activationRequest( + byte[] tuple, + byte[] projection, + UUID ownerMutationId, + UUID ownerAttemptId, + long ownerFence, + String expiry, + UUID participationId, + long participationFence, + byte[] launchRead, + UUID activationRequestId, + byte[] preparingEvidence) + throws Exception { + Map value = new LinkedHashMap<>(); + value.put("schema", "account-start-session-activation-protection-request/v1"); + value.put( + "originalPostAuthorizationTupleBytesBase64", Base64.getEncoder().encodeToString(tuple)); + value.put( + "accountRedemptionProjectionBytesBase64", Base64.getEncoder().encodeToString(projection)); + value.put("gameSessionOwnerMutationId", ownerMutationId.toString()); + value.put("gameSessionOwnerAttemptId", ownerAttemptId.toString()); + value.put("gameSessionOwnerFence", Long.toString(ownerFence)); + value.put("originalLeaseExpiresAt", expiry); + value.put("accountWorldParticipationId", participationId.toString()); + value.put("accountWorldParticipationFence", Long.toString(participationFence)); + value.put( + "gameSessionLaunchReadEvidenceBytesBase64", Base64.getEncoder().encodeToString(launchRead)); + value.put("worldActivationRequestId", activationRequestId.toString()); + value.put( + "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(preparingEvidence)); + byte[] result = jsonBytes(value); + return result; + } + + private static byte[] jsonBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static Fixture fixture() { + return fixture("latest"); + } + + private static Fixture fixture(String target) { + String schema = "ss_activation_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + activationFlyway(source, target).migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + String requestId = "activation-test/" + UUID.randomUUID(); + return new Fixture(dsl, transaction, requestId, source); + } + + private static Flyway activationFlyway(DriverManagerDataSource source, String target) { + return Flyway.configure() + .dataSource(source) + .schemas(source.getSchema()) + .defaultSchema(source.getSchema()) + .placeholders(Map.of("serviceSchema", source.getSchema())) + .locations("classpath:db/migration") + .target(target) + .load(); + } + + private static void insert(DSLContext dsl, String table, Object... fields) { + Map, Object> values = new java.util.LinkedHashMap<>(); + for (int index = 0; index < fields.length; index += 2) { + values.put(DSL.field(DSL.name((String) fields[index])), fields[index + 1]); + } + dsl.insertInto(DSL.table(DSL.name(table))).set(values).execute(); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String hash(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transaction, + String requestId, + DriverManagerDataSource dataSource) {} + + private record CurrentnessCase( + byte[] requestBytes, + byte[] operationIdentityBytes, + String operationIdentityDigest, + UUID ownerAttemptId, + String expiryText) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java new file mode 100644 index 0000000000..fbfedc3a4c --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -0,0 +1,1854 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationInfo; +import org.flywaydb.core.api.MigrationState; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.postgresql.util.PSQLException; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * SQL integrity and source-writer definitions. Upstream Account capture, redeemed authorization, + * World settlement and Game Session observation are explicitly stipulated with upstream triggers + * disabled. Current admission guards remain enabled for acquisition and all assertions. These + * fixtures are not genuine authenticated Account/World/Game Session producer or consumer proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionAdmissionProtectionPostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + // Exact installed parent artifacts at Entity source 9526190049a86feef40cd616ec7b5eb931247e8b. + private static final Set PARENT_MIGRATION_SCRIPTS = + Set.of( + "V100__account_jwt_signer_materialization_readback.sql", + "V101__account_jwt_jwks_prepublication.sql", + "V103__account_jwt_readiness_probes.sql", + "V106__account_jwt_signer_promotion_lifecycle.sql", + "V107__account_jwt_readiness_single_delivery_claims.sql", + "V109__account_jwt_validator_inventory_snapshots.sql", + "V10__platform_fee.sql", + "V11__donation_flag.sql", + "V123__account_jwt_readiness_per_pod_closure.sql", + "V124__account_jwt_readiness_version_aware_delivery_claim_guard.sql", + "V125__account_jwt_signer_promotion_receipt_binding.sql", + "V126.1__start_session_operator_response_envelope_erasure.sql", + "V126.2__account_control_ui_registry_cleanup_deadline.sql", + "V126.3__start_session_response_envelope_bounds.sql", + "V126__start_session_operator_authorization.sql", + "V12__virtual_currency.sql", + "V137.1__account_platform_restriction_lifecycle_consistency.sql", + "V137.2__account_platform_restriction_outbox_column_qualification.sql", + "V137.3__account_security_guard_source_row_type.sql", + "V137__account_platform_restriction_revision_receipts.sql", + "V13__creator_share.sql", + "V140__account_gameplay_admission_lease_operations.sql", + "V141__account_admission_unknown_decision_abort.sql", + "V142__account_admission_durable_commit_confirmation.sql", + "V143__account_global_pending_admission_fences.sql", + "V144__account_admission_original_ack_receipt.sql", + "V145__retire_experimental_admission_confirmation_writes.sql", + "V146__account_original_ack_pg18_fresh_insert.sql", + "V147__account_gameplay_delegation_issuance.sql", + "V148__account_auth_evidence_bundles.sql", + "V149__account_gameplay_delegation_encrypted_response.sql", + "V14__tenant_indexes.sql", + "V150__account_gameplay_delegation_committed_issuance.sql", + "V151__account_gameplay_token_identity_fences.sql", + "V152__account_gameplay_login_credential_request_binding.sql", + "V153__account_gameplay_delegation_decimal_source_versions.sql", + "V154__account_auth_evidence_checkpoint_key_count.sql", + "V155__account_auth_evidence_shared_issuer_guard.sql", + "V156__account_gameplay_commit_bundle_source_fence.sql", + "V157.1__account_gameplay_token_fence_truncate_guard.sql", + "V157__account_gameplay_authority_shared_issuer_guard.sql", + "V158__account_start_session_authority_captures.sql", + "V159__start_session_world_participation.sql", + "V15__account_tenant_membership.sql", + "V160.1__start_session_operator_bundle_source_fence.sql", + "V160__start_session_world_original_attempt_evidence.sql", + "V16__profile_presence_visibility.sql", + "V17__account_realm_access_grants.sql", + "V18__account_email_login_challenges.sql", + "V19__account_login_auth_modes.sql", + "V1__init.sql", + "V20__account_lifecycle_state.sql", + "V21__validate_account_lifecycle_state.sql", + "V22__canonicalize_account_emails.sql", + "V23__validate_account_email_canonical_check.sql", + "V24__account_credential_expiry_indexes.sql", + "V25__scope_profile_identity.sql", + "V26__global_registration_join_evidence.sql", + "V27__retain_join_connect_scopes.sql", + "V28__account_audit_delivery_backoff.sql", + "V29__account_identity_uuid_bridge.sql", + "V2__payment_tables.sql", + "V30__approved_legacy_tenant_associations.sql", + "V31__subscription_authority_generation.sql", + "V32__realm_grant_currentness.sql", + "V33__fresh_tenant_identity_associations.sql", + "V34__account_membership_pair_authority.sql", + "V35__canonical_uuid_membership_identity.sql", + "V36__account_auth_authority_generations.sql", + "V37__canonical_first_join_scope_and_intent.sql", + "V38__account_first_join_authority_outbox_and_roles.sql", + "V39__canonical_first_join_terminal_receipt.sql", + "V3__tenant_columns.sql", + "V40.1__retained_tenant_approval_payload_references.sql", + "V40__account_authority_source_baselines.sql", + "V4__roles_2fa.sql", + "V53__account_protected_demo_entitlements.sql", + "V5__payment_tenant_columns.sql", + "V6__password_reset_token.sql", + "V73__account_tenant_authority_source_bridge.sql", + "V74__account_global_role_source.sql", + "V75__draft_commit_authorization_fences.sql", + "V76__account_draft_required_owner_fence.sql", + "V77__account_password_reset_operation_receipts.sql", + "V78__account_logout_all_operation_receipts.sql", + "V79__account_security_state_operations.sql", + "V7__external_account.sql", + "V80__account_security_event_source_guard.sql", + "V81__account_platform_restriction_birth_sources.sql", + "V82__creator_membership_provenance.sql", + "V83__account_tenant_creation_bootstrap.sql", + "V84__individual_creator_party_sources.sql", + "V85__account_hosted_terms_acceptance_workflow.sql", + "V86__account_hosted_terms_environment_binding.sql", + "V87__account_control_ui_owner_source_guards.sql", + "V88__account_logout_all_pending_draft_source_changes.sql", + "V89__account_password_reset_pending_draft_source_changes.sql", + "V8__email_verification.sql", + "V90__account_control_ui_committed_issuance.sql", + "V91__account_selected_publication_authorization.sql", + "V92__account_publication_pre_freeze_order.sql", + "V93__account_selected_publication_settlement.sql", + "V94__selected_publication_inventory_v2.sql", + "V95__game_logic_intake_authorization.sql", + "V96__game_logic_intake_terminal_settlement.sql", + "V97__game_logic_intake_source_read_reservation.sql", + "V98__account_hosted_terms_disclosure_handoffs.sql", + "V99__account_jwt_signer_desired_state.sql", + "V9__payment_provider_id.sql", + "V1000__create_saga_schema.sql", + "V1001__saga_instance_table.sql", + "V1002__saga_step_table.sql"); + + @Test + void actualDefaultLocationsFreshBootstrapAppliesFullCombinedHistoryAndEnabledGuards() { + String schema = "ss_fresh_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway current = + actualParentFlyway(source, "classpath:db/migration", "classpath:db/migration/saga"); + current.migrate(); + current.validate(); + assertCurrentMigrationsInstalled(current); + var dsl = DSL.using(source, SQLDialect.POSTGRES); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ? AND NOT t.tgisinternal AND t.tgenabled <> 'O'", + schema) + .get(0, Long.class)) + .isZero(); + for (String signature : + List.of( + "account_ss_admission_assert_current(account_start_session_admission_protections,boolean)", + "account_ss_activation_assert_current(bytea,bytea,text,boolean)")) { + assertThat( + dsl.fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class)) + .contains("issuanceOperationIdentity,issuanceOperationId"); + } + } + + @Test + void actualReceivingParentIncludingSagaUpgradePreservesHistoryAndAppliesSourceProtections( + @TempDir Path parentMigrations) throws Exception { + var parent = fixture(60_000L, "160.1", false); + parent + .dsl() + .execute( + "ALTER TABLE flyway_schema_history RENAME TO flyway_schema_history_account_service"); + int copied = 0; + for (var resource : + new PathMatchingResourcePatternResolver() + .getResources("classpath*:db/migration/**/*.sql")) { + String filename = java.util.Objects.requireNonNull(resource.getFilename()); + if (!PARENT_MIGRATION_SCRIPTS.contains(filename)) continue; + try (var input = resource.getInputStream()) { + Files.copy(input, parentMigrations.resolve(filename)); + } + copied++; + } + assertThat(copied).isEqualTo(112); + actualParentFlyway(parent, "filesystem:" + parentMigrations).migrate(); + var checksums = + parent + .dsl() + .fetch( + "SELECT version || ':' || script || ':' || checksum || ':' || success FROM flyway_schema_history_account_service WHERE version IS NOT NULL ORDER BY installed_rank") + .getValues(0, String.class); + assertThat(checksums).hasSize(112); + var capture = retainedPhysicalRows(parent, "account_start_session_authority_captures"); + + Flyway current = + actualParentFlyway(parent, "classpath:db/migration", "classpath:db/migration/saga"); + current.migrate(); + current.validate(); + assertCurrentMigrationsInstalled(current); + + assertThat( + parent + .dsl() + .fetch( + "SELECT version || ':' || script || ':' || checksum || ':' || success FROM flyway_schema_history_account_service WHERE version IS NOT NULL AND installed_rank <= 112 ORDER BY installed_rank") + .getValues(0, String.class)) + .isEqualTo(checksums); + assertThat(retainedPhysicalRows(parent, "account_start_session_authority_captures")) + .isEqualTo(capture); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT to_regclass('account_start_session_admission_protections')::TEXT") + .get(0, String.class)) + .isNotNull(); + } + + private static void assertCurrentMigrationsInstalled(Flyway flyway) { + var migrations = flyway.info().all(); + assertThat(migrations) + .isNotEmpty() + .allSatisfy( + migration -> + assertThat(migration.getState()) + .as(migration.getScript()) + .isEqualTo(MigrationState.SUCCESS)); + assertThat(migrations) + .extracting(MigrationInfo::getVersion) + .contains(MigrationVersion.fromVersion("1003"), MigrationVersion.fromVersion("1004")); + } + + private static Flyway actualParentFlyway(Fixture fixture, String... locations) { + return actualParentFlyway(fixture.dataSource(), locations); + } + + private static Flyway actualParentFlyway(DriverManagerDataSource source, String... locations) { + return Flyway.configure() + .dataSource(source) + .schemas(source.getSchema()) + .defaultSchema(source.getSchema()) + .placeholders(Map.of("serviceSchema", source.getSchema())) + .locations(locations) + .table("flyway_schema_history_account_service") + .load(); + } + + @Test + void forwardMigrationAddsSourceProtectionsWithoutChangingRetainedCanonicalParentEvidence() { + Fixture parent = fixture(60_000L, "160.1", false); + // A passive non-authorizing signer baseline is explicitly stipulated, as are the upstream + // capture/World rows in this fixture. This does not establish authenticated producer proof. + parent + .transaction() + .executeWithoutResult( + status -> { + parent.dsl().execute("SET LOCAL session_replication_role = replica"); + parent + .dsl() + .execute( + "INSERT INTO account_jwt_signer_desired_states " + + "(environment_id, cluster_id, kubernetes_namespace, custody_mode) " + + "VALUES ('test', 'test-cluster', 'test', 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK')"); + parent.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + List retainedTables = + List.of( + "account_jwt_signer_desired_states", + "account_draft_authorization_source_locks", + "account_start_session_authority_captures", + "account_start_session_operator_authorizations", + "account_start_session_world_participations", + "account_start_session_world_participation_sources", + "account_start_session_world_original_attempt_evidence", + "account_start_session_world_participation_settlements"); + Map beforeRows = new LinkedHashMap<>(); + Map beforeOids = new LinkedHashMap<>(); + for (String table : retainedTables) { + beforeRows.put(table, retainedPhysicalRows(parent, table)); + beforeOids.put( + table, + parent.dsl().fetchSingle("SELECT ?::regclass::oid::bigint", table).get(0, Long.class)); + } + List retainedFunctions = + List.of( + "account_start_session_world_participation_insert_guard()", + "account_start_session_operator_authorization_guard()", + "account_jwt_signer_promotion_insert_guard()"); + Map beforeDefinitions = new LinkedHashMap<>(); + for (String signature : retainedFunctions) { + beforeDefinitions.put( + signature, + parent + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class)); + beforeOids.put( + signature, + parent + .dsl() + .fetchSingle("SELECT ?::regprocedure::oid::bigint", signature) + .get(0, Long.class)); + } + var checksums = + parent + .dsl() + .fetch( + "SELECT version, checksum FROM flyway_schema_history WHERE success AND version IS NOT NULL ORDER BY installed_rank"); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT to_regclass('account_start_session_admission_protections')::TEXT") + .get(0, String.class)) + .isNull(); + Flyway.configure() + .dataSource(parent.dataSource()) + .schemas(parent.dataSource().getSchema()) + .defaultSchema(parent.dataSource().getSchema()) + .placeholders(Map.of("serviceSchema", parent.dataSource().getSchema())) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("1003")) + .load() + .migrate(); + for (String table : retainedTables) { + assertThat(retainedPhysicalRows(parent, table)).isEqualTo(beforeRows.get(table)); + assertThat( + parent.dsl().fetchSingle("SELECT ?::regclass::oid::bigint", table).get(0, Long.class)) + .isEqualTo(beforeOids.get(table)); + } + for (String signature : retainedFunctions) { + assertThat( + parent + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class)) + .isEqualTo(beforeDefinitions.get(signature)); + assertThat( + parent + .dsl() + .fetchSingle("SELECT ?::regprocedure::oid::bigint", signature) + .get(0, Long.class)) + .isEqualTo(beforeOids.get(signature)); + } + for (var row : checksums) { + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT checksum FROM flyway_schema_history WHERE success AND version = ?", + row.get("version", String.class)) + .get(0, Integer.class)) + .isEqualTo(row.get("checksum", Integer.class)); + } + for (String signature : + List.of( + "account_ss_admission_assert_current(account_start_session_admission_protections,boolean)", + "account_ss_activation_assert_current(bytea,bytea,text,boolean)")) { + String definition = + parent + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class); + assertThat(definition) + .contains("issuanceOperationIdentity,issuanceOperationId") + .doesNotContain("'projectionSchemaId', 'accountStartSessionRedemptionProjection'"); + } + acquire(parent); + assertThat(parent.projection()).containsExactly(parent.tuple()); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT bundle_source_fence, issuance_fence FROM account_start_session_operator_authorizations WHERE control_plane_request_id = ?", + parent.requestId()) + .get("bundle_source_fence", String.class)) + .isEqualTo("13"); + assertThat( + parent + .dsl() + .fetchSingle( + "SELECT issuance_fence FROM account_start_session_operator_authorizations WHERE control_plane_request_id = ?", + parent.requestId()) + .get(0, Long.class)) + .isEqualTo(9L); + + Fixture scalar = fixture(60_000L, null, true); + assertThatThrownBy(() -> acquire(scalar)) + .hasMessageContaining( + "Admission projection differs from complete original Account redemption"); + } + + private static String retainedPhysicalRows(Fixture fixture, String table) { + return fixture + .dsl() + .fetchSingle( + "SELECT coalesce(jsonb_agg(value ORDER BY value::TEXT), '[]'::JSONB)::TEXT " + + "FROM (SELECT to_jsonb(original) || jsonb_build_object(" + + "'_xmin', original.xmin::TEXT, '_ctid', original.ctid::TEXT) AS value FROM " + + table + + " original) retained") + .get(0, String.class); + } + + @Test + void fullTupleDoesNotBypassIndependentOwnerIssuanceOperationBinding() { + Fixture fixture = fixture(); + // Stipulate a contradictory retained owner row to isolate this SQL integrity conjunct. + // The parent immutable writer remains enabled outside this deliberate corruption fixture. + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_operator_authorizations SET issuance_operation_id = ? " + + "WHERE control_plane_request_id = ?", + UUID.randomUUID(), + fixture.requestId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + assertThat(fixture.projection()).containsExactly(fixture.tuple()); + assertThatThrownBy(() -> acquire(fixture)) + .hasMessageContaining( + "Admission projection differs from complete original Account redemption"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + + @Test + void installsAdditiveHooksWithoutRemovingExistingOwnerChecks() { + Fixture fixture = fixture(); + for (String function : + List.of( + "account_control_ui_hold_required_sources(text[])", + "account_draft_authorization_source_change_guard()", + "account_hosted_terms_disclosure_handoff_guard()")) { + String definition = + fixture + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", function) + .get(0, String.class); + assertThat(definition) + .contains( + "account_ss_admission_assert_no_pending", + "account_start_session_world_participations") + // The actual published parent has the canonical World guard. Selected-owner source + // reservations remain a separate V130 receiving obligation, outside passive V165. + .doesNotContain("account_selected_owner_intake_source_read"); + } + String hold = + fixture + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef('account_control_ui_hold_required_sources(text[])'::regprocedure)") + .get(0, String.class); + assertThat(hold) + .contains( + "account_draft_authorization_sources", + "account_selected_publication_sources", + "account_game_logic_intake_sources", + "account_game_logic_intake_source_read_sources"); + for (String guard : + List.of( + "account_ss_admission_assert_current(account_start_session_admission_protections,boolean)", + "account_ss_admission_settlement_insert_guard()")) { + assertThat( + fixture + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", guard) + .get(0, String.class)) + .contains("account_ss_admission_canonical_hold_next_pointer(original)"); + } + } + + @Test + void exactCurrentReadPreservesIdentityWithoutAllocatingAndWorldCommitCannotReleaseIt() { + Fixture fixture = fixture(); + assertThat(fixture.expiry().getNano() % 1_000_000).isNotZero(); + acquire(fixture); + Long sequence = sequenceValue(fixture); + for (int retry = 0; retry < 2; retry++) { + var current = + fixture + .transaction() + .execute( + status -> + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request())); + assertThat(current.get("protection_id", UUID.class)).isEqualTo(fixture.protectionId()); + assertThat(current.get("request_binding_bytes", byte[].class)) + .containsExactly(fixture.request()); + OffsetDateTime retainedExpiry = + current.get("original_lease_expires_at", OffsetDateTime.class); + assertThat(retainedExpiry).isNotNull(); + assertThat(retainedExpiry.toInstant()).isEqualTo(fixture.expiry().toInstant()); + } + assertThat(sequenceValue(fixture)).isEqualTo(sequence); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT account_start_session_world_participation_is_settled(?)", + fixture.worldId()) + .get(0, Boolean.class)) + .isTrue(); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + fixture.source().key()))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + } + + @Test + void changedSubmillisecondOriginalExpiryCannotRecoverRetainedProtection() { + Fixture fixture = fixture(); + acquire(fixture); + var storedRowBefore = + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_start_session_admission_protections WHERE protection_id = ?", + fixture.protectionId()); + DateTimeFormatter expiryFormat = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC); + String originalExpiryText = expiryFormat.format(fixture.expiry().toInstant()); + String changedExpiryText = expiryFormat.format(fixture.expiry().plusNanos(1_000).toInstant()); + byte[] changedRequest = + new String(fixture.request(), StandardCharsets.UTF_8) + .replace(originalExpiryText, changedExpiryText) + .getBytes(StandardCharsets.UTF_8); + assertThat(changedRequest).isNotEqualTo(fixture.request()); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + changedRequest))) + .hasMessageContaining("Original admission recovery binding differs"); + var storedRowAfter = + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_start_session_admission_protections WHERE protection_id = ?", + fixture.protectionId()); + assertThat(storedRowAfter).isEqualTo(storedRowBefore); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void forgedWorldHoldDigestWithoutCanonicalPrefixCannotBecomeProtection() { + Fixture fixture = fixture(); + String holdText = new String(fixture.hold(), StandardCharsets.UTF_8); + String digestMarker = "\"holdBindingDigest\":\""; + int digestStart = holdText.indexOf(digestMarker) + digestMarker.length(); + int digestEnd = holdText.indexOf('"', digestStart); + String validDigest = holdText.substring(digestStart, digestEnd); + assertThat(validDigest).startsWith("sha256:"); + String forgedHoldText = + holdText.substring(0, digestStart) + + validDigest.substring("sha256:".length()) + + holdText.substring(digestEnd); + byte[] forgedHold = forgedHoldText.getBytes(StandardCharsets.UTF_8); + byte[] forgedRequest = + new String(fixture.request(), StandardCharsets.UTF_8) + .replace(base64(fixture.hold()), base64(forgedHold)) + .getBytes(StandardCharsets.UTF_8); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> insertProtection(fixture, 11L, forgedHold, forgedRequest))) + .hasMessageContaining( + "Original StartSession admission hold request differs from retained protection"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + + @Test + void pendingAdmissionExcludesRealSourceChangeCompletionAndDisclosureDispatch() { + Fixture fixture = fixture(); + acquire(fixture); + UUID changeId = UUID.randomUUID(); + fixture + .transaction() + .executeWithoutResult( + status -> { + insert( + fixture.dsl(), + "account_draft_authorization_source_changes", + "change_id", + changeId, + "binding", + bytes("change"), + "status", + "WAITING"); + insert( + fixture.dsl(), + "account_draft_authorization_changed_scopes", + "change_id", + changeId, + "source_key", + fixture.source().key()); + }); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes SET status = 'SOURCE_COMMITTED', committed_at = clock_timestamp() WHERE change_id = ?", + changeId))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + UUID handoffId = UUID.randomUUID(); + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_hosted_terms_disclosure_handoffs", + "handoff_id", + handoffId, + "request_id", + UUID.randomUUID(), + "kind", + "CATALOG", + "source_key", + fixture.source().key(), + "predecessor_digest", + "sha256:" + "a".repeat(64), + "candidate_digest", + "sha256:" + "b".repeat(64), + "effective_at", + OffsetDateTime.now().plusDays(1), + "binding", + bytes("disclosure"), + "binding_digest", + "sha256:" + hash(bytes("disclosure")), + "status", + "PREPARED")); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 WHERE handoff_id = ?", + handoffId))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + } + + @Test + void rawChangedCaptureAndIncompleteChildrenCannotBecomeProtection() { + Fixture changed = fixture(); + assertThatThrownBy( + () -> + changed + .transaction() + .executeWithoutResult(status -> insertProtection(changed, 99L))) + .hasMessageContaining("retained owner bindings"); + Fixture incomplete = fixture(); + assertThatThrownBy( + () -> + incomplete + .transaction() + .executeWithoutResult(status -> insertProtection(incomplete, 11L))) + .satisfies( + failure -> + assertDatabaseGuardFailure( + failure, + "Admission protection has incomplete or extra source children", + "23514")); + assertThat( + incomplete + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + + @Test + void immutableRowsAndUnprovedTerminalCannotReleaseProtection() { + Fixture fixture = fixture(); + acquire(fixture); + for (String table : + List.of( + "account_start_session_admission_protections", + "account_start_session_admission_protection_sources")) { + assertThatThrownBy(() -> fixture.dsl().execute("DELETE FROM " + table)) + .hasMessageContaining("append-only"); + assertThatThrownBy(() -> fixture.dsl().execute("TRUNCATE " + table + " CASCADE")) + .hasMessageContaining("append-only"); + } + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_admission_protection_sources SET source_evidence = ?", + bytes("changed"))) + .hasMessageContaining("append-only"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO account_start_session_admission_protection_settlements (protection_id, outcome, terminal_bytes, terminal_digest) VALUES (?, 'ABORTED', ?, ?)", + fixture.protectionId(), + malformedSettlementBytes(), + "sha256:" + hash(malformedSettlementBytes()))) + .hasMessageContaining("not the closed envelope"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void genuineFramedTerminalReceiptsReleaseRequiredSource() { + for (GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome : + List.of( + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)) { + Fixture fixture = fixture(); + acquire(fixture); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + fixture.source().key())) + .hasMessageContaining("Original StartSession admission protection remains pending"); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(fixture.hold()), + outcome, + outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED + ? 1L + : null, + outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED + ? 1L + : null, + "sha256:" + "a".repeat(64), + outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + Instant.now()); + byte[] ownerProof = GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof); + long fence = + fixture + .dsl() + .fetchSingle( + "SELECT protection_fence FROM account_start_session_admission_protections WHERE protection_id = ?", + fixture.protectionId()) + .get(0, Long.class); + byte[] evidence = + json( + Map.of( + "schema", "account-start-session-admission-protection-evidence/v1", + "accountProtectionId", fixture.protectionId().toString(), + "accountProtectionFence", Long.toString(fence), + "originalSourceCaptureReferenceBytesBase64", base64(bytes("{}")), + "originalSourceCaptureReferenceSha256", hash(bytes("{}")), + "requestBytesBase64", base64(fixture.request()), + "sourceEvidenceVector", List.of(base64(fixture.source().canonicalBytes())))); + byte[] terminal = + json( + Map.of( + "schema", "account-start-session-admission-protection-settlement/v1", + "canonicalAccountProtectionEvidenceBytesBase64", base64(evidence), + "canonicalGameSessionOwnerProofBytesBase64", base64(ownerProof))); + insert( + fixture.dsl(), + "account_start_session_admission_protection_settlements", + "protection_id", + fixture.protectionId(), + "outcome", + outcome.name(), + "terminal_bytes", + terminal, + "terminal_digest", + "sha256:" + hash(terminal)); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isTrue(); + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + fixture.source().key()); + } + } + + @Test + void expiredOriginalCannotRecoverEvenWhenRetainedIdentityAndSourcesRemain() { + Fixture fixture = fixture(); + acquire(fixture); + // Stipulate passage of the immutable original expiry without changing protection: + // rewriting the fixture row requires disabling the immutable upstream/new triggers. + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_admission_protections SET original_lease_expires_at = date_trunc('milliseconds', clock_timestamp() - INTERVAL '1 second') WHERE protection_id = ?", + fixture.protectionId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request()))) + .hasMessageContaining("not current"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void currentRecoveryRechecksDatabaseExpiryAfterTheCallerWaitsForOriginalCaptureLock() + throws Exception { + Fixture fixture = fixture(3_000L); + acquire(fixture); + var executor = Executors.newSingleThreadExecutor(); + CountDownLatch entered = new CountDownLatch(1); + try (Connection lock = fixture.dataSource().getConnection()) { + lock.setAutoCommit(false); + DSL.using(lock, SQLDialect.POSTGRES) + .fetch( + "SELECT control_plane_request_id FROM account_start_session_authority_captures WHERE control_plane_request_id = ? FOR UPDATE", + fixture.requestId()); + var waiting = + executor.submit( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> { + entered.countDown(); + // The currentness producer's original-capture lock can wait before the + // V165 + // boundary. V165 itself uses NOWAIT to avoid reversing source lock + // order. + fixture + .dsl() + .fetch( + "SELECT control_plane_request_id FROM account_start_session_authority_captures WHERE control_plane_request_id = ? FOR UPDATE", + fixture.requestId()); + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request()); + })); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + long expiryDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (fixture + .dsl() + .fetchSingle("SELECT clock_timestamp() >= ?::timestamptz", fixture.expiry()) + .get(0, Boolean.class) + .equals(false) + && System.nanoTime() < expiryDeadline) { + Thread.sleep(20L); + } + assertThat( + fixture + .dsl() + .fetchSingle("SELECT clock_timestamp() >= ?::timestamptz", fixture.expiry()) + .get(0, Boolean.class)) + .isTrue(); + assertThat(waiting.isDone()).isFalse(); + lock.commit(); + assertThatThrownBy(() -> waiting.get(5, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasStackTraceContaining("not current"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void acquisitionRejectsUnsettleableHoldRequestAndSourceSnapshotBounds() throws Exception { + Fixture fixture = fixture(); + byte[] oversizedHold = + bytes(new String(fixture.hold(), StandardCharsets.UTF_8) + " ".repeat(65537)); + Map oversizedHoldRequest = + tools.jackson.databind.json.JsonMapper.builder() + .build() + .readValue(fixture.request(), new tools.jackson.core.type.TypeReference<>() {}); + oversizedHoldRequest.put("worldAdmissionHoldIdentityBytesBase64", base64(oversizedHold)); + assertDatabaseGuardFailure( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + insertProtection(fixture, 11L, oversizedHold, json(oversizedHoldRequest))), + "23514"); + assertDatabaseGuardFailure( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + insertProtection( + fixture, + 11L, + fixture.hold(), + bytes( + new String(fixture.request(), StandardCharsets.UTF_8) + + " ".repeat(786433)))), + "23514"); + + for (List vector : + List.of( + List.of(), + java.util.Collections.nCopies(257, base64(fixture.source().canonicalBytes())), + List.of(base64(new byte[131073])), + List.of(base64(fixture.source().canonicalBytes()) + "\n"))) { + replaceSnapshot( + fixture, + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + fixture.requestId(), + "sourceVector", + vector))); + assertDatabaseGuardFailure(() -> acquire(fixture), "23514"); + } + assertDatabaseGuardFailure( + () -> + replaceSnapshot( + fixture, + bytes( + new String( + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + fixture.requestId(), + "sourceVector", + List.of(base64(fixture.source().canonicalBytes())))), + StandardCharsets.UTF_8) + + " ".repeat(245761))), + "23514"); + } + + @Test + void acquisitionRejectsEveryHoldShapeThatSettlementCannotAccept() throws Exception { + Fixture fixture = fixture(); + var mapper = tools.jackson.databind.json.JsonMapper.builder().build(); + Map originalHold = + mapper.readValue(fixture.hold(), new tools.jackson.core.type.TypeReference<>() {}); + byte[] originalHoldRequest = + Base64.getDecoder().decode((String) originalHold.get("requestBytesBase64")); + Map requestEnvelope = + mapper.readValue(originalHoldRequest, new tools.jackson.core.type.TypeReference<>() {}); + @SuppressWarnings("unchecked") + Map requestFields = (Map) requestEnvelope.get("request"); + + Map uppercaseId = new LinkedHashMap<>(originalHold); + uppercaseId.put( + "holdId", ((String) uppercaseId.get("holdId")).toUpperCase(java.util.Locale.ROOT)); + assertMalformedHoldRejected(fixture, json(uppercaseId)); + + Map extraEnvelope = new LinkedHashMap<>(requestEnvelope); + extraEnvelope.put("extra", "unsettleable"); + assertMalformedHoldRejected(fixture, holdWithRequest(originalHold, json(extraEnvelope))); + + Map extraFields = new LinkedHashMap<>(requestFields); + extraFields.put("extra", "unsettleable"); + assertMalformedHoldRejected(fixture, holdWithRequest(originalHold, holdRequest(extraFields))); + + Map wrongType = new LinkedHashMap<>(requestFields); + wrongType.put("activeLifecycleEpoch", 1); + assertMalformedHoldRejected(fixture, holdWithRequest(originalHold, holdRequest(wrongType))); + + assertMalformedHoldRejected( + fixture, + holdWithRequest( + originalHold, bytes(new String(originalHoldRequest, StandardCharsets.UTF_8) + " "))); + assertMalformedHoldRejected( + fixture, bytes(new String(fixture.hold(), StandardCharsets.UTF_8) + " ")); + + Map wrongOrigin = new LinkedHashMap<>(requestFields); + wrongOrigin.put("initialAdmissionOrigin", "EXPECT_CLOSED"); + assertMalformedHoldRejected(fixture, holdWithRequest(originalHold, holdRequest(wrongOrigin))); + + Map wrongPointer = new LinkedHashMap<>(requestFields); + wrongPointer.put("expectedPriorPointerVersion", "1"); + assertMalformedHoldRejected(fixture, holdWithRequest(originalHold, holdRequest(wrongPointer))); + + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + + private static byte[] holdRequest(Map fields) { + return json( + Map.of("schema", "world-canonical-initial-admission-hold-request/v1", "request", fields)); + } + + private static byte[] holdWithRequest(Map originalHold, byte[] requestBytes) { + Map hold = new LinkedHashMap<>(originalHold); + hold.put("requestBytesBase64", base64(requestBytes)); + hold.put("holdBindingDigest", "sha256:" + hash(requestBytes)); + return json(hold); + } + + private static void assertMalformedHoldRejected(Fixture fixture, byte[] hold) throws Exception { + Map request = + tools.jackson.databind.json.JsonMapper.builder() + .build() + .readValue(fixture.request(), new tools.jackson.core.type.TypeReference<>() {}); + request.put("worldAdmissionHoldIdentityBytesBase64", base64(hold)); + assertDatabaseGuardFailure( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> insertProtection(fixture, 11L, hold, json(request))), + "23514"); + } + + @Test + void acquisitionAccepts256CompleteSourcesAndRejects257CompleteSources() { + for (int sourceCount : List.of(256, 257)) { + Fixture fixture = fixture(); + var sources = new java.util.ArrayList(); + sources.add(fixture.source()); + for (int index = 1; index < sourceCount; index++) { + sources.add( + new SourceEvidence( + SourceKind.HOSTED_TERMS, + "bounded-source-" + index, + "1", + "1", + null, + null, + bytes("captured source"))); + } + sources.sort(java.util.Comparator.comparing(SourceEvidence::key)); + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + for (SourceEvidence source : sources) { + if (source.key().equals(fixture.source().key())) continue; + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + source.key()); + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + fixture.worldId(), + "source_key", + source.key(), + "source_evidence", + source.canonicalBytes()); + } + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + replaceSnapshot( + fixture, + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + fixture.requestId(), + "sourceVector", + sources.stream().map(source -> base64(source.canonicalBytes())).toList()))); + if (sourceCount == 256) { + acquire(fixture); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM account_start_session_admission_protection_sources WHERE protection_id = ?", + fixture.protectionId()) + .get(0, Long.class)) + .isEqualTo(256L); + } else { + assertDatabaseGuardFailure(() -> acquire(fixture), "23514"); + } + } + } + + @Test + void acquisitionRequiresCanonicalUtf16OrderForMultipleUnicodeSources() { + Fixture fixture = fixture(); + var supplementary = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + "terms-\uD800\uDC00", + "1", + "1", + null, + null, + bytes("supplementary")); + var bmp = + new SourceEvidence( + SourceKind.HOSTED_TERMS, "terms-\uE000", "1", "1", null, null, bytes("BMP")); + var sources = + java.util.stream.Stream.of(fixture.source(), supplementary, bmp) + .sorted(java.util.Comparator.comparing(SourceEvidence::key)) + .toList(); + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + for (SourceEvidence source : List.of(supplementary, bmp)) { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + source.key()); + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + fixture.worldId(), + "source_key", + source.key(), + "source_evidence", + source.canonicalBytes()); + } + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + var reversed = new java.util.ArrayList<>(sources); + java.util.Collections.reverse(reversed); + replaceSnapshot( + fixture, + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + fixture.requestId(), + "sourceVector", + reversed.stream().map(source -> base64(source.canonicalBytes())).toList()))); + assertDatabaseGuardFailure(() -> acquire(fixture), "23514"); + replaceSnapshot( + fixture, + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + fixture.requestId(), + "sourceVector", + sources.stream().map(source -> base64(source.canonicalBytes())).toList()))); + acquire(fixture); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM account_start_session_admission_protection_sources WHERE protection_id = ?", + fixture.protectionId()) + .get(0, Long.class)) + .isEqualTo(3L); + } + + private static void assertDatabaseGuardFailure(Runnable operation, String expectedSqlState) { + assertThatThrownBy(operation::run) + .isInstanceOf(RuntimeException.class) + .satisfies(failure -> assertDatabaseGuardFailure(failure, "", expectedSqlState)); + } + + private static void replaceSnapshot(Fixture fixture, byte[] snapshot) { + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_authority_captures SET canonical_snapshot_bytes = ?, snapshot_sha256 = ? WHERE control_plane_request_id = ?", + snapshot, + hash(snapshot), + fixture.requestId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + } + + private static void acquire(Fixture fixture) { + fixture + .transaction() + .executeWithoutResult( + status -> { + insertProtection(fixture, 11L); + fixture + .dsl() + .execute( + "INSERT INTO account_start_session_admission_protection_sources(protection_id, source_key, source_evidence) SELECT ?, source_key, source_evidence FROM account_start_session_world_participation_sources WHERE participation_id = ?", + fixture.protectionId(), + fixture.worldId()); + }); + } + + private static void insertProtection(Fixture fixture, long version) { + insertProtection(fixture, version, fixture.hold(), fixture.request()); + } + + private static void insertProtection( + Fixture fixture, long version, byte[] holdIdentity, byte[] request) { + insert( + fixture.dsl(), + "account_start_session_admission_protections", + "protection_id", + fixture.protectionId(), + "control_plane_request_id", + fixture.requestId(), + "original_post_authorization_tuple", + fixture.tuple(), + "account_redemption_projection", + fixture.projection(), + "game_session_owner_mutation_id", + fixture.mutationId(), + "game_session_owner_attempt_id", + fixture.attemptId(), + "game_session_owner_fence", + 47L, + "original_lease_expires_at", + fixture.expiry(), + "account_world_participation_id", + fixture.worldId(), + "account_world_participation_fence", + 1L, + "target_namespace", + "test", + "canonical_tenant_id", + fixture.tenantId(), + "canonical_game_instance_id", + fixture.instanceId(), + "capture_source_version", + version, + "capture_source_fence", + 13L, + "capture_sha256", + hash(bytes("{}")), + "world_admission_hold_identity_bytes", + holdIdentity, + "request_binding_bytes", + request, + "request_binding_digest", + "sha256:" + hash(request)); + } + + private static Fixture fixture() { + return fixture(60_000L); + } + + private static Fixture fixture(long leaseMillis) { + return fixture(leaseMillis, null, false); + } + + private static Fixture fixture(long leaseMillis, String target, boolean scalarProjection) { + String schema = "ss_admission_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + var migration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) migration.target(MigrationVersion.fromVersion(target)); + migration.load().migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + OffsetDateTime now = + dsl.fetchSingle( + "SELECT date_trunc('milliseconds', clock_timestamp()) + INTERVAL '123 microseconds'") + .get(0, OffsetDateTime.class); + OffsetDateTime capturedAt = now.truncatedTo(ChronoUnit.MILLIS); + UUID tenant = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + UUID actor = UUID.randomUUID(); + UUID mutation = UUID.randomUUID(); + UUID attempt = UUID.randomUUID(); + UUID world = UUID.randomUUID(); + UUID issuance = UUID.randomUUID(); + String requestId = "original/" + UUID.randomUUID(); + SourceEvidence evidence = + new SourceEvidence( + SourceKind.HOSTED_TERMS, "test-terms", "1", "1", null, null, bytes("terms")); + Map authorityBundle = + Map.of("issuanceOperationIdentity", Map.of("issuanceOperationId", issuance.toString())); + byte[] tuple = + json( + Map.of( + "preAuthorizationReservationTuple", + Map.of(), + "authorizationReferenceFingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "issuanceFence", + "9", + "authorityEvidenceBundle", + authorityBundle)); + // Upstream authority is explicitly stipulated; current SQL still requires exact tuple bytes. + byte[] projection = + scalarProjection + ? json( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "authorityEvidenceBundle", + authorityBundle, + "issuanceOperationId", + issuance.toString(), + "issuanceFence", + 9L)) + : tuple.clone(); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + "test", + tenant, + "test-world", + UUID.randomUUID(), + UUID.randomUUID(), + "SHARED", + instance, + UUID.randomUUID(), + 1L, + "separate-initial-admission-identity", + "b".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + byte[] hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, UUID.randomUUID(), UUID.randomUUID()) + .canonicalBytes(); + OffsetDateTime expiry = now.plusNanos(leaseMillis * 1_000_000L); + byte[] request = + json( + Map.of( + "schema", + "account-start-session-admission-protection-request/v1", + "originalPostAuthorizationTupleBytesBase64", + base64(tuple), + "accountRedemptionProjectionBytesBase64", + base64(projection), + "gameSessionOwnerMutationId", + mutation.toString(), + "gameSessionOwnerAttemptId", + attempt.toString(), + "gameSessionOwnerFence", + "47", + "originalLeaseExpiresAt", + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") + .withZone(ZoneOffset.UTC) + .format(expiry.toInstant()), + "accountWorldParticipationId", + world.toString(), + "accountWorldParticipationFence", + "1", + "worldAdmissionHoldIdentityBytesBase64", + base64(hold))); + Fixture fixture = + new Fixture( + dsl, + transaction, + source, + UUID.randomUUID(), + requestId, + tenant, + instance, + mutation, + attempt, + world, + expiry, + evidence, + tuple, + projection, + hold, + request); + byte[] snapshot = + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + requestId, + "sourceVector", + List.of(base64(evidence.canonicalBytes())))); + transaction.executeWithoutResult( + status -> { + dsl.execute("SET LOCAL session_replication_role = replica"); + insert( + dsl, + "account_canonical_tenant_identity_claims", + "canonical_tenant_id", + tenant, + "identity_kind", + "APPROVED_RETAINED", + "source_operation_id", + UUID.randomUUID(), + "source_account_legacy_tenant_id", + 1L, + "source_target_namespace", + "test", + "source_game_row_id", + 1L, + "source_game_tenant_key", + tenant.toString()); + insert(dsl, "account_draft_authorization_source_locks", "source_key", evidence.key()); + insert( + dsl, + "account_start_session_authority_captures", + "control_plane_request_id", + requestId, + "account_uuid", + actor, + "tenant_uuid", + tenant, + "target_owner", + "game-session-service", + "logging_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "pre_authorization_tuple", + bytes("{}"), + "mutation_digest", + "c".repeat(64), + "control_ui_operation_id", + UUID.randomUUID(), + "control_ui_token_jti", + UUID.randomUUID(), + "control_ui_token_hash", + "d".repeat(64), + "control_ui_signer_receipt_sha256", + "e".repeat(64), + "issuance_fence", + 9L, + "issuance_fence_source_version", + 1L, + "captured_at", + capturedAt, + "snapshot_sha256", + hash(snapshot), + "canonical_snapshot_bytes", + snapshot, + "source_version", + 11L, + "source_fence", + 13L, + "linearization", + "17", + "canonical_sha256", + hash(bytes("{}")), + "canonical_capture_bytes", + bytes("{}")); + insert( + dsl, + "account_start_session_operator_authorizations", + "control_plane_request_id", + requestId, + "pre_authorization_tuple", + bytes("{}"), + "mutation_digest", + "c".repeat(64), + "issuance_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "issuance_operation_id", + issuance, + "issuance_fence", + 9L, + "bundle_version", + "authorityEvidenceBundle/v1", + "bundle_source_version", + "11", + "bundle_source_fence", + "13", + "bundle_linearization", + "17", + "authority_evidence_bundle", + json(authorityBundle), + "authorization_reference_fingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "encrypted_response_envelope", + bytes("synthetic"), + "issued_at", + now.minusSeconds(10), + "reference_expires_at", + now.plusSeconds(90), + "response_envelope_expires_at", + now.plusSeconds(120), + "status", + "REDEEMED", + "redemption_redeemer_workload_uri", + "spiffe://firemud/ns/test/sa/game-session-service", + "redemption_owner_attempt_id", + attempt, + "redemption_owner_fence", + 47L, + "redeemed_at", + now.minusSeconds(5), + "redemption_reference_fingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "redemption_authority_evidence_bundle", + json(authorityBundle)); + insert( + dsl, + "account_start_session_world_participations", + "participation_id", + world, + "control_plane_request_id", + requestId, + "original_post_authorization_tuple", + tuple, + "target_namespace", + "test", + "canonical_tenant_id", + tenant, + "canonical_game_instance_id", + instance, + "game_session_owner_attempt_id", + attempt, + "game_session_owner_fence", + 47L, + "preparation_input_json", + "{}", + "preparation_input_digest", + "sha256:" + hash(bytes("{}"))); + insert( + dsl, + "account_start_session_world_participation_sources", + "participation_id", + world, + "source_key", + evidence.key(), + "source_evidence", + evidence.canonicalBytes()); + insert( + dsl, + "account_start_session_world_original_attempt_evidence", + "participation_id", + world, + "target_namespace", + "test", + "game_session_owner_mutation_id", + mutation, + "game_session_owner_attempt_id", + attempt, + "game_session_owner_fence", + 47L, + "original_lease_expires_at", + expiry, + "original_response_bytes", + bytes("synthetic-observation"), + "original_response_digest", + "sha256:" + hash(bytes("synthetic-observation"))); + insert( + dsl, + "account_start_session_world_participation_settlements", + "participation_id", + world, + "outcome", + "COMMITTED", + "world_execution_fence", + 1L, + "terminal_bytes", + bytes("synthetic-terminal"), + "terminal_digest", + "sha256:" + hash(bytes("synthetic-terminal"))); + dsl.execute("SET LOCAL session_replication_role = origin"); + }); + return fixture; + } + + private static void insert(DSLContext dsl, String table, Object... fields) { + Map, Object> values = new LinkedHashMap<>(); + for (int index = 0; index < fields.length; index += 2) + values.put(DSL.field(DSL.name((String) fields[index])), fields[index + 1]); + try { + dsl.insertInto(DSL.table(DSL.name(table))).set(values).execute(); + } catch (RuntimeException failure) { + String sqlState = "unavailable"; + String constraint = "unavailable"; + StringBuilder causeTypes = new StringBuilder(); + var visited = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + Throwable cause = failure; + int causeCount = 0; + while (cause != null && causeCount < 32 && visited.add(cause)) { + if (causeTypes.length() > 0) causeTypes.append("->"); + causeTypes.append(diagnosticIdentifier(cause.getClass().getSimpleName())); + causeCount++; + if (cause instanceof SQLException sqlFailure && sqlFailure.getSQLState() != null) { + sqlState = sqlFailure.getSQLState(); + } + if (cause instanceof PSQLException postgresFailure) { + var serverError = postgresFailure.getServerErrorMessage(); + if (serverError != null && serverError.getConstraint() != null) { + constraint = serverError.getConstraint(); + } + } + cause = cause.getCause(); + } + if (cause != null) causeTypes.append("->truncated"); + System.err.printf( + "StartSession admission fixture insert failed: " + + "table=%s SQLSTATE=%s constraint=%s causeTypes=%s%n", + diagnosticIdentifier(table), + diagnosticIdentifier(sqlState), + diagnosticIdentifier(constraint), + causeTypes); + throw failure; + } + } + + private static String diagnosticIdentifier(String value) { + return value != null && value.matches("[A-Za-z0-9_]+") ? value : "unavailable"; + } + + private static Long sequenceValue(Fixture fixture) { + var sequence = + fixture + .dsl() + .fetchSingle( + "SELECT namespace.nspname AS schema_name, relation.relname AS sequence_name " + + "FROM pg_class relation " + + "JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace " + + "WHERE relation.oid = pg_get_serial_sequence(" + + "format('%I.%I', current_schema(), ?), ?)::regclass", + "account_start_session_admission_protections", "protection_fence"); + return fixture + .dsl() + .select(DSL.field(DSL.name("last_value"), Long.class)) + .from( + DSL.table( + DSL.name( + sequence.get("schema_name", String.class), + sequence.get("sequence_name", String.class)))) + .fetchSingle(0, Long.class); + } + + private static void assertDatabaseGuardFailure( + Throwable failure, String expectedMessage, String expectedSqlState) { + var visited = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + Throwable cause = failure; + PSQLException databaseFailure = null; + while (cause != null && visited.add(cause)) { + if (cause instanceof PSQLException postgresFailure) { + databaseFailure = postgresFailure; + break; + } + cause = cause.getCause(); + } + assertThat((Throwable) databaseFailure) + .as("the rejected fixture write must fail at PostgreSQL's database guard") + .isNotNull(); + assertThat(databaseFailure.getSQLState()).isEqualTo(expectedSqlState); + assertThat(databaseFailure.getServerErrorMessage()).isNotNull(); + assertThat(databaseFailure.getServerErrorMessage().getMessage()).contains(expectedMessage); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static byte[] malformedSettlementBytes() { + return bytes( + "{\"canonicalAccountProtectionEvidenceBytesBase64\":\"\"," + + "\"canonicalGameSessionOwnerProofBytesBase64\":\"\"," + + "\"schema\":\"account-start-session-admission-protection-settlement/v2\"}"); + } + + private static byte[] json(Map value) { + return AccountControlUiAuthority.canonical(value); + } + + private static String base64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static String hash(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transaction, + DriverManagerDataSource dataSource, + UUID protectionId, + String requestId, + UUID tenantId, + UUID instanceId, + UUID mutationId, + UUID attemptId, + UUID worldId, + OffsetDateTime expiry, + SourceEvidence source, + byte[] tuple, + byte[] projection, + byte[] hold, + byte[] request) {} +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java new file mode 100644 index 0000000000..564ea95722 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.entitymanagement.entity; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.springframework.util.StringUtils; + +/** Canonical Entity-owned actor identity and the provenance disposition that gates its use. */ +public record ActorIdentity( + UUID characterUuid, + UUID accountUuid, + UUID tenantUuid, + UUID playableStateNamespaceId, + PlayableStateScope playableStateScope, + ActorIdentityStatus status, + String quarantineReason) { + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String UUID_PATTERN = + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"; + + public ActorIdentity { + requireNonNil(characterUuid, "characterUuid"); + requireNonNilWhenPresent(accountUuid, "accountUuid"); + requireNonNilWhenPresent(tenantUuid, "tenantUuid"); + requireNonNilWhenPresent(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(status, "status"); + if (playableStateScope != null) { + requireScope(playableStateScope); + } + if (status == ActorIdentityStatus.OWNER_RESOLVED) { + requireNonNil(accountUuid, "accountUuid"); + requireNonNil(tenantUuid, "tenantUuid"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireScope(playableStateScope); + if (StringUtils.hasText(quarantineReason)) { + throw new IllegalArgumentException( + "owner-resolved identity cannot have a quarantine reason"); + } + } else if (!StringUtils.hasText(quarantineReason)) { + throw new IllegalArgumentException("quarantined identity requires a reason"); + } + } + + public static UUID parseRequiredUuid(String value, String fieldName) { + if (!StringUtils.hasText(value) || !value.matches(UUID_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID"); + } + UUID parsed = UUID.fromString(value); + requireNonNil(parsed, fieldName); + return parsed; + } + + private static void requireNonNil(UUID value, String fieldName) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a non-nil UUID"); + } + } + + private static void requireNonNilWhenPresent(UUID value, String fieldName) { + if (value != null && NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must not be the nil UUID"); + } + } + + public static PlayableStateScope requireScope(PlayableStateScope scope) { + if (scope == null + || (scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + && scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) { + throw new IllegalArgumentException("playableStateScope must be owner-resolved"); + } + return scope; + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java new file mode 100644 index 0000000000..67bcce21ee --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.entitymanagement.entity; + +public enum ActorIdentityStatus { + OWNER_RESOLVED, + QUARANTINED +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java index 935b98a45c..9056764770 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java @@ -11,6 +11,7 @@ @EqualsAndHashCode(onlyExplicitlyIncluded = true) public class Character { @EqualsAndHashCode.Include private Long id; + private ActorIdentity actorIdentity; private Long tenantId; private Long accountId; private String playableStateKey; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java index 80f448eb72..4187236beb 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java @@ -14,6 +14,7 @@ public interface CharacterMapper { @Mapping(target = "lastLoginAt", ignore = true) @Mapping(target = "playableStateKey", ignore = true) @Mapping(target = "bodyLayoutKey", constant = "DEFAULT") + @Mapping(target = "actorIdentity", ignore = true) @Mapping(target = "version", ignore = true) Character toEntity(CharacterDto dto); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java index bc84020bf9..c9089faae2 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @Repository @@ -32,6 +33,8 @@ public List findActiveForCharacter( .eq(tenantId) .and(ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(characterId)) + .and( + CharacterRepository.legacyCharacterExists(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID)) .and( ACTOR_ACTIVE_CONDITIONS .EXPIRES_AT @@ -60,7 +63,10 @@ public List findActiveForCharacter( .and(ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY.eq(playableStateKey)) .and(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID.eq(characterId)) .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE.eq(sourceType)) - .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID.eq(sourceId))) + .and(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID.eq(sourceId)) + .and( + CharacterRepository.legacyCharacterExists( + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) .orderBy(ACTOR_ACTIVE_CONDITIONS.ID.asc()) .limit(1) .fetchOne(this::toEntity)); @@ -69,36 +75,80 @@ public List findActiveForCharacter( public ActorActiveCondition save(ActorActiveCondition entity) { if (entity.getId() == null) { Long id = - dsl.insertInto(ACTOR_ACTIVE_CONDITIONS) - .set(ACTOR_ACTIVE_CONDITIONS.TENANT_ID, entity.getTenantId()) - .set(ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) - .set(ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, entity.getCharacterId()) - .set(ACTOR_ACTIVE_CONDITIONS.CONDITION_KEY, entity.getConditionKey()) - .set(ACTOR_ACTIVE_CONDITIONS.STACK_COUNT, entity.getStackCount()) - .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE, entity.getSourceType()) - .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID, entity.getSourceId()) - .set(ACTOR_ACTIVE_CONDITIONS.STARTED_AT, toOffsetDateTime(entity.getStartedAt())) - .set(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT, toOffsetDateTime(entity.getExpiresAt())) - .set(ACTOR_ACTIVE_CONDITIONS.EFFECT_PAYLOAD_JSON, entity.getEffectPayloadJson()) - .set(ACTOR_ACTIVE_CONDITIONS.CREATED_AT, toOffsetDateTime(entity.getCreatedAt())) - .set(ACTOR_ACTIVE_CONDITIONS.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) + dsl.insertInto( + ACTOR_ACTIVE_CONDITIONS, + ACTOR_ACTIVE_CONDITIONS.TENANT_ID, + ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY, + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID, + ACTOR_ACTIVE_CONDITIONS.CONDITION_KEY, + ACTOR_ACTIVE_CONDITIONS.STACK_COUNT, + ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE, + ACTOR_ACTIVE_CONDITIONS.SOURCE_ID, + ACTOR_ACTIVE_CONDITIONS.STARTED_AT, + ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT, + ACTOR_ACTIVE_CONDITIONS.EFFECT_PAYLOAD_JSON, + ACTOR_ACTIVE_CONDITIONS.CREATED_AT, + ACTOR_ACTIVE_CONDITIONS.UPDATED_AT) + .select( + dsl.select( + DSL.val(entity.getTenantId(), ACTOR_ACTIVE_CONDITIONS.TENANT_ID), + DSL.val( + entity.getPlayableStateKey(), + ACTOR_ACTIVE_CONDITIONS.PLAYABLE_STATE_KEY), + DSL.val(entity.getCharacterId(), ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID), + DSL.val(entity.getConditionKey(), ACTOR_ACTIVE_CONDITIONS.CONDITION_KEY), + DSL.val(entity.getStackCount(), ACTOR_ACTIVE_CONDITIONS.STACK_COUNT), + DSL.val(entity.getSourceType(), ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE), + DSL.val(entity.getSourceId(), ACTOR_ACTIVE_CONDITIONS.SOURCE_ID), + DSL.val( + toOffsetDateTime(entity.getStartedAt()), + ACTOR_ACTIVE_CONDITIONS.STARTED_AT), + DSL.val( + toOffsetDateTime(entity.getExpiresAt()), + ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT), + DSL.val( + entity.getEffectPayloadJson(), + ACTOR_ACTIVE_CONDITIONS.EFFECT_PAYLOAD_JSON), + DSL.val( + toOffsetDateTime(entity.getCreatedAt()), + ACTOR_ACTIVE_CONDITIONS.CREATED_AT), + DSL.val( + toOffsetDateTime(entity.getUpdatedAt()), + ACTOR_ACTIVE_CONDITIONS.UPDATED_AT)) + .where( + CharacterRepository.legacyCharacterExists( + DSL.val( + entity.getCharacterId(), ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID)))) .returningResult(ACTOR_ACTIVE_CONDITIONS.ID) .fetchOne(ACTOR_ACTIVE_CONDITIONS.ID); + if (id == null) { + throw new IllegalStateException("Legacy condition character is unavailable"); + } entity.setId(id); return entity; } - dsl.update(ACTOR_ACTIVE_CONDITIONS) - .set(ACTOR_ACTIVE_CONDITIONS.CONDITION_KEY, entity.getConditionKey()) - .set(ACTOR_ACTIVE_CONDITIONS.STACK_COUNT, entity.getStackCount()) - .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE, entity.getSourceType()) - .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID, entity.getSourceId()) - .set(ACTOR_ACTIVE_CONDITIONS.STARTED_AT, toOffsetDateTime(entity.getStartedAt())) - .set(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT, toOffsetDateTime(entity.getExpiresAt())) - .set(ACTOR_ACTIVE_CONDITIONS.EFFECT_PAYLOAD_JSON, entity.getEffectPayloadJson()) - .set(ACTOR_ACTIVE_CONDITIONS.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) - .set(ACTOR_ACTIVE_CONDITIONS.VERSION, entity.getVersion() + 1) - .where(ACTOR_ACTIVE_CONDITIONS.ID.eq(entity.getId())) - .execute(); + int updated = + dsl.update(ACTOR_ACTIVE_CONDITIONS) + .set(ACTOR_ACTIVE_CONDITIONS.CONDITION_KEY, entity.getConditionKey()) + .set(ACTOR_ACTIVE_CONDITIONS.STACK_COUNT, entity.getStackCount()) + .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_TYPE, entity.getSourceType()) + .set(ACTOR_ACTIVE_CONDITIONS.SOURCE_ID, entity.getSourceId()) + .set(ACTOR_ACTIVE_CONDITIONS.STARTED_AT, toOffsetDateTime(entity.getStartedAt())) + .set(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT, toOffsetDateTime(entity.getExpiresAt())) + .set(ACTOR_ACTIVE_CONDITIONS.EFFECT_PAYLOAD_JSON, entity.getEffectPayloadJson()) + .set(ACTOR_ACTIVE_CONDITIONS.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) + .set(ACTOR_ACTIVE_CONDITIONS.VERSION, entity.getVersion() + 1) + .where( + ACTOR_ACTIVE_CONDITIONS + .ID + .eq(entity.getId()) + .and( + CharacterRepository.legacyCharacterExists( + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("Legacy condition row is unavailable"); + } entity.setVersion(entity.getVersion() + 1); return entity; } @@ -109,7 +159,10 @@ public int deleteExpired(Instant now) { ACTOR_ACTIVE_CONDITIONS .EXPIRES_AT .isNotNull() - .and(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT.le(toOffsetDateTime(now)))) + .and(ACTOR_ACTIVE_CONDITIONS.EXPIRES_AT.le(toOffsetDateTime(now))) + .and( + CharacterRepository.legacyCharacterExists( + ACTOR_ACTIVE_CONDITIONS.CHARACTER_ID))) .execute(); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java new file mode 100644 index 0000000000..83de1b6c5c --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +/** + * Exact, uncached canonical actor lookup. It intentionally has no write or resolution operation. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class ActorIdentityRepository { + private final DSLContext dsl; + + public ActorIdentityRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public List findOwnerResolvedRoster( + String tenantUuid, + String accountUuid, + String playableStateNamespaceId, + PlayableStateScope playableStateScope) { + UUID tenant = ActorIdentity.parseRequiredUuid(tenantUuid, "tenantUuid"); + UUID account = ActorIdentity.parseRequiredUuid(accountUuid, "accountUuid"); + UUID namespace = + ActorIdentity.parseRequiredUuid(playableStateNamespaceId, "playableStateNamespaceId"); + PlayableStateScope scope = ActorIdentity.requireScope(playableStateScope); + return dsl.select( + CHARACTERS.CHARACTER_UUID, + CHARACTERS.ACCOUNT_UUID, + CHARACTERS.TENANT_UUID, + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, + CHARACTERS.PLAYABLE_STATE_SCOPE, + CHARACTERS.ACTOR_IDENTITY_STATUS, + CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON) + .from(CHARACTERS) + .where( + CHARACTERS + .ACTOR_IDENTITY_STATUS + .eq(ActorIdentityStatus.OWNER_RESOLVED.name()) + .and(CHARACTERS.TENANT_UUID.eq(tenant)) + .and(CHARACTERS.ACCOUNT_UUID.eq(account)) + .and(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq(namespace)) + .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(scope.name()))) + .orderBy(CHARACTERS.CHARACTER_UUID.asc()) + .fetch(this::toIdentity); + } + + public Optional findOwnerResolvedActor( + String tenantUuid, + String accountUuid, + String playableStateNamespaceId, + PlayableStateScope playableStateScope, + String characterUuid) { + UUID tenant = ActorIdentity.parseRequiredUuid(tenantUuid, "tenantUuid"); + UUID account = ActorIdentity.parseRequiredUuid(accountUuid, "accountUuid"); + UUID namespace = + ActorIdentity.parseRequiredUuid(playableStateNamespaceId, "playableStateNamespaceId"); + PlayableStateScope scope = ActorIdentity.requireScope(playableStateScope); + UUID requestedCharacter = ActorIdentity.parseRequiredUuid(characterUuid, "characterUuid"); + return Optional.ofNullable( + dsl.select( + CHARACTERS.CHARACTER_UUID, + CHARACTERS.ACCOUNT_UUID, + CHARACTERS.TENANT_UUID, + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, + CHARACTERS.PLAYABLE_STATE_SCOPE, + CHARACTERS.ACTOR_IDENTITY_STATUS, + CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON) + .from(CHARACTERS) + .where( + CHARACTERS + .ACTOR_IDENTITY_STATUS + .eq(ActorIdentityStatus.OWNER_RESOLVED.name()) + .and(CHARACTERS.TENANT_UUID.eq(tenant)) + .and(CHARACTERS.ACCOUNT_UUID.eq(account)) + .and(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq(namespace)) + .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(scope.name())) + .and(CHARACTERS.CHARACTER_UUID.eq(requestedCharacter))) + .fetchOne(this::toIdentity)); + } + + private ActorIdentity toIdentity(Record record) { + return new ActorIdentity( + record.get(CHARACTERS.CHARACTER_UUID), + record.get(CHARACTERS.ACCOUNT_UUID), + record.get(CHARACTERS.TENANT_UUID), + record.get(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID), + PlayableStateScope.valueOf(record.get(CHARACTERS.PLAYABLE_STATE_SCOPE)), + ActorIdentityStatus.valueOf(record.get(CHARACTERS.ACTOR_IDENTITY_STATUS)), + record.get(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON)); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java index 478bd81341..83ee788a5b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.entitymanagement.entity.ActorResourceState; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @Repository @@ -29,7 +30,8 @@ public List findByTenantIdAndPlayableStateKeyAndCharacterIdO .TENANT_ID .eq(tenantId) .and(ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY.eq(playableStateKey)) - .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(characterId))) + .and(ACTOR_RESOURCE_STATES.CHARACTER_ID.eq(characterId)) + .and(CharacterRepository.legacyCharacterExists(ACTOR_RESOURCE_STATES.CHARACTER_ID))) .orderBy(ACTOR_RESOURCE_STATES.STAT_KEY.asc()) .fetch(this::toEntity); } @@ -37,33 +39,70 @@ public List findByTenantIdAndPlayableStateKeyAndCharacterIdO public ActorResourceState save(ActorResourceState entity) { if (entity.getId() == null) { Long id = - dsl.insertInto(ACTOR_RESOURCE_STATES) - .set(ACTOR_RESOURCE_STATES.TENANT_ID, entity.getTenantId()) - .set(ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) - .set(ACTOR_RESOURCE_STATES.CHARACTER_ID, entity.getCharacterId()) - .set(ACTOR_RESOURCE_STATES.STAT_KEY, entity.getStatKey()) - .set(ACTOR_RESOURCE_STATES.CURRENT_VALUE, entity.getCurrentValue()) - .set(ACTOR_RESOURCE_STATES.MAX_VALUE, entity.getMaxValue()) - .set(ACTOR_RESOURCE_STATES.BASE_VALUE, entity.getBaseValue()) - .set(ACTOR_RESOURCE_STATES.SOURCE_TYPE, entity.getSourceType()) - .set(ACTOR_RESOURCE_STATES.SOURCE_ID, entity.getSourceId()) - .set(ACTOR_RESOURCE_STATES.CREATED_AT, toOffsetDateTime(entity.getCreatedAt())) - .set(ACTOR_RESOURCE_STATES.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) + dsl.insertInto( + ACTOR_RESOURCE_STATES, + ACTOR_RESOURCE_STATES.TENANT_ID, + ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY, + ACTOR_RESOURCE_STATES.CHARACTER_ID, + ACTOR_RESOURCE_STATES.STAT_KEY, + ACTOR_RESOURCE_STATES.CURRENT_VALUE, + ACTOR_RESOURCE_STATES.MAX_VALUE, + ACTOR_RESOURCE_STATES.BASE_VALUE, + ACTOR_RESOURCE_STATES.SOURCE_TYPE, + ACTOR_RESOURCE_STATES.SOURCE_ID, + ACTOR_RESOURCE_STATES.CREATED_AT, + ACTOR_RESOURCE_STATES.UPDATED_AT) + .select( + dsl.select( + DSL.val(entity.getTenantId(), ACTOR_RESOURCE_STATES.TENANT_ID), + DSL.val( + entity.getPlayableStateKey(), + ACTOR_RESOURCE_STATES.PLAYABLE_STATE_KEY), + DSL.val(entity.getCharacterId(), ACTOR_RESOURCE_STATES.CHARACTER_ID), + DSL.val(entity.getStatKey(), ACTOR_RESOURCE_STATES.STAT_KEY), + DSL.val(entity.getCurrentValue(), ACTOR_RESOURCE_STATES.CURRENT_VALUE), + DSL.val(entity.getMaxValue(), ACTOR_RESOURCE_STATES.MAX_VALUE), + DSL.val(entity.getBaseValue(), ACTOR_RESOURCE_STATES.BASE_VALUE), + DSL.val(entity.getSourceType(), ACTOR_RESOURCE_STATES.SOURCE_TYPE), + DSL.val(entity.getSourceId(), ACTOR_RESOURCE_STATES.SOURCE_ID), + DSL.val( + toOffsetDateTime(entity.getCreatedAt()), + ACTOR_RESOURCE_STATES.CREATED_AT), + DSL.val( + toOffsetDateTime(entity.getUpdatedAt()), + ACTOR_RESOURCE_STATES.UPDATED_AT)) + .where( + CharacterRepository.legacyCharacterExists( + DSL.val( + entity.getCharacterId(), ACTOR_RESOURCE_STATES.CHARACTER_ID)))) .returningResult(ACTOR_RESOURCE_STATES.ID) .fetchOne(ACTOR_RESOURCE_STATES.ID); + if (id == null) { + throw new IllegalStateException("Legacy resource character is unavailable"); + } entity.setId(id); return entity; } - dsl.update(ACTOR_RESOURCE_STATES) - .set(ACTOR_RESOURCE_STATES.CURRENT_VALUE, entity.getCurrentValue()) - .set(ACTOR_RESOURCE_STATES.MAX_VALUE, entity.getMaxValue()) - .set(ACTOR_RESOURCE_STATES.BASE_VALUE, entity.getBaseValue()) - .set(ACTOR_RESOURCE_STATES.SOURCE_TYPE, entity.getSourceType()) - .set(ACTOR_RESOURCE_STATES.SOURCE_ID, entity.getSourceId()) - .set(ACTOR_RESOURCE_STATES.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) - .set(ACTOR_RESOURCE_STATES.VERSION, entity.getVersion() + 1) - .where(ACTOR_RESOURCE_STATES.ID.eq(entity.getId())) - .execute(); + int updated = + dsl.update(ACTOR_RESOURCE_STATES) + .set(ACTOR_RESOURCE_STATES.CURRENT_VALUE, entity.getCurrentValue()) + .set(ACTOR_RESOURCE_STATES.MAX_VALUE, entity.getMaxValue()) + .set(ACTOR_RESOURCE_STATES.BASE_VALUE, entity.getBaseValue()) + .set(ACTOR_RESOURCE_STATES.SOURCE_TYPE, entity.getSourceType()) + .set(ACTOR_RESOURCE_STATES.SOURCE_ID, entity.getSourceId()) + .set(ACTOR_RESOURCE_STATES.UPDATED_AT, toOffsetDateTime(entity.getUpdatedAt())) + .set(ACTOR_RESOURCE_STATES.VERSION, entity.getVersion() + 1) + .where( + ACTOR_RESOURCE_STATES + .ID + .eq(entity.getId()) + .and( + CharacterRepository.legacyCharacterExists( + ACTOR_RESOURCE_STATES.CHARACTER_ID))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("Legacy resource row is unavailable"); + } entity.setVersion(entity.getVersion() + 1); return entity; } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java index acfd6bd865..6d7c2e5470 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java @@ -35,7 +35,8 @@ public Page findByIdCharacterIdAndCharacterTenantId( CHARACTER_EQUIPMENT .CHARACTER_ID .eq(characterId) - .and(CHARACTERS.TENANT_ID.eq(tenantId)))); + .and(CHARACTERS.TENANT_ID.eq(tenantId)) + .and(CharacterRepository.legacyCharacterRow()))); var content = dsl.select( CHARACTER_EQUIPMENT.CHARACTER_ID, @@ -68,7 +69,8 @@ public Page findByIdCharacterIdAndCharacterTenantId( CHARACTER_EQUIPMENT .CHARACTER_ID .eq(characterId) - .and(CHARACTERS.TENANT_ID.eq(tenantId))) + .and(CHARACTERS.TENANT_ID.eq(tenantId)) + .and(CharacterRepository.legacyCharacterRow())) .orderBy(CHARACTER_EQUIPMENT.SLOT.asc()) .limit( JooqEntityManagementRepositorySupport.limitOrDefault(pageable, Integer.MAX_VALUE)) @@ -83,7 +85,8 @@ public long countByCharacterTenantId(Long tenantId) { .from(CHARACTER_EQUIPMENT) .join(CHARACTERS) .on(CHARACTER_EQUIPMENT.CHARACTER_ID.eq(CHARACTERS.ID)) - .where(CHARACTERS.TENANT_ID.eq(tenantId))); + .where( + CHARACTERS.TENANT_ID.eq(tenantId).and(CharacterRepository.legacyCharacterRow()))); } private CharacterEquipmentEntry toEntity(Record record) { diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java index a206dbbc9a..ba8f53e915 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java @@ -7,8 +7,10 @@ import java.util.Optional; import net.firedevops.firemud.entitymanagement.entity.CharacterFriend; import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; +import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; @@ -25,10 +27,12 @@ public CharacterFriendRepository(DSLContext dsl) { } public Page findByIdCharacterId(Long characterId, Pageable pageable) { - long total = dsl.fetchCount(CHARACTER_FRIEND, CHARACTER_FRIEND.CHARACTER_ID.eq(characterId)); + Condition condition = + CHARACTER_FRIEND.CHARACTER_ID.eq(characterId).and(legacyFriendEndpoints()); + long total = dsl.fetchCount(CHARACTER_FRIEND, condition); var content = dsl.selectFrom(CHARACTER_FRIEND) - .where(CHARACTER_FRIEND.CHARACTER_ID.eq(characterId)) + .where(condition) .orderBy(CHARACTER_FRIEND.FRIEND_ID.asc()) .limit(limitOrDefault(pageable, Integer.MAX_VALUE)) .offset(offsetOrZero(pageable)) @@ -37,7 +41,8 @@ public Page findByIdCharacterId(Long characterId, Pageable page } public long countByTenantId(Long tenantId) { - return dsl.fetchCount(CHARACTER_FRIEND, CHARACTER_FRIEND.TENANT_ID.eq(tenantId)); + return dsl.fetchCount( + CHARACTER_FRIEND, CHARACTER_FRIEND.TENANT_ID.eq(tenantId).and(legacyFriendEndpoints())); } public Optional findById(CharacterFriendKey key) { @@ -47,18 +52,41 @@ public Optional findById(CharacterFriendKey key) { CHARACTER_FRIEND .CHARACTER_ID .eq(key.getCharacterId()) - .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId()))) + .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId())) + .and(legacyFriendEndpoints())) .fetchOne(this::toEntity)); } public CharacterFriend save(CharacterFriend entity) { if (findById(entity.getId()).isEmpty()) { - dsl.insertInto(CHARACTER_FRIEND) - .set(CHARACTER_FRIEND.CHARACTER_ID, entity.getId().getCharacterId()) - .set(CHARACTER_FRIEND.FRIEND_ID, entity.getId().getFriendId()) - .set(CHARACTER_FRIEND.TENANT_ID, entity.getTenantId()) - .set(CHARACTER_FRIEND.CREATED_AT, toLocalDateTime(entity.getCreatedAt())) - .execute(); + int inserted = + dsl.insertInto( + CHARACTER_FRIEND, + CHARACTER_FRIEND.CHARACTER_ID, + CHARACTER_FRIEND.FRIEND_ID, + CHARACTER_FRIEND.TENANT_ID, + CHARACTER_FRIEND.CREATED_AT) + .select( + dsl.select( + DSL.val(entity.getId().getCharacterId(), CHARACTER_FRIEND.CHARACTER_ID), + DSL.val(entity.getId().getFriendId(), CHARACTER_FRIEND.FRIEND_ID), + DSL.val(entity.getTenantId(), CHARACTER_FRIEND.TENANT_ID), + DSL.val( + toLocalDateTime(entity.getCreatedAt()), CHARACTER_FRIEND.CREATED_AT)) + .where( + CharacterRepository.legacyCharacterExists( + DSL.val( + entity.getId().getCharacterId(), + CHARACTER_FRIEND.CHARACTER_ID)) + .and( + CharacterRepository.legacyCharacterExists( + DSL.val( + entity.getId().getFriendId(), + CHARACTER_FRIEND.FRIEND_ID))))) + .execute(); + if (inserted != 1) { + throw new IllegalStateException("Legacy friend endpoints are unavailable"); + } } return entity; } @@ -69,10 +97,16 @@ public void deleteById(CharacterFriendKey key) { CHARACTER_FRIEND .CHARACTER_ID .eq(key.getCharacterId()) - .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId()))) + .and(CHARACTER_FRIEND.FRIEND_ID.eq(key.getFriendId())) + .and(legacyFriendEndpoints())) .execute(); } + private static Condition legacyFriendEndpoints() { + return CharacterRepository.legacyCharacterExists(CHARACTER_FRIEND.CHARACTER_ID) + .and(CharacterRepository.legacyCharacterExists(CHARACTER_FRIEND.FRIEND_ID)); + } + private CharacterFriend toEntity(Record record) { if (record == null) { return null; diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java index 9e2d219ee4..8bddbdf70c 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java @@ -2,37 +2,172 @@ import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.*; import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; +import static net.firedevops.firemud.entitymanagement.jooq.Tables.ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES; import static net.firedevops.firemud.entitymanagement.jooq.Tables.INVENTORY; import static net.firedevops.firemud.entitymanagement.jooq.Tables.ITEMS; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.Character; import net.firedevops.firemud.entitymanagement.entity.InventoryEntry; import net.firedevops.firemud.entitymanagement.entity.InventoryKey; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshot; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshotDigest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceipt; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceiptRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult.Outcome; +import org.jooq.Condition; import org.jooq.DSLContext; +import org.jooq.Field; import org.jooq.Record; +import org.jooq.Table; import org.jooq.impl.DSL; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; @Repository @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class CharacterRepository { + private static final Table ASSIGNMENT_OPERATIONS = + DSL.table(DSL.name("entity_preseeded_actor_assignment_operations")); + private static final Table TENANT_IDENTITIES = DSL.table(DSL.name("entity_tenant_identities")); + private static final Table ROSTER_SNAPSHOTS = + DSL.table(DSL.name("entity_canonical_gameplay_roster_snapshots")); + private static final Table ROSTER_SNAPSHOT_ACTORS = + DSL.table(DSL.name("entity_canonical_gameplay_roster_snapshot_actors")); + + private static final Field ASSIGNMENT_UUID = uuidField("assignment_uuid"); + private static final Field INTENT_DIGEST = stringField("intent_digest"); + private static final Field ACCOUNT_UUID = uuidField("account_uuid"); + private static final Field ACCOUNT_UUID_PROVENANCE = + stringField("account_uuid_provenance"); + private static final Field ACCOUNT_IDENTITY_SCHEMA_VERSION = + DSL.field(DSL.name("account_identity_schema_version"), Short.class); + private static final Field ACCOUNT_IDENTITY_TARGET_NAMESPACE = + stringField("account_identity_target_namespace"); + private static final Field SOURCE_ACCOUNT_ROW_ID = longField("source_account_row_id"); + private static final Field ELIGIBILITY = stringField("eligibility"); + private static final Field ELIGIBILITY_EVALUATED_AT = + DSL.field(DSL.name("eligibility_evaluated_at"), OffsetDateTime.class); + private static final Field MEMBERSHIP_AUTHORITY_GENERATION = + longField("membership_authority_generation"); + private static final Field ELIGIBILITY_EVIDENCE_DIGEST = + stringField("eligibility_evidence_digest"); + private static final Field ACCOUNT_AUTHORITY_SNAPSHOT_DIGEST = + stringField("account_authority_snapshot_digest"); + private static final Field ACCOUNT_PURPOSE = stringField("account_purpose"); + private static final Field ACCOUNT_CURRENTNESS = stringField("account_currentness"); + private static final Field PUBLISHED_OWNER_PROOF_DIGEST = + stringField("published_owner_proof_digest"); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + stringField("published_release_bundle_ref"); + private static final Field TENANT_UUID = uuidField("tenant_uuid"); + private static final Field CANONICAL_TENANT_UUID = uuidField("canonical_tenant_uuid"); + private static final Field REALM_UUID = uuidField("realm_uuid"); + private static final Field WORLD_SLUG = stringField("world_slug"); + private static final Field REALM_SLUG = stringField("realm_slug"); + private static final Field GAME_INSTANCE_ID = stringField("game_instance_id"); + private static final Field CATALOG_REVISION = longField("catalog_revision"); + private static final Field CANONICAL_VERSION_UUID = uuidField("canonical_version_uuid"); + private static final Field PUBLICATION_EVIDENCE_FORMAT = + stringField("publication_evidence_format"); + private static final String CURRENT_PUBLICATION_EVIDENCE_FORMAT = "CANONICAL_UUID"; + private static final Field FROZEN_POLICY_DIGEST = stringField("frozen_policy_digest"); + private static final Field NAMESPACE_UUID = uuidField("playable_state_namespace_id"); + private static final Field PLAYABLE_STATE_SCOPE = stringField("playable_state_scope"); + private static final Field ENTRY_POLICY = stringField("entry_policy"); + private static final Field ACTOR_KIND = stringField("actor_kind"); + private static final Field DISPLAY_NAME = stringField("display_name"); + private static final Field ASSIGNMENT_STATUS = stringField("status"); + private static final Field ASSIGNED_CHARACTER_UUID = uuidField("character_uuid"); + private static final Field ASSIGNMENT_COMPLETED_AT = + DSL.field(DSL.name("completed_at"), OffsetDateTime.class); + private static final Field ENTITY_TENANT_ROW_ID = longField("entity_tenant_row_id"); + private static final Field ROSTER_SNAPSHOT_UUID = uuidField("snapshot_uuid"); + private static final Field ROSTER_SNAPSHOT_DIGEST = stringField("snapshot_digest"); + private static final Field ROSTER_ACCOUNT_UUID = uuidField("canonical_account_uuid"); + private static final Field ROSTER_TENANT_UUID = uuidField("tenant_uuid"); + private static final Field ROSTER_REALM_UUID = uuidField("realm_uuid"); + private static final Field ROSTER_WORLD_SLUG = stringField("world_slug"); + private static final Field ROSTER_REALM_SLUG = stringField("realm_slug"); + private static final Field ROSTER_GAME_INSTANCE_UUID = uuidField("game_instance_uuid"); + private static final Field ROSTER_CATALOG_REVISION = longField("catalog_revision"); + private static final Field ROSTER_CANONICAL_VERSION_UUID = + uuidField("canonical_version_uuid"); + private static final Field ROSTER_POINTER_VERSION = longField("pointer_version"); + private static final Field ROSTER_ACTIVE_WORLD_EPOCH = longField("active_world_epoch"); + private static final Field ROSTER_PUBLICATION_EVIDENCE_FORMAT = + stringField("publication_evidence_format"); + private static final String CURRENT_ROSTER_EVIDENCE_FORMAT = "CANONICAL_UUID_V2"; + private static final Field ROSTER_PUBLISHED_POLICY_DIGEST = + stringField("published_policy_digest"); + private static final Field ROSTER_PUBLISHED_RELEASE_REF = + stringField("published_release_bundle_ref"); + private static final Field ROSTER_POINTER_SNAPSHOT_DIGEST = + stringField("admission_pointer_snapshot_digest"); + private static final Field ROSTER_OWNER_PROOF_DIGEST = + stringField("published_owner_proof_digest"); + private static final Field ROSTER_NAMESPACE_UUID = + uuidField("playable_state_namespace_uuid"); + private static final Field ROSTER_PLAYABLE_SCOPE = stringField("playable_state_scope"); + private static final Field ROSTER_ENTRY_POLICY = stringField("entry_policy"); + private static final Field ROSTER_COUNT = DSL.field(DSL.name("roster_count"), Short.class); + private static final Field ROSTER_CONSTRUCTION_STATE = stringField("construction_state"); + private static final Field ROSTER_ORDINAL = + DSL.field(DSL.name("ordinal_position"), Short.class); + private static final Field ROSTER_CHARACTER_UUID = uuidField("character_uuid"); + private static final Field ROSTER_DISPLAY_NAME = stringField("display_name"); + private static final Field ROSTER_ACTOR_KIND = stringField("actor_kind"); + private final DSLContext dsl; public CharacterRepository(DSLContext dsl) { this.dsl = dsl; } + static Condition legacyCharacterExists(Field characterId) { + return DSL.exists( + DSL.selectOne() + .from(CHARACTERS) + .where(CHARACTERS.ID.eq(characterId).and(legacyCharacterRow()))); + } + + static Condition legacyCharacterRow() { + return CHARACTERS + .ACTOR_IDENTITY_STATUS + .ne(ActorIdentityStatus.OWNER_RESOLVED.name()) + .and(CHARACTERS.TENANT_UUID.isNull()); + } + public Optional findWithInventoryById(Long id) { Character character = - dsl.selectFrom(CHARACTERS).where(CHARACTERS.ID.eq(id)).fetchOne(this::toEntity); + dsl.selectFrom(CHARACTERS) + .where(CHARACTERS.ID.eq(id).and(legacyCharacterRow())) + .fetchOne(this::toEntity); if (character == null) { return Optional.empty(); } @@ -42,6 +177,7 @@ public Optional findWithInventoryById(Long id) { INVENTORY.CHARACTER_ID, INVENTORY.ITEM_ID, INVENTORY.QUANTITY, + INVENTORY.VERSION, ITEMS.ID, ITEMS.TENANT_ID, ITEMS.VERSION_ID, @@ -65,13 +201,20 @@ public Optional findWithInventoryById(Long id) { public Optional findById(Long id) { return Optional.ofNullable( - dsl.selectFrom(CHARACTERS).where(CHARACTERS.ID.eq(id)).fetchOne(this::toEntity)); + dsl.selectFrom(CHARACTERS) + .where(CHARACTERS.ID.eq(id).and(legacyCharacterRow())) + .fetchOne(this::toEntity)); } public Optional findByIdAndTenantId(Long id, Long tenantId) { return Optional.ofNullable( dsl.selectFrom(CHARACTERS) - .where(CHARACTERS.ID.eq(id).and(CHARACTERS.TENANT_ID.eq(tenantId))) + .where( + CHARACTERS + .ID + .eq(id) + .and(CHARACTERS.TENANT_ID.eq(tenantId)) + .and(legacyCharacterRow())) .fetchOne(this::toEntity)); } @@ -84,7 +227,8 @@ public Optional findByIdAndTenantIdAndPlayableStateKey( .ID .eq(id) .and(CHARACTERS.TENANT_ID.eq(tenantId)) - .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey))) + .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)) + .and(legacyCharacterRow())) .fetchOne(this::toEntity)); } @@ -95,7 +239,8 @@ public Page findByTenantIdAndAccountIdAndPlayableStateKey( .TENANT_ID .eq(tenantId) .and(CHARACTERS.ACCOUNT_ID.eq(accountId)) - .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)); + .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)) + .and(legacyCharacterRow()); long total = dsl.fetchCount(CHARACTERS, condition); var content = dsl.selectFrom(CHARACTERS) @@ -118,19 +263,1042 @@ public Optional findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( .TENANT_ID .eq(tenantId) .and(CHARACTERS.PLAYABLE_STATE_KEY.eq(playableStateKey)) - .and(DSL.lower(CHARACTERS.NAME).eq(name.toLowerCase()))) + .and(DSL.lower(CHARACTERS.NAME).eq(name.toLowerCase())) + .and(legacyCharacterRow())) .limit(1) .fetchOne(this::toEntity)); } public long countByTenantId(Long tenantId) { - return dsl.fetchCount(CHARACTERS, CHARACTERS.TENANT_ID.eq(tenantId)); + return dsl.fetchCount(CHARACTERS, CHARACTERS.TENANT_ID.eq(tenantId).and(legacyCharacterRow())); + } + + public long countQuarantinedByTenantId(Long tenantId) { + return dsl.fetchCount( + CHARACTERS, + CHARACTERS + .TENANT_ID + .eq(tenantId) + .and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq(ActorIdentityStatus.QUARANTINED.name())) + .and(CHARACTERS.TENANT_UUID.isNull())); + } + + /** + * Atomically enrolls the owner-proven namespace, records one replay guard, and allocates the + * Entity-owned actor/account association after the protected assignment service authorizes the + * exact run-owned action and owner evidence. The committed actor is non-admitting; this + * repository operation has no direct RPC adapter and grants no PLAY authority. + */ + @Transactional + public PreseededActorAssignmentResult assignPreseededActor( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence evidence, + RuntimeAccountIdentityEvidence accountIdentityEvidence, + String intentDigest) { + if (request == null + || evidence == null + || evidence.eligibility() != PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE + || evidence.entryPolicy() + != PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY + || evidence.accountPurpose() + != PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING + || evidence.accountCurrentness() + != PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION + || accountIdentityEvidence == null + || !request.assignmentUuid().equals(evidence.assignmentUuid()) + || !request.canonicalAccountUuid().equals(evidence.canonicalAccountUuid()) + || !request.expectedTarget().exactlyMatches(evidence) + || !evidence.assignmentUuid().equals(accountIdentityEvidence.requestId()) + || !evidence.canonicalAccountUuid().equals(accountIdentityEvidence.canonicalAccountId()) + || intentDigest == null + || !intentDigest.matches("[0-9a-f]{64}") + || !request.mutationIntentDigest().equals(intentDigest)) { + throw new IllegalArgumentException("Exact eligible pre-seeded assignment proof is required"); + } + + var insertedGuard = + insertAssignmentGuard(request, evidence, accountIdentityEvidence, intentDigest); + if (insertedGuard == null) { + return replayOrConflict(request, evidence, intentDigest); + } + + enrollNamespace(evidence); + long entityTenantRowId = requireEntityTenantRow(evidence.canonicalTenantUuid()); + if (hasOwnerResolvedAccountNamespace(evidence)) { + completeWithoutActor(evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT); + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT, null, intentDigest); + } + UUID characterUuid = UUID.randomUUID(); + + if (!insertOwnerResolvedCharacter( + request, + evidence, + accountIdentityEvidence.sourceAccountRowId(), + entityTenantRowId, + characterUuid)) { + // The partial unique index is the final guard if another writer does not use this row lock. + // Persist the deterministic loser result after confirming the account/namespace slot won. + if (!hasOwnerResolvedAccountNamespace(evidence)) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACTOR_INSERT_FAILED"); + } + completeWithoutActor(evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT); + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT, null, intentDigest); + } + completeWithActor(evidence.assignmentUuid(), characterUuid); + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.ASSIGNED, characterUuid, intentDigest); + } + + private Record insertAssignmentGuard( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence evidence, + RuntimeAccountIdentityEvidence accountIdentityEvidence, + String intentDigest) { + return dsl.insertInto(ASSIGNMENT_OPERATIONS) + .set(ASSIGNMENT_UUID, evidence.assignmentUuid()) + .set(INTENT_DIGEST, intentDigest) + .set(ACCOUNT_UUID, evidence.canonicalAccountUuid()) + .set(ACCOUNT_UUID_PROVENANCE, accountIdentityEvidence.accountUuidProvenance()) + .set(ACCOUNT_IDENTITY_SCHEMA_VERSION, (short) accountIdentityEvidence.schemaVersion()) + .set(ACCOUNT_IDENTITY_TARGET_NAMESPACE, accountIdentityEvidence.targetNamespace()) + .set(SOURCE_ACCOUNT_ROW_ID, accountIdentityEvidence.sourceAccountRowId()) + .set(ELIGIBILITY, evidence.eligibility().name()) + .set( + ELIGIBILITY_EVALUATED_AT, + OffsetDateTime.ofInstant(evidence.eligibilityEvaluatedAt(), ZoneOffset.UTC)) + .set(MEMBERSHIP_AUTHORITY_GENERATION, evidence.membershipAuthorityGeneration()) + .set(ELIGIBILITY_EVIDENCE_DIGEST, evidence.eligibilityEvidenceDigest()) + .set(ACCOUNT_AUTHORITY_SNAPSHOT_DIGEST, evidence.accountAuthoritySnapshotDigest()) + .set(ACCOUNT_PURPOSE, evidence.accountPurpose().name()) + .set(ACCOUNT_CURRENTNESS, evidence.accountCurrentness().name()) + .set(PUBLISHED_OWNER_PROOF_DIGEST, evidence.publishedOwnerProofDigest()) + .set(PUBLISHED_RELEASE_BUNDLE_REF, evidence.publishedReleaseBundleRef()) + .set(TENANT_UUID, evidence.canonicalTenantUuid()) + .set(REALM_UUID, evidence.realmUuid()) + .set(WORLD_SLUG, evidence.worldSlug()) + .set(REALM_SLUG, evidence.realmSlug()) + .set(GAME_INSTANCE_ID, evidence.gameInstanceId()) + .set(CATALOG_REVISION, evidence.catalogRevision()) + .set(CANONICAL_VERSION_UUID, evidence.canonicalVersionUuid()) + .set(PUBLICATION_EVIDENCE_FORMAT, CURRENT_PUBLICATION_EVIDENCE_FORMAT) + .set(FROZEN_POLICY_DIGEST, evidence.frozenPolicyDigest()) + .set(NAMESPACE_UUID, evidence.playableStateNamespaceId()) + .set(PLAYABLE_STATE_SCOPE, evidence.playableStateScope().name()) + .set(ENTRY_POLICY, evidence.entryPolicy().name()) + .set(ACTOR_KIND, request.corePayload().actorKind().name()) + .set(DISPLAY_NAME, request.corePayload().displayName()) + .set(ASSIGNMENT_STATUS, "PENDING") + .onConflict(ASSIGNMENT_UUID) + .doNothing() + .returning(ASSIGNMENT_UUID) + .fetchOne(); + } + + private PreseededActorAssignmentResult replayOrConflict( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence evidence, + String requestedDigest) { + Record stored = + dsl.select( + INTENT_DIGEST, + ACCOUNT_UUID, + ASSIGNMENT_COMPLETED_AT, + TENANT_UUID, + REALM_UUID, + WORLD_SLUG, + REALM_SLUG, + GAME_INSTANCE_ID, + CATALOG_REVISION, + CANONICAL_VERSION_UUID, + PUBLICATION_EVIDENCE_FORMAT, + FROZEN_POLICY_DIGEST, + NAMESPACE_UUID, + PLAYABLE_STATE_SCOPE, + ENTRY_POLICY, + ACTOR_KIND, + DISPLAY_NAME, + ASSIGNMENT_STATUS, + ASSIGNED_CHARACTER_UUID, + PUBLISHED_RELEASE_BUNDLE_REF) + .from(ASSIGNMENT_OPERATIONS) + .where(ASSIGNMENT_UUID.eq(evidence.assignmentUuid())) + .forUpdate() + .fetchOne(); + if (stored == null) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_REPLAY_GUARD_UNAVAILABLE"); + } + if (!CURRENT_PUBLICATION_EVIDENCE_FORMAT.equals(stored.get(PUBLICATION_EVIDENCE_FORMAT))) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_LEGACY_PUBLICATION_EVIDENCE"); + } + if (!requestedDigest.equals(stored.get(INTENT_DIGEST))) { + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT, null, requestedDigest); + } + requireSameStoredIntent(stored, request, evidence); + + String status = stored.get(ASSIGNMENT_STATUS); + UUID characterUuid = stored.get(ASSIGNED_CHARACTER_UUID); + OffsetDateTime completedAt = stored.get(ASSIGNMENT_COMPLETED_AT); + if ("IDEMPOTENCY_CONFLICT".equals(status) && characterUuid == null && completedAt != null) { + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.IDEMPOTENCY_CONFLICT, null, requestedDigest); + } + if ("ASSIGNED".equals(status) && characterUuid != null && completedAt != null) { + requireStoredAssignedActor(evidence, characterUuid); + return new PreseededActorAssignmentResult( + evidence.assignmentUuid(), Outcome.ASSIGNED, characterUuid, requestedDigest); + } + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_REPLAY_RESULT_INCOMPLETE"); + } + + private void requireSameStoredIntent( + Record stored, + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence evidence) { + boolean sameIntent = + evidence.canonicalAccountUuid().equals(stored.get(ACCOUNT_UUID)) + && evidence.canonicalTenantUuid().equals(stored.get(TENANT_UUID)) + && evidence.realmUuid().equals(stored.get(REALM_UUID)) + && evidence.worldSlug().equals(stored.get(WORLD_SLUG)) + && evidence.realmSlug().equals(stored.get(REALM_SLUG)) + && evidence.gameInstanceId().equals(stored.get(GAME_INSTANCE_ID)) + && evidence.catalogRevision() == stored.get(CATALOG_REVISION) + && evidence.canonicalVersionUuid().equals(stored.get(CANONICAL_VERSION_UUID)) + && evidence.frozenPolicyDigest().equals(stored.get(FROZEN_POLICY_DIGEST)) + && evidence.playableStateNamespaceId().equals(stored.get(NAMESPACE_UUID)) + && evidence.playableStateScope().name().equals(stored.get(PLAYABLE_STATE_SCOPE)) + && evidence.entryPolicy().name().equals(stored.get(ENTRY_POLICY)) + && evidence.publishedReleaseBundleRef().equals(stored.get(PUBLISHED_RELEASE_BUNDLE_REF)) + && request.corePayload().actorKind().name().equals(stored.get(ACTOR_KIND)) + && request.corePayload().displayName().equals(stored.get(DISPLAY_NAME)); + if (!sameIntent) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_STORED_INTENT_MISMATCH"); + } + } + + /** Returns only an exact committed operation whose PLAYER row remains owner-resolved. */ + @Transactional(readOnly = true) + public Optional readPreseededActorAssignmentReceipt( + PreseededActorAssignmentReceiptRequest request) { + Record operation = + dsl.select( + ASSIGNMENT_UUID, + INTENT_DIGEST, + ACCOUNT_UUID, + ACCOUNT_UUID_PROVENANCE, + ACCOUNT_IDENTITY_SCHEMA_VERSION, + ACCOUNT_IDENTITY_TARGET_NAMESPACE, + SOURCE_ACCOUNT_ROW_ID, + ELIGIBILITY, + ELIGIBILITY_EVALUATED_AT, + MEMBERSHIP_AUTHORITY_GENERATION, + ELIGIBILITY_EVIDENCE_DIGEST, + ACCOUNT_AUTHORITY_SNAPSHOT_DIGEST, + ACCOUNT_PURPOSE, + ACCOUNT_CURRENTNESS, + PUBLISHED_OWNER_PROOF_DIGEST, + PUBLISHED_RELEASE_BUNDLE_REF, + TENANT_UUID, + REALM_UUID, + WORLD_SLUG, + REALM_SLUG, + GAME_INSTANCE_ID, + CATALOG_REVISION, + CANONICAL_VERSION_UUID, + PUBLICATION_EVIDENCE_FORMAT, + FROZEN_POLICY_DIGEST, + NAMESPACE_UUID, + PLAYABLE_STATE_SCOPE, + ENTRY_POLICY, + ACTOR_KIND, + ASSIGNMENT_STATUS, + ASSIGNED_CHARACTER_UUID, + DISPLAY_NAME, + ASSIGNMENT_COMPLETED_AT) + .from(ASSIGNMENT_OPERATIONS) + .where(ASSIGNMENT_UUID.eq(request.assignmentUuid())) + .fetchOne(); + if (operation == null + || !request.canonicalAccountUuid().equals(operation.get(ACCOUNT_UUID)) + || operation.get(ACCOUNT_UUID_PROVENANCE) == null + || operation.get(ACCOUNT_UUID_PROVENANCE).isBlank() + || operation.get(ACCOUNT_IDENTITY_SCHEMA_VERSION) == null + || operation.get(ACCOUNT_IDENTITY_TARGET_NAMESPACE) == null + || operation.get(SOURCE_ACCOUNT_ROW_ID) == null + || operation.get(TENANT_UUID) == null + || operation.get(REALM_UUID) == null + || operation.get(WORLD_SLUG) == null + || operation.get(REALM_SLUG) == null + || operation.get(GAME_INSTANCE_ID) == null + || operation.get(CATALOG_REVISION) == null + || !CURRENT_PUBLICATION_EVIDENCE_FORMAT.equals(operation.get(PUBLICATION_EVIDENCE_FORMAT)) + || operation.get(CANONICAL_VERSION_UUID) == null + || operation.get(FROZEN_POLICY_DIGEST) == null + || operation.get(NAMESPACE_UUID) == null + || operation.get(PUBLISHED_RELEASE_BUNDLE_REF) == null + || operation.get(PLAYABLE_STATE_SCOPE) == null + || operation.get(DISPLAY_NAME) == null + || !"ELIGIBLE".equals(operation.get(ELIGIBILITY)) + || !request.intentDigest().equals(operation.get(INTENT_DIGEST)) + || !"PLAYER".equals(operation.get(ACTOR_KIND)) + || !"ASSIGNED".equals(operation.get(ASSIGNMENT_STATUS)) + || operation.get(ASSIGNMENT_COMPLETED_AT) == null + || !request.characterUuid().equals(operation.get(ASSIGNED_CHARACTER_UUID))) { + return Optional.empty(); + } + + Record actor = + dsl.select( + CHARACTERS.CHARACTER_UUID, + CHARACTERS.ACCOUNT_ID, + CHARACTERS.ACCOUNT_UUID, + CHARACTERS.TENANT_UUID, + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, + CHARACTERS.PLAYABLE_STATE_SCOPE, + CHARACTERS.ACTOR_IDENTITY_STATUS, + CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON, + CHARACTERS.NAME) + .from(CHARACTERS) + .where(CHARACTERS.CHARACTER_UUID.eq(request.characterUuid())) + .fetchOne(); + if (actor == null + || !request.canonicalAccountUuid().equals(actor.get(CHARACTERS.ACCOUNT_UUID)) + || !Objects.equals(operation.get(SOURCE_ACCOUNT_ROW_ID), actor.get(CHARACTERS.ACCOUNT_ID)) + || !Objects.equals(operation.get(TENANT_UUID), actor.get(CHARACTERS.TENANT_UUID)) + || !Objects.equals( + operation.get(NAMESPACE_UUID), actor.get(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID)) + || !Objects.equals( + operation.get(PLAYABLE_STATE_SCOPE), actor.get(CHARACTERS.PLAYABLE_STATE_SCOPE)) + || !ActorIdentityStatus.OWNER_RESOLVED + .name() + .equals(actor.get(CHARACTERS.ACTOR_IDENTITY_STATUS)) + || actor.get(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON) != null + || !Objects.equals(operation.get(DISPLAY_NAME), actor.get(CHARACTERS.NAME))) { + return Optional.empty(); + } + + try { + var target = + new PreseededActorAssignmentExpectedTarget( + operation.get(TENANT_UUID), + operation.get(REALM_UUID), + operation.get(WORLD_SLUG), + operation.get(REALM_SLUG), + operation.get(GAME_INSTANCE_ID), + operation.get(CATALOG_REVISION), + operation.get(CANONICAL_VERSION_UUID), + operation.get(FROZEN_POLICY_DIGEST), + operation.get(NAMESPACE_UUID), + operation.get(PUBLISHED_RELEASE_BUNDLE_REF), + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.valueOf( + operation.get(PLAYABLE_STATE_SCOPE))); + if (!request.expectedTarget().equals(target)) { + return Optional.empty(); + } + OffsetDateTime evaluatedAt = operation.get(ELIGIBILITY_EVALUATED_AT); + String evidenceDigest = operation.get(ELIGIBILITY_EVIDENCE_DIGEST); + String authorityDigest = operation.get(ACCOUNT_AUTHORITY_SNAPSHOT_DIGEST); + String purpose = operation.get(ACCOUNT_PURPOSE); + String currentness = operation.get(ACCOUNT_CURRENTNESS); + String ownerProofDigest = operation.get(PUBLISHED_OWNER_PROOF_DIGEST); + String releaseRef = operation.get(PUBLISHED_RELEASE_BUNDLE_REF); + String entryPolicy = operation.get(ENTRY_POLICY); + Long generation = operation.get(MEMBERSHIP_AUTHORITY_GENERATION); + if (evaluatedAt == null + || generation == null + || generation <= 0 + || evidenceDigest == null + || authorityDigest == null + || ownerProofDigest == null + || releaseRef == null + || purpose == null + || currentness == null + || !"PRESEEDED_ACTOR_STAGING".equals(purpose) + || !"CURRENT_AT_REVALIDATION".equals(currentness) + || !"PRESEEDED_ONLY".equals(entryPolicy)) { + return Optional.empty(); + } + return Optional.of( + new PreseededActorAssignmentReceipt( + request.assignmentUuid(), + request.canonicalAccountUuid(), + request.characterUuid(), + request.intentDigest(), + target, + new net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload( + net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload + .ActorKind.valueOf(operation.get(ACTOR_KIND)), + operation.get(DISPLAY_NAME)), + operation.get(ACCOUNT_IDENTITY_SCHEMA_VERSION).intValue(), + operation.get(ACCOUNT_IDENTITY_TARGET_NAMESPACE), + operation.get(SOURCE_ACCOUNT_ROW_ID), + operation.get(ACCOUNT_UUID_PROVENANCE), + PreseededActorAssignmentOwnerEvidence.Eligibility.valueOf(operation.get(ELIGIBILITY)), + evaluatedAt.toInstant(), + generation, + evidenceDigest, + authorityDigest, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.valueOf(purpose), + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.valueOf(currentness), + ownerProofDigest, + releaseRef, + entryPolicy, + operation.get(ASSIGNMENT_STATUS))); + } catch (IllegalArgumentException invalidStoredReceipt) { + return Optional.empty(); + } + } + + /** + * Resolves one historical assignment for an exact selected actor and immutable target. Current + * owner counters are independently checked before this method is called; the persisted owner + * proof digest must still match that owner-resolved target. Zero or multiple matches disclose no + * assignment reference. + */ + @Transactional(readOnly = true) + public Optional readSelectedPreseededActorAssignmentReceipt( + UUID canonicalAccountUuid, + UUID selectedCharacterUuid, + PreseededActorAssignmentExpectedTarget expectedTarget, + String publishedOwnerProofDigest) { + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(selectedCharacterUuid, "selectedCharacterUuid"); + Objects.requireNonNull(expectedTarget, "expectedTarget"); + if (publishedOwnerProofDigest == null || !publishedOwnerProofDigest.matches("[0-9a-f]{64}")) { + return Optional.empty(); + } + + List matchingOperations = + dsl.select(ASSIGNMENT_UUID, INTENT_DIGEST) + .from(ASSIGNMENT_OPERATIONS) + .where( + ACCOUNT_UUID + .eq(canonicalAccountUuid) + .and(ASSIGNED_CHARACTER_UUID.eq(selectedCharacterUuid)) + .and(TENANT_UUID.eq(expectedTarget.canonicalTenantUuid())) + .and(REALM_UUID.eq(expectedTarget.realmUuid())) + .and(WORLD_SLUG.eq(expectedTarget.worldSlug())) + .and(REALM_SLUG.eq(expectedTarget.realmSlug())) + .and(GAME_INSTANCE_ID.eq(expectedTarget.gameInstanceId())) + .and(CATALOG_REVISION.eq(expectedTarget.catalogRevision())) + .and(CANONICAL_VERSION_UUID.eq(expectedTarget.canonicalVersionUuid())) + .and(FROZEN_POLICY_DIGEST.eq(expectedTarget.frozenPolicyDigest())) + .and(NAMESPACE_UUID.eq(expectedTarget.playableStateNamespaceId())) + .and(PLAYABLE_STATE_SCOPE.eq(expectedTarget.playableStateScope().name())) + .and( + PUBLISHED_RELEASE_BUNDLE_REF.eq(expectedTarget.publishedReleaseBundleRef())) + .and(PUBLISHED_OWNER_PROOF_DIGEST.eq(publishedOwnerProofDigest)) + .and(ENTRY_POLICY.eq("PRESEEDED_ONLY")) + .and(ACTOR_KIND.eq("PLAYER")) + .and(ASSIGNMENT_STATUS.eq("ASSIGNED")) + .and(ASSIGNMENT_COMPLETED_AT.isNotNull())) + .limit(2) + .fetch(); + Optional uniqueOperation = onlyOneAssignmentMatch(matchingOperations); + if (uniqueOperation.isEmpty()) { + return Optional.empty(); + } + + Record operation = uniqueOperation.orElseThrow(); + UUID assignmentUuid = operation.get(ASSIGNMENT_UUID); + String intentDigest = operation.get(INTENT_DIGEST); + if (assignmentUuid == null || intentDigest == null || !intentDigest.matches("[0-9a-f]{64}")) { + return Optional.empty(); + } + Optional receipt = + readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + canonicalAccountUuid, + selectedCharacterUuid, + intentDigest, + expectedTarget)); + if (receipt.isEmpty() + || !publishedOwnerProofDigest.equals(receipt.orElseThrow().publishedOwnerProofDigest())) { + return Optional.empty(); + } + return receipt; + } + + static Optional onlyOneAssignmentMatch(List matchingOperations) { + if (matchingOperations == null || matchingOperations.size() != 1) { + return Optional.empty(); + } + return Optional.ofNullable(matchingOperations.get(0)); + } + + /** + * Locks the immutable assignment and its current actor row before returning the exact receipt. + * Callers use this only inside the same writable transaction that records an applicability hold, + * so actor changes either win first and invalidate the receipt or observe the durable hold. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional lockCurrentPreseededActorAssignmentReceipt( + UUID assignmentUuid, UUID canonicalAccountUuid, UUID characterUuid, String intentDigest) { + if (!org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Pre-seeded placement receipt locking requires the writable hold transaction"); + } + Record operation = + dsl.select( + INTENT_DIGEST, + ACCOUNT_UUID, + TENANT_UUID, + REALM_UUID, + WORLD_SLUG, + REALM_SLUG, + GAME_INSTANCE_ID, + CATALOG_REVISION, + CANONICAL_VERSION_UUID, + FROZEN_POLICY_DIGEST, + NAMESPACE_UUID, + PLAYABLE_STATE_SCOPE, + PUBLISHED_RELEASE_BUNDLE_REF, + ASSIGNED_CHARACTER_UUID) + .from(ASSIGNMENT_OPERATIONS) + .where(ASSIGNMENT_UUID.eq(assignmentUuid)) + .forUpdate() + .fetchOne(); + if (operation == null + || !canonicalAccountUuid.equals(operation.get(ACCOUNT_UUID)) + || !characterUuid.equals(operation.get(ASSIGNED_CHARACTER_UUID)) + || !intentDigest.equals(operation.get(INTENT_DIGEST))) { + return Optional.empty(); + } + Record actor = + dsl.select(CHARACTERS.CHARACTER_UUID) + .from(CHARACTERS) + .where(CHARACTERS.CHARACTER_UUID.eq(characterUuid)) + .forUpdate() + .fetchOne(); + if (actor == null) { + return Optional.empty(); + } + try { + var target = + new PreseededActorAssignmentExpectedTarget( + operation.get(TENANT_UUID), + operation.get(REALM_UUID), + operation.get(WORLD_SLUG), + operation.get(REALM_SLUG), + operation.get(GAME_INSTANCE_ID), + operation.get(CATALOG_REVISION), + operation.get(CANONICAL_VERSION_UUID), + operation.get(FROZEN_POLICY_DIGEST), + operation.get(NAMESPACE_UUID), + operation.get(PUBLISHED_RELEASE_BUNDLE_REF), + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.valueOf( + operation.get(PLAYABLE_STATE_SCOPE))); + return readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, canonicalAccountUuid, characterUuid, intentDigest, target)); + } catch (IllegalArgumentException invalidStoredTarget) { + return Optional.empty(); + } + } + + private void enrollNamespace(PreseededActorAssignmentOwnerEvidence evidence) { + dsl.insertInto(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .set(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.TENANT_UUID, evidence.canonicalTenantUuid()) + .set( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID, + evidence.playableStateNamespaceId()) + .set( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE, + evidence.playableStateScope().name()) + .onConflict( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.TENANT_UUID, + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID) + .doNothing() + .execute(); + + String enrolledScope = + dsl.select(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE) + .from(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .where( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES + .TENANT_UUID + .eq(evidence.canonicalTenantUuid()) + .and( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID.eq( + evidence.playableStateNamespaceId()))) + .forUpdate() + .fetchOne(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE); + if (!evidence.playableStateScope().name().equals(enrolledScope)) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_NAMESPACE_SCOPE_MISMATCH"); + } + } + + private long requireEntityTenantRow(UUID tenantUuid) { + ensureEntityTenantRow(tenantUuid); + Long rowId = + dsl.select(ENTITY_TENANT_ROW_ID) + .from(TENANT_IDENTITIES) + .where(CANONICAL_TENANT_UUID.eq(tenantUuid)) + .forUpdate() + .fetchOne(ENTITY_TENANT_ROW_ID); + if (rowId == null || rowId <= 0L) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ENTITY_TENANT_MAPPING_UNAVAILABLE"); + } + return rowId; + } + + private long requireEntityTenantRowForRoster(UUID tenantUuid) { + ensureEntityTenantRow(tenantUuid); + // Assignment's FOR UPDATE still excludes this reader while the immutable mapping stays stable. + Long rowId = + dsl.select(ENTITY_TENANT_ROW_ID) + .from(TENANT_IDENTITIES) + .where(CANONICAL_TENANT_UUID.eq(tenantUuid)) + .forKeyShare() + .fetchOne(ENTITY_TENANT_ROW_ID); + if (rowId == null || rowId <= 0L) { + throw new IllegalStateException( + "CANONICAL_GAMEPLAY_ROSTER_ENTITY_TENANT_MAPPING_UNAVAILABLE"); + } + return rowId; + } + + private void ensureEntityTenantRow(UUID tenantUuid) { + dsl.insertInto(TENANT_IDENTITIES) + .set(CANONICAL_TENANT_UUID, tenantUuid) + .onConflict(CANONICAL_TENANT_UUID) + .doNothing() + .execute(); + } + + private boolean hasOwnerResolvedAccountNamespace(PreseededActorAssignmentOwnerEvidence evidence) { + UUID existingActor = + dsl.select(CHARACTERS.CHARACTER_UUID) + .from(CHARACTERS) + .where( + CHARACTERS + .TENANT_UUID + .eq(evidence.canonicalTenantUuid()) + .and(CHARACTERS.ACCOUNT_UUID.eq(evidence.canonicalAccountUuid())) + .and( + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq( + evidence.playableStateNamespaceId())) + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name()))) + .limit(1) + .forUpdate() + .fetchOne(CHARACTERS.CHARACTER_UUID); + return existingActor != null; + } + + private boolean insertOwnerResolvedCharacter( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence evidence, + long sourceAccountRowId, + long entityTenantRowId, + UUID characterUuid) { + Long characterRowId = + dsl.insertInto(CHARACTERS) + .set(CHARACTERS.CHARACTER_UUID, characterUuid) + .set(CHARACTERS.ACCOUNT_UUID, evidence.canonicalAccountUuid()) + .set(CHARACTERS.TENANT_UUID, evidence.canonicalTenantUuid()) + .set(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, evidence.playableStateNamespaceId()) + .set(CHARACTERS.PLAYABLE_STATE_SCOPE, evidence.playableStateScope().name()) + .set(CHARACTERS.ACTOR_IDENTITY_STATUS, ActorIdentityStatus.OWNER_RESOLVED.name()) + .set(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON, (String) null) + .set(CHARACTERS.ACCOUNT_ID, sourceAccountRowId) + .set(CHARACTERS.TENANT_ID, entityTenantRowId) + .set(CHARACTERS.PLAYABLE_STATE_KEY, evidence.playableStateNamespaceId().toString()) + .set(CHARACTERS.NAME, request.corePayload().displayName()) + .onConflictDoNothing() + .returningResult(CHARACTERS.ID) + .fetchOne(CHARACTERS.ID); + return characterRowId != null; + } + + private void completeWithActor(UUID assignmentUuid, UUID characterUuid) { + int updated = + dsl.update(ASSIGNMENT_OPERATIONS) + .set(ASSIGNMENT_STATUS, "ASSIGNED") + .set(ASSIGNED_CHARACTER_UUID, characterUuid) + .set(ASSIGNMENT_COMPLETED_AT, OffsetDateTime.now(ZoneOffset.UTC)) + .where(ASSIGNMENT_UUID.eq(assignmentUuid).and(ASSIGNMENT_STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_OPERATION_COMPLETION_FAILED"); + } + } + + private void completeWithoutActor(UUID assignmentUuid, Outcome outcome) { + if (outcome != Outcome.IDEMPOTENCY_CONFLICT) { + throw new IllegalArgumentException("Only terminal no-actor outcomes can omit a character"); + } + int updated = + dsl.update(ASSIGNMENT_OPERATIONS) + .set(ASSIGNMENT_STATUS, outcome.name()) + .set(ASSIGNMENT_COMPLETED_AT, OffsetDateTime.now(ZoneOffset.UTC)) + .where(ASSIGNMENT_UUID.eq(assignmentUuid).and(ASSIGNMENT_STATUS.eq("PENDING"))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_OPERATION_COMPLETION_FAILED"); + } + } + + private void requireStoredAssignedActor( + PreseededActorAssignmentOwnerEvidence evidence, UUID characterUuid) { + Record actor = + dsl.select( + CHARACTERS.CHARACTER_UUID, + CHARACTERS.ACCOUNT_UUID, + CHARACTERS.TENANT_UUID, + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, + CHARACTERS.PLAYABLE_STATE_SCOPE, + CHARACTERS.ACTOR_IDENTITY_STATUS) + .from(CHARACTERS) + .where(CHARACTERS.CHARACTER_UUID.eq(characterUuid)) + .fetchOne(); + if (actor == null + || !evidence.canonicalAccountUuid().equals(actor.get(CHARACTERS.ACCOUNT_UUID)) + || !evidence.canonicalTenantUuid().equals(actor.get(CHARACTERS.TENANT_UUID)) + || !evidence + .playableStateNamespaceId() + .equals(actor.get(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID)) + || !evidence.playableStateScope().name().equals(actor.get(CHARACTERS.PLAYABLE_STATE_SCOPE)) + || !ActorIdentityStatus.OWNER_RESOLVED + .name() + .equals(actor.get(CHARACTERS.ACTOR_IDENTITY_STATUS))) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACTOR_PROVENANCE_MISMATCH"); + } + } + + /** + * Captures an ordered roster only from fresh owner-resolved actor rows, then persists and reads + * back its immutable target-bound snapshot. This lookup never uses legacy numeric actor fields. + */ + @Transactional + public CanonicalGameplayRosterSnapshot captureCanonicalGameplayRosterSnapshot( + CanonicalGameplayRosterReadRequest request, + CanonicalGameplayRosterOwnerEvidence ownerEvidence) { + if (request == null + || ownerEvidence == null + || !request.requestUuid().equals(ownerEvidence.requestUuid()) + || !request.canonicalAccountUuid().equals(ownerEvidence.canonicalAccountUuid()) + || !request.expectedTarget().equals(ownerEvidence.target()) + || ownerEvidence.target().entryPolicy() + != net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy + .PRESEEDED_ONLY) { + throw new IllegalArgumentException("Exact PRESEEDED_ONLY owner evidence is required"); + } + + CanonicalGameplayRosterTarget target = ownerEvidence.target(); + lockCanonicalRosterNamespace(target); + requireEntityTenantRowForRoster(target.tenantUuid()); + + List currentActors = + readCurrentCanonicalRoster(request.canonicalAccountUuid(), target); + String digest = + CanonicalGameplayRosterSnapshotDigest.compute( + request.canonicalAccountUuid(), target, currentActors); + UUID proposedSnapshotUuid = UUID.randomUUID(); + UUID insertedSnapshotUuid = + dsl.insertInto(ROSTER_SNAPSHOTS) + .set(ROSTER_SNAPSHOT_UUID, proposedSnapshotUuid) + .set(ROSTER_SNAPSHOT_DIGEST, digest) + .set(ROSTER_ACCOUNT_UUID, request.canonicalAccountUuid()) + .set(ROSTER_TENANT_UUID, target.tenantUuid()) + .set(ROSTER_REALM_UUID, target.realmUuid()) + .set(ROSTER_WORLD_SLUG, target.worldSlug()) + .set(ROSTER_REALM_SLUG, target.realmSlug()) + .set(ROSTER_GAME_INSTANCE_UUID, target.gameInstanceUuid()) + .set(ROSTER_CATALOG_REVISION, target.catalogRevision()) + .set(ROSTER_CANONICAL_VERSION_UUID, target.canonicalVersionUuid()) + .set(ROSTER_POINTER_VERSION, target.pointerVersion()) + .set(ROSTER_ACTIVE_WORLD_EPOCH, target.activeWorldEpoch()) + .set(ROSTER_PUBLICATION_EVIDENCE_FORMAT, CURRENT_ROSTER_EVIDENCE_FORMAT) + .set(ROSTER_PUBLISHED_POLICY_DIGEST, target.publishedPolicyDigest()) + .set(ROSTER_PUBLISHED_RELEASE_REF, target.publishedReleaseBundleRef()) + .set(ROSTER_POINTER_SNAPSHOT_DIGEST, target.admissionPointerSnapshotDigest()) + .set(ROSTER_OWNER_PROOF_DIGEST, target.publishedOwnerProofDigest()) + .set(ROSTER_NAMESPACE_UUID, target.playableStateNamespaceId()) + .set(ROSTER_PLAYABLE_SCOPE, target.playableStateScope().name()) + .set(ROSTER_ENTRY_POLICY, target.entryPolicy().name()) + .set(ROSTER_COUNT, (short) currentActors.size()) + .set(ROSTER_CONSTRUCTION_STATE, "BUILDING") + .onConflict(ROSTER_SNAPSHOT_DIGEST) + .doNothing() + .returningResult(ROSTER_SNAPSHOT_UUID) + .fetchOne(ROSTER_SNAPSHOT_UUID); + + if (insertedSnapshotUuid != null) { + for (int index = 0; index < currentActors.size(); index++) { + CanonicalGameplayRosterActor actor = currentActors.get(index); + dsl.insertInto(ROSTER_SNAPSHOT_ACTORS) + .set(ROSTER_SNAPSHOT_UUID, insertedSnapshotUuid) + .set(ROSTER_ORDINAL, (short) index) + .set(ROSTER_CHARACTER_UUID, actor.characterUuid()) + .set(ROSTER_DISPLAY_NAME, actor.displayName()) + .set(ROSTER_ACTOR_KIND, "PLAYER") + .execute(); + } + int sealed = + dsl.update(ROSTER_SNAPSHOTS) + .set(ROSTER_CONSTRUCTION_STATE, "SEALED") + .where( + ROSTER_SNAPSHOT_UUID + .eq(insertedSnapshotUuid) + .and(ROSTER_CONSTRUCTION_STATE.eq("BUILDING"))) + .execute(); + if (sealed != 1) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_SEAL_FAILED"); + } + } + + return readBackCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), target, currentActors, digest, null); + } + + /** + * Reads back a previously sealed snapshot only when it still exactly describes the current + * owner-resolved roster. This never captures or creates a snapshot. + */ + @Transactional + public CanonicalGameplayRosterSnapshot readCurrentCanonicalGameplayRosterSnapshot( + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget expectedTarget, + CanonicalGameplayRosterSnapshotReference expectedSnapshot) { + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(expectedTarget, "expectedTarget"); + Objects.requireNonNull(expectedSnapshot, "expectedSnapshot"); + if (expectedTarget.entryPolicy() + != net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy + .PRESEEDED_ONLY) { + throw new IllegalArgumentException("PRESEEDED_ONLY target is required"); + } + + String enrolledScope = + dsl.select(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE) + .from(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .where( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES + .TENANT_UUID + .eq(expectedTarget.tenantUuid()) + .and( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID.eq( + expectedTarget.playableStateNamespaceId()))) + .forShare() + .fetchOne(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE); + if (!expectedTarget.playableStateScope().name().equals(enrolledScope)) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_NAMESPACE_SCOPE_MISMATCH"); + } + + List currentActors = + readCurrentCanonicalRoster(canonicalAccountUuid, expectedTarget); + String currentDigest = + CanonicalGameplayRosterSnapshotDigest.compute( + canonicalAccountUuid, expectedTarget, currentActors); + if (!expectedSnapshot.snapshotDigest().equals(currentDigest)) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_STALE"); + } + return readBackCanonicalGameplayRosterSnapshot( + canonicalAccountUuid, + expectedTarget, + currentActors, + currentDigest, + expectedSnapshot.snapshotUuid()); + } + + private void lockCanonicalRosterNamespace(CanonicalGameplayRosterTarget target) { + dsl.insertInto(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .set(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.TENANT_UUID, target.tenantUuid()) + .set( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID, + target.playableStateNamespaceId()) + .set( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE, + target.playableStateScope().name()) + .onConflict( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.TENANT_UUID, + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID) + .doNothing() + .execute(); + + // Assignment takes FOR UPDATE on this row before actor insertion. + String enrolledScope = + dsl.select(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE) + .from(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES) + .where( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES + .TENANT_UUID + .eq(target.tenantUuid()) + .and( + ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_NAMESPACE_ID.eq( + target.playableStateNamespaceId()))) + .forShare() + .fetchOne(ENTITY_PLAYABLE_STATE_NAMESPACE_SCOPES.PLAYABLE_STATE_SCOPE); + if (!target.playableStateScope().name().equals(enrolledScope)) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_NAMESPACE_SCOPE_MISMATCH"); + } + } + + private List readCurrentCanonicalRoster( + UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target) { + List actors = + dsl.select(CHARACTERS.CHARACTER_UUID, CHARACTERS.NAME) + .from(CHARACTERS) + .where( + CHARACTERS + .ACCOUNT_UUID + .eq(canonicalAccountUuid) + .and(CHARACTERS.TENANT_UUID.eq(target.tenantUuid())) + .and( + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq( + target.playableStateNamespaceId())) + .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(target.playableStateScope().name())) + .and( + CHARACTERS.ACTOR_IDENTITY_STATUS.eq( + ActorIdentityStatus.OWNER_RESOLVED.name())) + .and(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON.isNull())) + .orderBy(CHARACTERS.CHARACTER_UUID.asc()) + .limit(CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE + 1) + .forShare() + .fetch( + row -> + new CanonicalGameplayRosterActor( + row.get(CHARACTERS.CHARACTER_UUID), row.get(CHARACTERS.NAME))); + if (actors.size() > CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_LIMIT_EXCEEDED"); + } + return actors; + } + + private CanonicalGameplayRosterSnapshot readBackCanonicalGameplayRosterSnapshot( + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget expectedTarget, + List expectedActors, + String expectedDigest, + UUID expectedSnapshotUuid) { + Condition snapshotCondition = ROSTER_SNAPSHOT_DIGEST.eq(expectedDigest); + if (expectedSnapshotUuid != null) { + snapshotCondition = snapshotCondition.and(ROSTER_SNAPSHOT_UUID.eq(expectedSnapshotUuid)); + } + Record stored = + dsl.select( + ROSTER_SNAPSHOT_UUID, + ROSTER_SNAPSHOT_DIGEST, + ROSTER_ACCOUNT_UUID, + ROSTER_TENANT_UUID, + ROSTER_REALM_UUID, + ROSTER_WORLD_SLUG, + ROSTER_REALM_SLUG, + ROSTER_GAME_INSTANCE_UUID, + ROSTER_CATALOG_REVISION, + ROSTER_CANONICAL_VERSION_UUID, + ROSTER_POINTER_VERSION, + ROSTER_ACTIVE_WORLD_EPOCH, + ROSTER_PUBLICATION_EVIDENCE_FORMAT, + ROSTER_PUBLISHED_POLICY_DIGEST, + ROSTER_PUBLISHED_RELEASE_REF, + ROSTER_POINTER_SNAPSHOT_DIGEST, + ROSTER_OWNER_PROOF_DIGEST, + ROSTER_NAMESPACE_UUID, + ROSTER_PLAYABLE_SCOPE, + ROSTER_ENTRY_POLICY, + ROSTER_COUNT, + ROSTER_CONSTRUCTION_STATE) + .from(ROSTER_SNAPSHOTS) + .where(snapshotCondition) + .forShare() + .fetchOne(); + if (stored == null + || !"SEALED".equals(stored.get(ROSTER_CONSTRUCTION_STATE)) + || !CURRENT_ROSTER_EVIDENCE_FORMAT.equals(stored.get(ROSTER_PUBLICATION_EVIDENCE_FORMAT))) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_READBACK_UNAVAILABLE"); + } + + CanonicalGameplayRosterTarget storedTarget = + new CanonicalGameplayRosterTarget( + stored.get(ROSTER_TENANT_UUID), + stored.get(ROSTER_REALM_UUID), + stored.get(ROSTER_WORLD_SLUG), + stored.get(ROSTER_REALM_SLUG), + stored.get(ROSTER_GAME_INSTANCE_UUID), + stored.get(ROSTER_CATALOG_REVISION), + stored.get(ROSTER_POINTER_VERSION), + stored.get(ROSTER_ACTIVE_WORLD_EPOCH), + stored.get(ROSTER_CANONICAL_VERSION_UUID), + stored.get(ROSTER_PUBLISHED_POLICY_DIGEST), + stored.get(ROSTER_PUBLISHED_RELEASE_REF), + stored.get(ROSTER_POINTER_SNAPSHOT_DIGEST), + stored.get(ROSTER_OWNER_PROOF_DIGEST), + stored.get(ROSTER_NAMESPACE_UUID), + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.valueOf( + stored.get(ROSTER_PLAYABLE_SCOPE)), + net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy + .valueOf(stored.get(ROSTER_ENTRY_POLICY))); + + List storedActorRows = + dsl.select(ROSTER_ORDINAL, ROSTER_CHARACTER_UUID, ROSTER_DISPLAY_NAME, ROSTER_ACTOR_KIND) + .from(ROSTER_SNAPSHOT_ACTORS) + .where(ROSTER_SNAPSHOT_UUID.eq(stored.get(ROSTER_SNAPSHOT_UUID))) + .orderBy(ROSTER_ORDINAL.asc()) + .fetch(); + List storedActors = new ArrayList<>(storedActorRows.size()); + for (int index = 0; index < storedActorRows.size(); index++) { + Record row = storedActorRows.get(index); + Short ordinal = row.get(ROSTER_ORDINAL); + if (ordinal == null || ordinal != index || !"PLAYER".equals(row.get(ROSTER_ACTOR_KIND))) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_ORDER_INVALID"); + } + storedActors.add( + new CanonicalGameplayRosterActor( + row.get(ROSTER_CHARACTER_UUID), row.get(ROSTER_DISPLAY_NAME))); + } + + Short storedCount = stored.get(ROSTER_COUNT); + UUID storedSnapshotUuid = stored.get(ROSTER_SNAPSHOT_UUID); + if (storedSnapshotUuid == null + || (expectedSnapshotUuid != null && !expectedSnapshotUuid.equals(storedSnapshotUuid)) + || !expectedDigest.equals(stored.get(ROSTER_SNAPSHOT_DIGEST)) + || !canonicalAccountUuid.equals(stored.get(ROSTER_ACCOUNT_UUID)) + || storedCount == null + || storedCount != storedActors.size() + || !expectedTarget.equals(storedTarget) + || !expectedActors.equals(storedActors) + || !expectedDigest.equals( + CanonicalGameplayRosterSnapshotDigest.compute( + canonicalAccountUuid, storedTarget, storedActors))) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_READBACK_MISMATCH"); + } + + if (!expectedActors.equals(readCurrentCanonicalRoster(canonicalAccountUuid, expectedTarget))) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_CHANGED_DURING_READ"); + } + return new CanonicalGameplayRosterSnapshot( + canonicalAccountUuid, storedSnapshotUuid, expectedDigest, storedTarget, storedActors); + } + + private static Field uuidField(String name) { + return DSL.field(DSL.name(name), UUID.class); + } + + private static Field stringField(String name) { + return DSL.field(DSL.name(name), String.class); + } + + private static Field longField(String name) { + return DSL.field(DSL.name(name), Long.class); } public Character save(Character entity) { if (entity.getId() == null) { + UUID characterUuid = UUID.randomUUID(); Long id = dsl.insertInto(CHARACTERS) + .set(CHARACTERS.CHARACTER_UUID, characterUuid) + .set(CHARACTERS.ACTOR_IDENTITY_STATUS, ActorIdentityStatus.QUARANTINED.name()) + .set(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON, "OWNER_PROVENANCE_MISSING") .set(CHARACTERS.TENANT_ID, entity.getTenantId()) .set(CHARACTERS.ACCOUNT_ID, entity.getAccountId()) .set(CHARACTERS.PLAYABLE_STATE_KEY, entity.getPlayableStateKey()) @@ -167,7 +1335,7 @@ public Character save(Character entity) { .set(CHARACTERS.BODY_LAYOUT_KEY, entity.getBodyLayoutKey()) .set(CHARACTERS.LAST_LOGIN_AT, toLocalDateTime(entity.getLastLoginAt())) .set(CHARACTERS.VERSION, entity.getVersion() + 1) - .where(CHARACTERS.ID.eq(entity.getId())) + .where(CHARACTERS.ID.eq(entity.getId()).and(legacyCharacterRow())) .execute(); return findById(entity.getId()).orElseThrow(); } @@ -178,6 +1346,16 @@ private Character toEntity(Record record) { } Character character = new Character(); character.setId(record.get(CHARACTERS.ID)); + character.setActorIdentity( + new net.firedevops.firemud.entitymanagement.entity.ActorIdentity( + record.get(CHARACTERS.CHARACTER_UUID), + record.get(CHARACTERS.ACCOUNT_UUID), + record.get(CHARACTERS.TENANT_UUID), + record.get(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID), + scopeFrom(record.get(CHARACTERS.PLAYABLE_STATE_SCOPE)), + net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus.valueOf( + record.get(CHARACTERS.ACTOR_IDENTITY_STATUS)), + record.get(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON))); character.setTenantId(record.get(CHARACTERS.TENANT_ID)); character.setAccountId(record.get(CHARACTERS.ACCOUNT_ID)); character.setPlayableStateKey(record.get(CHARACTERS.PLAYABLE_STATE_KEY)); @@ -196,6 +1374,12 @@ private Character toEntity(Record record) { return character; } + private net.firedevops.firemud.entitymanagement.v1.PlayableStateScope scopeFrom(String value) { + return value == null + ? null + : net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.valueOf(value); + } + private InventoryEntry toInventoryEntry(Record record, Character character) { InventoryEntry entry = new InventoryEntry(); InventoryKey key = new InventoryKey(); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java index c552c4ebd8..c6662bf066 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/InventoryEntryRepository.java @@ -40,17 +40,19 @@ public long countByCharacterTenantId(Long tenantId) { .from(INVENTORY) .join(CHARACTERS) .on(INVENTORY.CHARACTER_ID.eq(CHARACTERS.ID)) - .where(CHARACTERS.TENANT_ID.eq(tenantId))); + .where( + CHARACTERS.TENANT_ID.eq(tenantId).and(CharacterRepository.legacyCharacterRow()))); } private Page fetchPage(Condition condition, Pageable pageable) { + Condition legacyCondition = condition.and(CharacterRepository.legacyCharacterRow()); long total = dsl.fetchCount( dsl.selectOne() .from(INVENTORY) .join(CHARACTERS) .on(INVENTORY.CHARACTER_ID.eq(CHARACTERS.ID)) - .where(condition)); + .where(legacyCondition)); var content = dsl.select( INVENTORY.CHARACTER_ID, @@ -79,7 +81,7 @@ private Page fetchPage(Condition condition, Pageable pageable) { .on(INVENTORY.CHARACTER_ID.eq(CHARACTERS.ID)) .join(ITEMS) .on(INVENTORY.ITEM_ID.eq(ITEMS.ID)) - .where(condition) + .where(legacyCondition) .orderBy(INVENTORY.ITEM_ID.asc()) .limit( JooqEntityManagementRepositorySupport.limitOrDefault(pageable, Integer.MAX_VALUE)) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterActor.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterActor.java new file mode 100644 index 0000000000..f08f38fe00 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterActor.java @@ -0,0 +1,21 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Persisted primary controllable actor returned by canonical roster discovery. */ +public record CanonicalGameplayRosterActor(UUID characterUuid, String displayName) { + public CanonicalGameplayRosterActor { + Objects.requireNonNull(characterUuid, "characterUuid"); + if (characterUuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("characterUuid must be non-nil"); + } + if (displayName == null + || displayName.isBlank() + || !displayName.equals(displayName.trim()) + || displayName.codePointCount(0, displayName.length()) > 100 + || displayName.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("displayName is incomplete"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterEntryPolicy.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterEntryPolicy.java new file mode 100644 index 0000000000..85e435da02 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterEntryPolicy.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.entitymanagement.service; + +/** Published entry policies represented at the canonical roster boundary. */ +public enum CanonicalGameplayRosterEntryPolicy { + UNSPECIFIED, + PLAYER_CREATED, + PRESEEDED_ONLY, + AUTO_PROVISIONED +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterExecutionContext.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterExecutionContext.java new file mode 100644 index 0000000000..00487bfc3d --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterExecutionContext.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** Parsed unsigned scope carried by the authenticated, allowlisted gameplay workload. */ +public record CanonicalGameplayRosterExecutionContext( + UUID accountUuid, + UUID tenantUuid, + UUID playableStateNamespaceUuid, + UUID gameInstanceUuid, + UUID characterUuid, + UUID sessionUuid, + UUID realmUuid, + UUID requestUuid, + PlayableStateScope playableStateScope) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalGameplayRosterExecutionContext { + requireNonNil(accountUuid, "accountUuid"); + requireNonNil(tenantUuid, "tenantUuid"); + requireNonNil(playableStateNamespaceUuid, "playableStateNamespaceUuid"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + if (characterUuid != null) { + requireNonNil(characterUuid, "characterUuid"); + } + requireNonNil(sessionUuid, "sessionUuid"); + requireNonNil(realmUuid, "realmUuid"); + requireNonNil(requestUuid, "requestUuid"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + if (playableStateScope == PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED + || playableStateScope == PlayableStateScope.UNRECOGNIZED) { + throw new IllegalArgumentException("playableStateScope is required"); + } + } + + public void requireTargetBinding( + UUID expectedRequestUuid, UUID expectedAccountUuid, CanonicalGameplayRosterTarget target) { + Objects.requireNonNull(target, "target"); + if (!requestUuid.equals(expectedRequestUuid) + || !accountUuid.equals(expectedAccountUuid) + || !tenantUuid.equals(target.tenantUuid()) + || !realmUuid.equals(target.realmUuid()) + || !playableStateNamespaceUuid.equals(target.playableStateNamespaceId()) + || !gameInstanceUuid.equals(target.gameInstanceUuid()) + || playableStateScope != target.playableStateScope()) { + throw new IllegalArgumentException("Player execution context does not match exact target"); + } + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidence.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidence.java new file mode 100644 index 0000000000..faa7ce7666 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidence.java @@ -0,0 +1,19 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; + +/** Live owner-resolved target evidence; it is not actor admission or runtime authorization. */ +public record CanonicalGameplayRosterOwnerEvidence( + UUID requestUuid, + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget target, + Instant resolvedAt) { + public CanonicalGameplayRosterOwnerEvidence { + Objects.requireNonNull(requestUuid, "requestUuid"); + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(resolvedAt, "resolvedAt"); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidencePort.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidencePort.java new file mode 100644 index 0000000000..018e78d756 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidencePort.java @@ -0,0 +1,27 @@ +package net.firedevops.firemud.entitymanagement.service; + +/** + * Resolves current Game Session owner evidence independently of the caller's expected target. + * + *

A production implementation must bind the exact Account UUID to canonical tenant, realm, + * active instance, namespace/scope, published PRESEEDED_ONLY policy, release/catalog version, + * admission-pointer evidence, and exact positive {@code pointerVersion} and {@code + * activeWorldEpoch} counters. It must reread those owners for every request; counters cannot be + * inferred from digests, defaults, or numeric identifiers. Cached assertions and caller-selected + * scope are not authority. Roster discovery remains non-admitting. + */ +@FunctionalInterface +public interface CanonicalGameplayRosterOwnerEvidencePort { + CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( + CanonicalGameplayRosterReadRequest request); + + final class OwnerEvidenceUnavailableException extends IllegalStateException { + public OwnerEvidenceUnavailableException() { + super("CANONICAL_GAMEPLAY_ROSTER_OWNER_EVIDENCE_UNAVAILABLE"); + } + + public OwnerEvidenceUnavailableException(Throwable cause) { + super("CANONICAL_GAMEPLAY_ROSTER_OWNER_EVIDENCE_UNAVAILABLE", cause); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterReadRequest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterReadRequest.java new file mode 100644 index 0000000000..155cd2ea03 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterReadRequest.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Exact-account canonical roster lookup with an independently checked target precondition. */ +public record CanonicalGameplayRosterReadRequest( + UUID requestUuid, + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget expectedTarget, + CanonicalGameplayRosterExecutionContext playerExecutionContext) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalGameplayRosterReadRequest { + requireNonNil(requestUuid, "requestUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(expectedTarget, "expectedTarget"); + Objects.requireNonNull(playerExecutionContext, "playerExecutionContext") + .requireTargetBinding(requestUuid, canonicalAccountUuid, expectedTarget); + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReadRequest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReadRequest.java new file mode 100644 index 0000000000..e55145745d --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReadRequest.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Exact selected actor lookup precondition for a non-admitting PRESEEDED assignment read. */ +public record CanonicalGameplayRosterSelectedAssignmentReadRequest( + UUID requestUuid, + UUID canonicalAccountUuid, + UUID selectedCharacterUuid, + CanonicalGameplayRosterTarget expectedTarget, + CanonicalGameplayRosterSnapshotReference expectedSnapshot, + CanonicalGameplayRosterExecutionContext playerExecutionContext) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalGameplayRosterSelectedAssignmentReadRequest { + requireNonNil(requestUuid, "requestUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + requireNonNil(selectedCharacterUuid, "selectedCharacterUuid"); + Objects.requireNonNull(expectedTarget, "expectedTarget"); + Objects.requireNonNull(expectedSnapshot, "expectedSnapshot"); + Objects.requireNonNull(playerExecutionContext, "playerExecutionContext") + .requireTargetBinding(requestUuid, canonicalAccountUuid, expectedTarget); + if (!selectedCharacterUuid.equals(playerExecutionContext.characterUuid())) { + throw new IllegalArgumentException( + "playerExecutionContext.character_id must equal selectedCharacterUuid"); + } + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReference.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReference.java new file mode 100644 index 0000000000..6519e8befb --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReference.java @@ -0,0 +1,35 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Minimal historical assignment reference returned for one exact selected actor and target. */ +public record CanonicalGameplayRosterSelectedAssignmentReference( + UUID requestUuid, + UUID canonicalAccountUuid, + UUID selectedCharacterUuid, + CanonicalGameplayRosterTarget target, + CanonicalGameplayRosterSnapshotReference snapshot, + UUID assignmentUuid, + String intentDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalGameplayRosterSelectedAssignmentReference { + requireNonNil(requestUuid, "requestUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + requireNonNil(selectedCharacterUuid, "selectedCharacterUuid"); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(snapshot, "snapshot"); + requireNonNil(assignmentUuid, "assignmentUuid"); + if (intentDigest == null || !intentDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("intentDigest must be lowercase SHA-256 hex"); + } + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java new file mode 100644 index 0000000000..7ccab4f45b --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Non-admitting read of the exact committed assignment for a selected PRESEEDED actor. */ +public final class CanonicalGameplayRosterSelectedAssignmentService { + private final CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort; + private final CharacterRepository characterRepository; + + public CanonicalGameplayRosterSelectedAssignmentService( + CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort, + CharacterRepository characterRepository) { + this.ownerEvidencePort = Objects.requireNonNull(ownerEvidencePort, "ownerEvidencePort"); + this.characterRepository = Objects.requireNonNull(characterRepository, "characterRepository"); + } + + public CanonicalGameplayRosterSelectedAssignmentReference read( + CanonicalGameplayRosterSelectedAssignmentReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + requireSupportedTarget(request.expectedTarget()); + + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + CanonicalGameplayRosterOwnerEvidence evidence = + ownerEvidencePort.resolveCurrentTarget(ownerRequest); + if (evidence == null) { + throw new CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException(); + } + requireSupportedTarget(evidence.target()); + if (!request.requestUuid().equals(evidence.requestUuid()) + || !request.canonicalAccountUuid().equals(evidence.canonicalAccountUuid()) + || !request.expectedTarget().equals(evidence.target())) { + throw new IllegalStateException("SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + } + + var snapshot = + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot()); + long selectedOccurrences = + snapshot.actors().stream() + .filter(actor -> request.selectedCharacterUuid().equals(actor.characterUuid())) + .count(); + if (selectedOccurrences != 1L) { + throw new IllegalStateException("SELECTED_PRESEEDED_ASSIGNMENT_NOT_IN_EXPECTED_SNAPSHOT"); + } + + PreseededActorAssignmentExpectedTarget expectedAssignmentTarget = + expectedAssignmentTarget(evidence.target()); + PreseededActorAssignmentReceipt receipt = + characterRepository + .readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + expectedAssignmentTarget, + evidence.target().publishedOwnerProofDigest()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PRESEEDED_ASSIGNMENT_UNAVAILABLE")); + + if (!request.canonicalAccountUuid().equals(receipt.canonicalAccountUuid()) + || !request.selectedCharacterUuid().equals(receipt.characterUuid()) + || !request + .expectedTarget() + .publishedOwnerProofDigest() + .equals(receipt.publishedOwnerProofDigest()) + || !expectedAssignmentTarget.equals(receipt.target())) { + throw new IllegalStateException("SELECTED_PRESEEDED_ASSIGNMENT_RECEIPT_MISMATCH"); + } + + return new CanonicalGameplayRosterSelectedAssignmentReference( + request.requestUuid(), + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + request.expectedTarget(), + request.expectedSnapshot(), + receipt.assignmentUuid(), + receipt.intentDigest()); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } + } + + private static void requireSupportedTarget(CanonicalGameplayRosterTarget target) { + if (target.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY) { + throw new UnsupportedOperationException("SELECTED_PRESEEDED_ASSIGNMENT_TARGET_UNSUPPORTED"); + } + } + + private static PreseededActorAssignmentExpectedTarget expectedAssignmentTarget( + CanonicalGameplayRosterTarget target) { + return new PreseededActorAssignmentExpectedTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope()); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java new file mode 100644 index 0000000000..9a05fce123 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Non-admitting PRESEEDED_ONLY roster discovery over persisted, owner-resolved actors. */ +public final class CanonicalGameplayRosterService { + private final CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort; + private final CharacterRepository characterRepository; + + public CanonicalGameplayRosterService( + CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort, + CharacterRepository characterRepository) { + this.ownerEvidencePort = Objects.requireNonNull(ownerEvidencePort, "ownerEvidencePort"); + this.characterRepository = Objects.requireNonNull(characterRepository, "characterRepository"); + } + + public CanonicalGameplayRosterSnapshot read(CanonicalGameplayRosterReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + requirePreseededOnly(request.expectedTarget()); + if (request.playerExecutionContext().characterUuid() != null) { + throw new IllegalArgumentException("Roster discovery must not select a character"); + } + + CanonicalGameplayRosterOwnerEvidence evidence = ownerEvidencePort.resolveCurrentTarget(request); + if (evidence == null) { + throw new CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException(); + } + requirePreseededOnly(evidence.target()); + if (!request.requestUuid().equals(evidence.requestUuid()) + || !request.canonicalAccountUuid().equals(evidence.canonicalAccountUuid()) + || !request.expectedTarget().equals(evidence.target())) { + throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_OWNER_TARGET_MISMATCH"); + } + + return characterRepository.captureCanonicalGameplayRosterSnapshot(request, evidence); + } + + private static void requirePreseededOnly(CanonicalGameplayRosterTarget target) { + if (target.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY) { + throw new UnsupportedOperationException("CANONICAL_GAMEPLAY_ROSTER_ENTRY_POLICY_UNSUPPORTED"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "CANONICAL_GAMEPLAY_ROSTER_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java new file mode 100644 index 0000000000..a5be205c33 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +/** Immutable point-in-time roster snapshot; its identity grants no admission or PLAY authority. */ +public record CanonicalGameplayRosterSnapshot( + UUID canonicalAccountUuid, + UUID snapshotUuid, + String snapshotDigest, + CanonicalGameplayRosterTarget target, + List actors) { + public CanonicalGameplayRosterSnapshot { + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(snapshotUuid, "snapshotUuid"); + Objects.requireNonNull(target, "target"); + actors = List.copyOf(Objects.requireNonNull(actors, "actors")); + if (snapshotDigest == null || !snapshotDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("snapshotDigest must be a lowercase SHA-256 digest"); + } + if (actors.size() > CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE) { + throw new IllegalArgumentException("Roster snapshot exceeds its bounded size"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotDigest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotDigest.java new file mode 100644 index 0000000000..ebe7025be0 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotDigest.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; + +/** Canonical digest of complete owner-resolved target evidence and its ordered persisted roster. */ +public final class CanonicalGameplayRosterSnapshotDigest { + public static final int MAX_ROSTER_SIZE = 100; + private static final String DOMAIN = "firemud.entity.canonical-gameplay-roster.v3"; + + private CanonicalGameplayRosterSnapshotDigest() {} + + public static String compute( + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget target, + List actors) { + if (actors.size() > MAX_ROSTER_SIZE) { + throw new IllegalArgumentException("Roster exceeds the maximum supported size"); + } + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + write(output, DOMAIN); + write(output, canonicalAccountUuid.toString()); + write(output, target.tenantUuid().toString()); + write(output, target.realmUuid().toString()); + write(output, target.worldSlug()); + write(output, target.realmSlug()); + write(output, target.gameInstanceUuid().toString()); + write(output, Long.toString(target.catalogRevision())); + write(output, Long.toString(target.pointerVersion())); + write(output, Long.toString(target.activeWorldEpoch())); + write(output, target.canonicalVersionUuid().toString()); + write(output, target.publishedPolicyDigest()); + write(output, target.publishedReleaseBundleRef()); + write(output, target.admissionPointerSnapshotDigest()); + write(output, target.publishedOwnerProofDigest()); + write(output, target.playableStateNamespaceId().toString()); + write(output, target.playableStateScope().name()); + write(output, target.entryPolicy().name()); + write(output, Integer.toString(actors.size())); + for (CanonicalGameplayRosterActor actor : actors) { + write(output, actor.characterUuid().toString()); + write(output, actor.displayName()); + } + } + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } catch (IOException exception) { + throw new IllegalStateException("Unable to encode canonical roster snapshot", exception); + } + } + + private static void write(DataOutputStream output, String value) throws IOException { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + output.writeInt(encoded.length); + output.write(encoded); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotReference.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotReference.java new file mode 100644 index 0000000000..e8dcea1811 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotReference.java @@ -0,0 +1,19 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Exact immutable identity and digest of one previously returned roster snapshot. */ +public record CanonicalGameplayRosterSnapshotReference(UUID snapshotUuid, String snapshotDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalGameplayRosterSnapshotReference { + Objects.requireNonNull(snapshotUuid, "snapshotUuid"); + if (NIL_UUID.equals(snapshotUuid)) { + throw new IllegalArgumentException("snapshotUuid must be non-nil"); + } + if (snapshotDigest == null || !snapshotDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("snapshotDigest must be lowercase SHA-256 hex"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterTarget.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterTarget.java new file mode 100644 index 0000000000..d4a0961a6b --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterTarget.java @@ -0,0 +1,84 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** Complete caller-echoed target precondition, independently resolved by the trusted owner port. */ +public record CanonicalGameplayRosterTarget( + UUID tenantUuid, + UUID realmUuid, + String worldSlug, + String realmSlug, + UUID gameInstanceUuid, + long catalogRevision, + long pointerVersion, + long activeWorldEpoch, + UUID canonicalVersionUuid, + String publishedPolicyDigest, + String publishedReleaseBundleRef, + String admissionPointerSnapshotDigest, + String publishedOwnerProofDigest, + UUID playableStateNamespaceId, + PlayableStateScope playableStateScope, + CanonicalGameplayRosterEntryPolicy entryPolicy) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String DIGEST_PATTERN = "[0-9a-f]{64}"; + private static final String SLUG_PATTERN = "[a-z0-9][a-z0-9-]{0,63}"; + private static final int MAX_RELEASE_REF_LENGTH = 1024; + + public CanonicalGameplayRosterTarget { + requireNonNil(tenantUuid, "tenantUuid"); + requireNonNil(realmUuid, "realmUuid"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireSlug(worldSlug, "worldSlug"); + requireSlug(realmSlug, "realmSlug"); + requirePositive(catalogRevision, "catalogRevision"); + requirePositive(pointerVersion, "pointerVersion"); + requirePositive(activeWorldEpoch, "activeWorldEpoch"); + requireNonNil(canonicalVersionUuid, "canonicalVersionUuid"); + requireDigest(publishedPolicyDigest, "publishedPolicyDigest"); + requireDigest(admissionPointerSnapshotDigest, "admissionPointerSnapshotDigest"); + requireDigest(publishedOwnerProofDigest, "publishedOwnerProofDigest"); + requireReleaseRef(publishedReleaseBundleRef); + ActorIdentity.requireScope(playableStateScope); + Objects.requireNonNull(entryPolicy, "entryPolicy"); + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } + + private static void requirePositive(long value, String fieldName) { + if (value <= 0L) { + throw new IllegalArgumentException(fieldName + " must be positive"); + } + } + + private static void requireSlug(String value, String fieldName) { + if (value == null || !value.matches(SLUG_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a canonical selector"); + } + } + + private static void requireDigest(String value, String fieldName) { + if (value == null || !value.matches(DIGEST_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireReleaseRef(String value) { + if (value == null + || value.isBlank() + || !value.equals(value.trim()) + || value.length() > MAX_RELEASE_REF_LENGTH + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("publishedReleaseBundleRef is incomplete"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAccountIdentityPort.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAccountIdentityPort.java new file mode 100644 index 0000000000..dcfa117813 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAccountIdentityPort.java @@ -0,0 +1,10 @@ +package net.firedevops.firemud.entitymanagement.service; + +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; + +/** Account-owned canonical UUID provenance read used by the protected actor-assignment path. */ +@FunctionalInterface +public interface PreseededActorAccountIdentityPort { + RuntimeAccountIdentityEvidence resolveRuntimeAccountIdentity( + String canonicalAccountUuid, String assignmentUuid); +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentExpectedTarget.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentExpectedTarget.java new file mode 100644 index 0000000000..ecc3bc6206 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentExpectedTarget.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** + * Caller-echoed complete target used only as an assignment precondition and grant correlation. + * Owner evidence remains the sole source of authority for these values. + */ +public record PreseededActorAssignmentExpectedTarget( + UUID canonicalTenantUuid, + UUID realmUuid, + String worldSlug, + String realmSlug, + String gameInstanceId, + long catalogRevision, + UUID canonicalVersionUuid, + String frozenPolicyDigest, + UUID playableStateNamespaceId, + String publishedReleaseBundleRef, + PlayableStateScope playableStateScope) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String DIGEST_PATTERN = "[0-9a-f]{64}"; + private static final String SLUG_PATTERN = "[a-z0-9][a-z0-9-]{0,63}"; + private static final int MAX_GAME_INSTANCE_ID_LENGTH = 255; + private static final int MAX_RELEASE_REF_LENGTH = 1024; + + public PreseededActorAssignmentExpectedTarget { + requireNonNil(canonicalTenantUuid, "canonicalTenantUuid"); + requireNonNil(realmUuid, "realmUuid"); + requireSlug(worldSlug, "worldSlug"); + requireSlug(realmSlug, "realmSlug"); + requireBoundedOpaqueId(gameInstanceId, "gameInstanceId", MAX_GAME_INSTANCE_ID_LENGTH); + requirePositive(catalogRevision, "catalogRevision"); + requireNonNil(canonicalVersionUuid, "canonicalVersionUuid"); + if (frozenPolicyDigest == null || !frozenPolicyDigest.matches(DIGEST_PATTERN)) { + throw new IllegalArgumentException("frozenPolicyDigest must be a lowercase SHA-256 digest"); + } + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (publishedReleaseBundleRef == null + || publishedReleaseBundleRef.isBlank() + || !publishedReleaseBundleRef.equals(publishedReleaseBundleRef.trim()) + || publishedReleaseBundleRef.length() > MAX_RELEASE_REF_LENGTH + || publishedReleaseBundleRef.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("publishedReleaseBundleRef is incomplete"); + } + ActorIdentity.requireScope(playableStateScope); + } + + /** Compares every caller-echoed target selector with the independent owner-resolved target. */ + public boolean exactlyMatches(PreseededActorAssignmentOwnerEvidence ownerEvidence) { + return ownerEvidence != null + && canonicalTenantUuid.equals(ownerEvidence.canonicalTenantUuid()) + && realmUuid.equals(ownerEvidence.realmUuid()) + && worldSlug.equals(ownerEvidence.worldSlug()) + && realmSlug.equals(ownerEvidence.realmSlug()) + && gameInstanceId.equals(ownerEvidence.gameInstanceId()) + && catalogRevision == ownerEvidence.catalogRevision() + && canonicalVersionUuid.equals(ownerEvidence.canonicalVersionUuid()) + && frozenPolicyDigest.equals(ownerEvidence.frozenPolicyDigest()) + && playableStateNamespaceId.equals(ownerEvidence.playableStateNamespaceId()) + && publishedReleaseBundleRef.equals(ownerEvidence.publishedReleaseBundleRef()) + && playableStateScope == ownerEvidence.playableStateScope(); + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } + + private static void requirePositive(long value, String fieldName) { + if (value <= 0L) { + throw new IllegalArgumentException(fieldName + " must be positive"); + } + } + + private static void requireSlug(String value, String fieldName) { + if (value == null || !value.matches(SLUG_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a canonical realm selector"); + } + } + + private static void requireBoundedOpaqueId(String value, String fieldName, int maxLength) { + if (value == null + || value.isBlank() + || !value.equals(value.trim()) + || value.length() > maxLength + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(fieldName + " is incomplete"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java new file mode 100644 index 0000000000..8b67f21c89 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java @@ -0,0 +1,10 @@ +package net.firedevops.firemud.entitymanagement.service; + +/** Computes the assignment digest from the caller target before any owner reads are performed. */ +final class PreseededActorAssignmentGrantIntentDigest { + private PreseededActorAssignmentGrantIntentDigest() {} + + static String compute(PreseededActorAssignmentRequest request) { + return PreseededActorAssignmentIntentDigest.computeGrant(request); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java new file mode 100644 index 0000000000..1f8c9eb82b --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** Entity-side canonical digest for the immutable assignment intent. */ +final class PreseededActorAssignmentIntentDigest { + private static final String DOMAIN = "firemud.entity.preseeded-actor-assignment.v4"; + + private PreseededActorAssignmentIntentDigest() {} + + static String computeGrant(PreseededActorAssignmentRequest request) { + var target = request.expectedTarget(); + return encode( + request, + target.canonicalTenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceId(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.frozenPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope(), + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY); + } + + static String compute( + PreseededActorAssignmentRequest request, PreseededActorAssignmentOwnerEvidence evidence) { + return encode( + request, + evidence.canonicalTenantUuid(), + evidence.realmUuid(), + evidence.worldSlug(), + evidence.realmSlug(), + evidence.gameInstanceId(), + evidence.catalogRevision(), + evidence.canonicalVersionUuid(), + evidence.frozenPolicyDigest(), + evidence.playableStateNamespaceId(), + evidence.publishedReleaseBundleRef(), + evidence.playableStateScope(), + evidence.entryPolicy()); + } + + private static String encode( + PreseededActorAssignmentRequest request, + UUID canonicalTenantUuid, + UUID realmUuid, + String worldSlug, + String realmSlug, + String gameInstanceId, + long catalogRevision, + UUID canonicalVersionUuid, + String frozenPolicyDigest, + UUID playableStateNamespaceId, + String publishedReleaseBundleRef, + PlayableStateScope playableStateScope, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy entryPolicy) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + write(output, DOMAIN); + write(output, request.assignmentUuid().toString()); + write(output, request.canonicalAccountUuid().toString()); + write(output, request.corePayload().actorKind().name()); + write(output, request.corePayload().displayName()); + write(output, canonicalTenantUuid.toString()); + write(output, realmUuid.toString()); + write(output, worldSlug); + write(output, realmSlug); + write(output, gameInstanceId); + write(output, Long.toString(catalogRevision)); + write(output, canonicalVersionUuid.toString()); + write(output, frozenPolicyDigest); + write(output, playableStateNamespaceId.toString()); + write(output, publishedReleaseBundleRef); + write(output, scopeText(playableStateScope)); + write(output, entryPolicy.name()); + } + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } catch (IOException exception) { + throw new IllegalStateException("Unable to encode assignment intent", exception); + } + } + + private static String scopeText(PlayableStateScope scope) { + return switch (scope) { + case PLAYABLE_STATE_SCOPE_SHARED -> "SHARED"; + case PLAYABLE_STATE_SCOPE_ISOLATED -> "ISOLATED"; + default -> throw new IllegalArgumentException("Unsupported playable-state scope"); + }; + } + + private static void write(DataOutputStream output, String value) throws IOException { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + output.writeInt(encoded.length); + output.write(encoded); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidence.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidence.java new file mode 100644 index 0000000000..12e959d354 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidence.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** + * Point-in-time Account eligibility observation and frozen published target returned by the + * owner-read adapter. {@code CURRENT_AT_REVALIDATION} means Account evidence was revalidated at + * observation time; it is not a held authorization or PLAY grant. Numeric Game Design and Game + * Session row identifiers are intentionally not part of this value. + */ +public record PreseededActorAssignmentOwnerEvidence( + UUID assignmentUuid, + UUID canonicalAccountUuid, + Eligibility eligibility, + Instant eligibilityEvaluatedAt, + long membershipAuthorityGeneration, + String eligibilityEvidenceDigest, + UUID canonicalTenantUuid, + UUID realmUuid, + String worldSlug, + String realmSlug, + String gameInstanceId, + long catalogRevision, + UUID canonicalVersionUuid, + String frozenPolicyDigest, + UUID playableStateNamespaceId, + PlayableStateScope playableStateScope, + PublishedEntryPolicy entryPolicy, + AccountPurpose accountPurpose, + AccountCurrentness accountCurrentness, + String accountAuthoritySnapshotDigest, + String publishedOwnerProofDigest, + String publishedReleaseBundleRef) { + public enum Eligibility { + ELIGIBLE, + INELIGIBLE + } + + public enum PublishedEntryPolicy { + PRESEEDED_ONLY + } + + public enum AccountPurpose { + PRESEEDED_ACTOR_STAGING + } + + public enum AccountCurrentness { + OBSERVED, + /** Point-in-time Account revalidation result; not a held authorization or PLAY grant. */ + CURRENT_AT_REVALIDATION, + CHANGED_SINCE_OBSERVATION + } + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String DIGEST_PATTERN = "[0-9a-f]{64}"; + private static final String SLUG_PATTERN = "[a-z0-9][a-z0-9-]{0,63}"; + private static final int MAX_GAME_INSTANCE_ID_LENGTH = 255; + private static final int MAX_RELEASE_REF_LENGTH = 1024; + + public PreseededActorAssignmentOwnerEvidence { + requireNonNil(assignmentUuid, "assignmentUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(eligibility, "eligibility"); + Objects.requireNonNull(eligibilityEvaluatedAt, "eligibilityEvaluatedAt"); + requirePositive(membershipAuthorityGeneration, "membershipAuthorityGeneration"); + requireDigest(eligibilityEvidenceDigest, "eligibilityEvidenceDigest"); + requireNonNil(canonicalTenantUuid, "canonicalTenantUuid"); + requireNonNil(realmUuid, "realmUuid"); + requireSlug(worldSlug, "worldSlug"); + requireSlug(realmSlug, "realmSlug"); + requireBoundedOpaqueId(gameInstanceId, "gameInstanceId", MAX_GAME_INSTANCE_ID_LENGTH); + requirePositive(catalogRevision, "catalogRevision"); + requireNonNil(canonicalVersionUuid, "canonicalVersionUuid"); + requireDigest(frozenPolicyDigest, "frozenPolicyDigest"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + ActorIdentity.requireScope(playableStateScope); + Objects.requireNonNull(entryPolicy, "entryPolicy"); + Objects.requireNonNull(accountPurpose, "accountPurpose"); + Objects.requireNonNull(accountCurrentness, "accountCurrentness"); + requireDigest(accountAuthoritySnapshotDigest, "accountAuthoritySnapshotDigest"); + requireDigest(publishedOwnerProofDigest, "publishedOwnerProofDigest"); + if (publishedReleaseBundleRef == null + || publishedReleaseBundleRef.isBlank() + || !publishedReleaseBundleRef.equals(publishedReleaseBundleRef.trim()) + || publishedReleaseBundleRef.length() > MAX_RELEASE_REF_LENGTH + || publishedReleaseBundleRef.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("publishedReleaseBundleRef is incomplete"); + } + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } + + private static void requirePositive(long value, String fieldName) { + if (value <= 0L) { + throw new IllegalArgumentException(fieldName + " must be positive"); + } + } + + private static void requireDigest(String value, String fieldName) { + if (value == null || !value.matches(DIGEST_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireSlug(String value, String fieldName) { + if (value == null || !value.matches(SLUG_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a canonical realm selector"); + } + } + + private static void requireBoundedOpaqueId(String value, String fieldName, int maxLength) { + if (value == null + || value.isBlank() + || !value.equals(value.trim()) + || value.length() > maxLength + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(fieldName + " is incomplete"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidencePort.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidencePort.java new file mode 100644 index 0000000000..e808969519 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidencePort.java @@ -0,0 +1,35 @@ +package net.firedevops.firemud.entitymanagement.service; + +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; + +/** + * Game Session owner read for one frozen PRESEEDED_ONLY assignment target, bound to the exact + * Account staging snapshot already read by Entity. + * + *

The production adapter must bind the supplied single Account staging snapshot to the Game + * Session owner-validated canonical tenant, realm, active instance, published release, + * PRESEEDED_ONLY policy/catalog revision, and namespace/scope target. It returns evidence + * independent of the caller's expected-target fields; Entity exact-compares both the target and its + * Account eligibility snapshot before persistence. CURRENT_AT_REVALIDATION is a point-in-time + * Account observation, not a held JOIN authorization, PLAY grant, or admission decision; the + * persisted actor and receipt are non-admitting. Account evidence alone does not satisfy this port. + * The production adapter uses a selector-only Game Session owner read and the one Account staging + * snapshot already read by Entity; it performs no second Account lookup. + */ +public interface PreseededActorAssignmentOwnerEvidencePort { + PreseededActorAssignmentOwnerEvidence resolveCurrentEligibleTarget( + PreseededActorAssignmentRequest request, + RuntimeAccountIdentityEvidence accountIdentityEvidence, + AccountActorStagingEligibilityEvidence stagingEligibilityEvidence); + + final class OwnerEvidenceUnavailableException extends IllegalStateException { + public OwnerEvidenceUnavailableException() { + super("PRESEEDED_ASSIGNMENT_OWNER_EVIDENCE_UNAVAILABLE"); + } + + public OwnerEvidenceUnavailableException(Throwable cause) { + super("PRESEEDED_ASSIGNMENT_OWNER_EVIDENCE_UNAVAILABLE", cause); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceipt.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceipt.java new file mode 100644 index 0000000000..2c29cc5e1a --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceipt.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Immutable readback of a committed, non-admitting PRESEEDED actor assignment and its owner + * snapshots. {@code CURRENT_AT_REVALIDATION} records an Account observation made at that point in + * time; it is neither a held Account authorization nor a PLAY grant, and this receipt does not + * authorize runtime admission or activation. + */ +public record PreseededActorAssignmentReceipt( + UUID assignmentUuid, + UUID canonicalAccountUuid, + UUID characterUuid, + String intentDigest, + PreseededActorAssignmentExpectedTarget target, + PreseededActorCorePayload corePayload, + int accountIdentitySchemaVersion, + String accountIdentityTargetNamespace, + long sourceAccountRowId, + String accountUuidProvenance, + PreseededActorAssignmentOwnerEvidence.Eligibility eligibility, + Instant eligibilityEvaluatedAt, + long membershipAuthorityGeneration, + String eligibilityEvidenceDigest, + String accountAuthoritySnapshotDigest, + PreseededActorAssignmentOwnerEvidence.AccountPurpose accountPurpose, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness accountCurrentness, + String publishedOwnerProofDigest, + String publishedReleaseBundleRef, + String entryPolicy, + String status) { + public PreseededActorAssignmentReceipt { + Objects.requireNonNull(assignmentUuid, "assignmentUuid"); + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(characterUuid, "characterUuid"); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(corePayload, "corePayload"); + Objects.requireNonNull(eligibility, "eligibility"); + Objects.requireNonNull(eligibilityEvaluatedAt, "eligibilityEvaluatedAt"); + Objects.requireNonNull(accountPurpose, "accountPurpose"); + Objects.requireNonNull(accountCurrentness, "accountCurrentness"); + if (intentDigest == null + || !intentDigest.matches("[0-9a-f]{64}") + || accountIdentitySchemaVersion != 1 + || !GrpcPeerIdentity.isValidNamespace(accountIdentityTargetNamespace) + || sourceAccountRowId <= 0L + || !isRecognizedAccountUuidProvenance(accountUuidProvenance) + || eligibility != PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE + || membershipAuthorityGeneration <= 0 + || eligibilityEvidenceDigest == null + || !eligibilityEvidenceDigest.matches("[0-9a-f]{64}") + || accountAuthoritySnapshotDigest == null + || !accountAuthoritySnapshotDigest.matches("[0-9a-f]{64}") + || publishedOwnerProofDigest == null + || !publishedOwnerProofDigest.matches("[0-9a-f]{64}") + || publishedReleaseBundleRef == null + || publishedReleaseBundleRef.isBlank() + || publishedReleaseBundleRef.length() > 1024 + || accountPurpose + != PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING + || accountCurrentness + != PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION + || !"PRESEEDED_ONLY".equals(entryPolicy) + || !target.publishedReleaseBundleRef().equals(publishedReleaseBundleRef) + || !"ASSIGNED".equals(status)) { + throw new IllegalArgumentException("Committed PRESEEDED assignment receipt is incomplete"); + } + PreseededActorAssignmentRequest intent = + new PreseededActorAssignmentRequest( + assignmentUuid, canonicalAccountUuid, corePayload, target); + if (!intentDigest.equals(intent.mutationIntentDigest())) { + throw new IllegalArgumentException("Committed PRESEEDED assignment intent digest is invalid"); + } + } + + /** + * Returns the persisted point-in-time result; it does not assert eligibility is still current. + */ + public boolean eligibleAtRevalidation() { + return eligibility == PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE; + } + + private static boolean isRecognizedAccountUuidProvenance(String provenance) { + return "ACCOUNT_V29_MIGRATION".equals(provenance) + || "ACCOUNT_REPOSITORY_INSERT".equals(provenance) + || "ACCOUNT_DATABASE_INSERT".equals(provenance); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptRequest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptRequest.java new file mode 100644 index 0000000000..01f40fab75 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptRequest.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Exact immutable operation/actor selector for Entity's assignment receipt owner read. */ +public record PreseededActorAssignmentReceiptRequest( + UUID assignmentUuid, + UUID canonicalAccountUuid, + UUID characterUuid, + String intentDigest, + PreseededActorAssignmentExpectedTarget expectedTarget) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public PreseededActorAssignmentReceiptRequest { + requireNonNil(assignmentUuid, "assignmentUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + requireNonNil(characterUuid, "characterUuid"); + if (intentDigest == null || !intentDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("intentDigest must be lowercase SHA-256 hex"); + } + Objects.requireNonNull(expectedTarget, "expectedTarget"); + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java new file mode 100644 index 0000000000..5416948a51 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java @@ -0,0 +1,20 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; + +/** Exposes only repository-verified committed receipts for owner-resolved assigned actors. */ +public final class PreseededActorAssignmentReceiptService { + private final CharacterRepository characterRepository; + + public PreseededActorAssignmentReceiptService(CharacterRepository characterRepository) { + this.characterRepository = Objects.requireNonNull(characterRepository, "characterRepository"); + } + + public Optional read( + PreseededActorAssignmentReceiptRequest request) { + Objects.requireNonNull(request, "request"); + return characterRepository.readPreseededActorAssignmentReceipt(request); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentRequest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentRequest.java new file mode 100644 index 0000000000..547ddff9d1 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentRequest.java @@ -0,0 +1,34 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** Stable operation identity and the exact minimal core payload requested for assignment. */ +public record PreseededActorAssignmentRequest( + UUID assignmentUuid, + UUID canonicalAccountUuid, + PreseededActorCorePayload corePayload, + PreseededActorAssignmentExpectedTarget expectedTarget) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public PreseededActorAssignmentRequest { + requireNonNil(assignmentUuid, "assignmentUuid"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + Objects.requireNonNull(corePayload, "corePayload"); + Objects.requireNonNull(expectedTarget, "expectedTarget"); + } + + /** + * Stable operation digest computed from caller intent, never from transient owner observations. + */ + public String mutationIntentDigest() { + return PreseededActorAssignmentGrantIntentDigest.compute(this); + } + + private static void requireNonNil(UUID value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentResult.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentResult.java new file mode 100644 index 0000000000..9da512e869 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentResult.java @@ -0,0 +1,27 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import java.util.UUID; + +/** + * Persisted outcome for a digest-bound pre-seeded assignment attempt. {@code ASSIGNED} means only + * that Entity persisted the actor; it is not a PLAY grant or runtime-admission result. + */ +public record PreseededActorAssignmentResult( + UUID assignmentUuid, Outcome outcome, UUID characterUuid, String intentDigest) { + public enum Outcome { + ASSIGNED, + IDEMPOTENCY_CONFLICT + } + + public PreseededActorAssignmentResult { + Objects.requireNonNull(assignmentUuid, "assignmentUuid"); + Objects.requireNonNull(outcome, "outcome"); + if (intentDigest == null || !intentDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("intentDigest must be a lowercase SHA-256 digest"); + } + if ((outcome == Outcome.ASSIGNED) != (characterUuid != null)) { + throw new IllegalArgumentException("Only assigned outcomes carry a character UUID"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java new file mode 100644 index 0000000000..fcf99a1624 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; + +/** + * Entity-owned persistence boundary behind a dedicated run-owned bootstrap action. Successful + * assignment persists a non-admitting PRESEEDED actor and receipt; it does not grant PLAY or + * authorize runtime activation. + */ +public final class PreseededActorAssignmentService { + private final RunOwnedPreseededAssignmentAuthority runAuthority; + private final PreseededActorAccountIdentityPort accountIdentityPort; + private final PreseededActorStagingEligibilityPort stagingEligibilityPort; + private final PreseededActorAssignmentOwnerEvidencePort ownerEvidencePort; + private final CharacterRepository characterRepository; + + public PreseededActorAssignmentService( + RunOwnedPreseededAssignmentAuthority runAuthority, + PreseededActorAccountIdentityPort accountIdentityPort, + PreseededActorStagingEligibilityPort stagingEligibilityPort, + PreseededActorAssignmentOwnerEvidencePort ownerEvidencePort, + CharacterRepository characterRepository) { + this.runAuthority = Objects.requireNonNull(runAuthority, "runAuthority"); + this.accountIdentityPort = Objects.requireNonNull(accountIdentityPort, "accountIdentityPort"); + this.stagingEligibilityPort = + Objects.requireNonNull(stagingEligibilityPort, "stagingEligibilityPort"); + this.ownerEvidencePort = Objects.requireNonNull(ownerEvidencePort, "ownerEvidencePort"); + this.characterRepository = Objects.requireNonNull(characterRepository, "characterRepository"); + } + + public PreseededActorAssignmentResult assign(PreseededActorAssignmentRequest request) { + Objects.requireNonNull(request, "request"); + runAuthority.requireAuthorized( + request, RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + + RuntimeAccountIdentityEvidence accountIdentity = + accountIdentityPort.resolveRuntimeAccountIdentity( + request.canonicalAccountUuid().toString(), request.assignmentUuid().toString()); + requireExactAccountProof(request, accountIdentity); + + // One current Account staging snapshot is a non-admitting predicate, not held JOIN authority. + AccountActorStagingEligibilityEvidence stagingEligibility = + stagingEligibilityPort.resolvePreseededActorStagingEligibility( + request.canonicalAccountUuid().toString(), + request.expectedTarget().canonicalTenantUuid().toString(), + request.assignmentUuid().toString()); + requireExactStagingProof(request, accountIdentity, stagingEligibility); + + PreseededActorAssignmentOwnerEvidence target = + ownerEvidencePort.resolveCurrentEligibleTarget( + request, accountIdentity, stagingEligibility); + requireExactEligibleTarget(request, target, stagingEligibility); + + String intentDigest = PreseededActorAssignmentIntentDigest.compute(request, target); + if (!request.mutationIntentDigest().equals(intentDigest)) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_MUTATION_INTENT_DIGEST_MISMATCH"); + } + // Re-read the run-owned capability against the independently resolved target immediately + // before entering the atomic owner repository operation. + runAuthority.requireTargetBoundAuthorized( + request, target, RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + return characterRepository.assignPreseededActor(request, target, accountIdentity, intentDigest); + } + + private static void requireExactAccountProof( + PreseededActorAssignmentRequest request, RuntimeAccountIdentityEvidence proof) { + if (proof == null + || !request.assignmentUuid().equals(proof.requestId()) + || !request.canonicalAccountUuid().equals(proof.canonicalAccountId())) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_IDENTITY_PROOF_MISMATCH"); + } + } + + private static void requireExactStagingProof( + PreseededActorAssignmentRequest request, + RuntimeAccountIdentityEvidence identity, + AccountActorStagingEligibilityEvidence staging) { + if (staging == null + || !request.assignmentUuid().equals(staging.requestId()) + || !request.canonicalAccountUuid().equals(staging.canonicalAccountId()) + || !request.expectedTarget().canonicalTenantUuid().equals(staging.canonicalTenantId()) + || !identity.targetNamespace().equals(staging.targetNamespace()) + || !identity.accountUuidProvenance().equals(staging.accountUuidProvenance())) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_STAGING_EVIDENCE_MISMATCH"); + } + if (staging.purpose() + != AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY + || staging.currentness() + != AccountActorStagingEligibilityEvidence.Currentness.CURRENT_AT_REVALIDATION) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_REVALIDATION_REQUIRED"); + } + if (staging.decision() != AccountActorStagingEligibilityEvidence.Decision.STAGING_ELIGIBLE) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_NOT_CURRENTLY_ELIGIBLE"); + } + } + + private void requireExactEligibleTarget( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence target, + AccountActorStagingEligibilityEvidence staging) { + if (target == null + || !request.assignmentUuid().equals(target.assignmentUuid()) + || !request.canonicalAccountUuid().equals(target.canonicalAccountUuid())) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_OWNER_PROOF_MISMATCH"); + } + if (target.eligibility() != PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_NOT_CURRENTLY_ELIGIBLE"); + } + if (target.accountPurpose() + != PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING + || target.accountCurrentness() + != PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_REVALIDATION_REQUIRED"); + } + if (target.entryPolicy() + != PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_POLICY_MISMATCH"); + } + if (!request.expectedTarget().exactlyMatches(target)) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + } + if (!target.canonicalTenantUuid().equals(staging.canonicalTenantId()) + || target.eligibilityEvaluatedAt() == null + || !target.eligibilityEvaluatedAt().equals(staging.observedAt()) + || target.membershipAuthorityGeneration() != staging.membershipAuthorityGeneration() + || !target.eligibilityEvidenceDigest().equals(staging.eligibilityDecisionDigest()) + || !target.accountAuthoritySnapshotDigest().equals(staging.authoritySnapshotDigest())) { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_STAGING_EVIDENCE_MISMATCH"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayload.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayload.java new file mode 100644 index 0000000000..7d9d10bec5 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayload.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; + +/** Minimal Entity-owned core for a newly assigned player actor; it carries no authored state. */ +public record PreseededActorCorePayload(ActorKind actorKind, String displayName) { + public enum ActorKind { + PLAYER + } + + private static final int MAX_DISPLAY_NAME_CODE_POINTS = 100; + + public PreseededActorCorePayload { + Objects.requireNonNull(actorKind, "actorKind"); + if (actorKind != ActorKind.PLAYER) { + throw new IllegalArgumentException("Only the canonical PLAYER actor kind can be assigned"); + } + if (displayName == null + || displayName.isBlank() + || !displayName.equals(displayName.trim()) + || displayName.codePointCount(0, displayName.length()) > MAX_DISPLAY_NAME_CODE_POINTS + || hasUnpairedSurrogate(displayName) + || displayName.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("displayName must be bounded printable text"); + } + } + + private static boolean hasUnpairedSurrogate(String value) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + return true; + } + index++; + } else if (Character.isLowSurrogate(current)) { + return true; + } + } + return false; + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorStagingEligibilityPort.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorStagingEligibilityPort.java new file mode 100644 index 0000000000..918d919b19 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorStagingEligibilityPort.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.entitymanagement.service; + +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; + +/** + * Account-owned, point-in-time staging predicate read; this is not gameplay admission authority. + */ +@FunctionalInterface +public interface PreseededActorStagingEligibilityPort { + AccountActorStagingEligibilityEvidence resolvePreseededActorStagingEligibility( + String canonicalAccountUuid, String canonicalTenantUuid, String assignmentUuid); +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapter.java new file mode 100644 index 0000000000..853156f038 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapter.java @@ -0,0 +1,111 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.function.Supplier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.boot.ssl.SslBundles; + +/** Reads the separately provisioned run-owned action grant at both protected service boundaries. */ +public final class RunOwnedPreseededActorAssignmentAuthorityAdapter + implements RunOwnedPreseededAssignmentAuthority { + private final String capabilityPath; + private final String runId; + private final String composeProjectName; + private final String trustedGameSessionNamespace; + private final Supplier entityServerTrustRootFingerprint; + + RunOwnedPreseededActorAssignmentAuthorityAdapter( + String capabilityPath, + String runId, + String composeProjectName, + String trustedGameSessionNamespace, + Supplier entityServerTrustRootFingerprint) { + this.capabilityPath = capabilityPath; + this.runId = runId; + this.composeProjectName = composeProjectName; + this.trustedGameSessionNamespace = trustedGameSessionNamespace; + this.entityServerTrustRootFingerprint = entityServerTrustRootFingerprint; + } + + public static RunOwnedPreseededActorAssignmentAuthorityAdapter forActiveServerTrustBundle( + String capabilityPath, + String runId, + String composeProjectName, + String trustedGameSessionNamespace, + SslBundles sslBundles, + String activeServerBundleName, + String entityServerTrustRootPath) { + return new RunOwnedPreseededActorAssignmentAuthorityAdapter( + capabilityPath, + runId, + composeProjectName, + trustedGameSessionNamespace, + () -> + RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( + sslBundles, activeServerBundleName, entityServerTrustRootPath)); + } + + @Override + public void requireAuthorized(PreseededActorAssignmentRequest request, Action dedicatedAction) { + requireExactPeer(); + requireAction(dedicatedAction); + RunOwnedPreseededActorAssignmentCapability capability = readCapability(); + if (!capability.matchesRequest(request)) { + throw denied(); + } + } + + @Override + public void requireTargetBoundAuthorized( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence exactTarget, + Action dedicatedAction) { + requireExactPeer(); + requireAction(dedicatedAction); + RunOwnedPreseededActorAssignmentCapability capability = readCapability(); + if (!capability.matchesOwnerTarget(request, exactTarget)) { + throw denied(); + } + } + + private RunOwnedPreseededActorAssignmentCapability readCapability() { + try { + return RunOwnedPreseededActorAssignmentCapability.load( + capabilityPath, + runId, + composeProjectName, + trustedGameSessionNamespace, + entityServerTrustRootFingerprint.get()); + } catch (RuntimeException exception) { + throw denied(); + } + } + + private void requireExactPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (SessionContext.hasAuthenticatedCallerContext() + || peer == null + || !GrpcPeerIdentity.isValidNamespace(trustedGameSessionNamespace) + || !peer.isInNamespace(trustedGameSessionNamespace) + || !peer.isService("game-session-service") + || !peer.uri() + .equals( + "spiffe://firemud/ns/" + + trustedGameSessionNamespace + + "/sa/game-session-service")) { + throw denied(); + } + } + + private static void requireAction(Action action) { + if (action != Action.PRESEEDED_ACTOR_ASSIGNMENT) { + throw denied(); + } + } + + private static AdminAuthorizationException denied() { + return new AdminAuthorizationException( + "PRESEEDED_ASSIGNMENT_RUN_OWNED_ACTION_GRANT_UNAVAILABLE_OR_MISMATCHED"); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java new file mode 100644 index 0000000000..102bfe2dac --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java @@ -0,0 +1,602 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.channels.Channels; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.core.io.ClassPathResource; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Read-only, exact run-owned grant for one immutable PRESEEDED actor-assignment intent. */ +public final class RunOwnedPreseededActorAssignmentCapability { + static final String CAPABILITY_SCHEMA = "firemud.run-owned-preseeded-actor-assignment.v3"; + static final String ACTION = "PRESEEDED_ACTOR_ASSIGNMENT"; + private static final String GAME_SESSION_SERVICE = "game-session-service"; + private static final String URI_PREFIX = "spiffe://firemud/ns/"; + private static final String URI_SUFFIX = "/sa/game-session-service"; + private static final String DIGEST_PATTERN = "[0-9a-f]{64}"; + private static final String SAFE_ID_PATTERN = "[a-z0-9][a-z0-9-]{0,127}"; + private static final int MAX_CAPABILITY_BYTES = 16 * 1024; + private static final int MAX_TRUST_ROOT_BYTES = 1024 * 1024; + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "runId", + "composeProjectName", + "action", + "trustedGameSessionUriSan", + "trustedGameSessionNamespace", + "assignmentUuid", + "canonicalAccountUuid", + "expectedTarget", + "corePayload", + "intentDigest", + "entityServerTrustRootSha256"); + private static final Set TARGET_FIELDS = + Set.of( + "canonicalTenantUuid", + "realmUuid", + "worldSlug", + "realmSlug", + "gameInstanceId", + "catalogRevision", + "canonicalVersionUuid", + "frozenPolicyDigest", + "playableStateNamespaceUuid", + "publishedReleaseBundleRef", + "playableStateScope"); + private static final Set CORE_FIELDS = Set.of("actorKind", "displayName"); + private static final ObjectMapper STRICT_JSON_MAPPER = + JsonMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build(); + + private final String runId; + private final String composeProjectName; + private final String trustedGameSessionUriSan; + private final String trustedGameSessionNamespace; + private final PreseededActorAssignmentRequest request; + private final String intentDigest; + private final String entityServerTrustRootSha256; + + private RunOwnedPreseededActorAssignmentCapability( + String runId, + String composeProjectName, + String trustedGameSessionUriSan, + String trustedGameSessionNamespace, + PreseededActorAssignmentRequest request, + String intentDigest, + String entityServerTrustRootSha256) { + this.runId = runId; + this.composeProjectName = composeProjectName; + this.trustedGameSessionUriSan = trustedGameSessionUriSan; + this.trustedGameSessionNamespace = trustedGameSessionNamespace; + this.request = request; + this.intentDigest = intentDigest; + this.entityServerTrustRootSha256 = entityServerTrustRootSha256; + } + + static RunOwnedPreseededActorAssignmentCapability load( + String capabilityPath, + String expectedRunId, + String expectedComposeProjectName, + String expectedGameSessionNamespace, + String expectedEntityServerTrustRootSha256) { + requireExpectedRunBinding(expectedRunId, expectedComposeProjectName); + requireGameSessionNamespace(expectedGameSessionNamespace); + if (capabilityPath == null || capabilityPath.isBlank()) { + throw invalidCapability(); + } + String expectedGameSessionUri = URI_PREFIX + expectedGameSessionNamespace + URI_SUFFIX; + byte[] capabilityBytes; + try { + capabilityBytes = readCapability(Path.of(capabilityPath)); + } catch (RuntimeException exception) { + throw invalidCapability(); + } + return parseAndValidate( + capabilityBytes, + expectedRunId, + expectedComposeProjectName, + expectedGameSessionUri, + expectedGameSessionNamespace, + expectedEntityServerTrustRootSha256); + } + + static RunOwnedPreseededActorAssignmentCapability parseAndValidate( + byte[] capabilityBytes, + String expectedRunId, + String expectedComposeProjectName, + String expectedGameSessionUri, + String expectedGameSessionNamespace, + String expectedEntityServerTrustRootSha256) { + requireExpectedRunBinding(expectedRunId, expectedComposeProjectName); + requireGameSessionNamespace(expectedGameSessionNamespace); + if (capabilityBytes == null + || capabilityBytes.length == 0 + || capabilityBytes.length > MAX_CAPABILITY_BYTES + || !isExpectedGameSessionUri(expectedGameSessionUri, expectedGameSessionNamespace) + || expectedEntityServerTrustRootSha256 == null + || !expectedEntityServerTrustRootSha256.matches(DIGEST_PATTERN)) { + throw invalidCapability(); + } + + JsonNode root; + try { + root = STRICT_JSON_MAPPER.readTree(decodeUtf8(capabilityBytes)); + } catch (CharacterCodingException | JacksonException exception) { + throw invalidCapability(); + } + if (root == null || !root.isObject() || !hasExactFields(root, ROOT_FIELDS)) { + throw invalidCapability(); + } + + String schema = requiredText(root, "schema"); + String runId = requiredText(root, "runId"); + String composeProjectName = requiredText(root, "composeProjectName"); + String action = requiredText(root, "action"); + String trustedUri = requiredText(root, "trustedGameSessionUriSan"); + String trustedNamespace = requiredText(root, "trustedGameSessionNamespace"); + UUID assignmentUuid = requiredCanonicalUuid(root, "assignmentUuid"); + UUID accountUuid = requiredCanonicalUuid(root, "canonicalAccountUuid"); + PreseededActorAssignmentExpectedTarget target = parseTarget(root.get("expectedTarget")); + PreseededActorCorePayload corePayload = parseCorePayload(root.get("corePayload")); + String intentDigest = requiredText(root, "intentDigest"); + String entityTrustRoot = requiredText(root, "entityServerTrustRootSha256"); + + if (!CAPABILITY_SCHEMA.equals(schema) + || !runId.equals(expectedRunId) + || !composeProjectName.equals(expectedComposeProjectName) + || !ACTION.equals(action) + || !trustedUri.equals(expectedGameSessionUri) + || !trustedNamespace.equals(expectedGameSessionNamespace) + || !entityTrustRoot.equals(expectedEntityServerTrustRootSha256) + || !intentDigest.matches(DIGEST_PATTERN)) { + throw invalidCapability(); + } + + PreseededActorAssignmentRequest request = + new PreseededActorAssignmentRequest(assignmentUuid, accountUuid, corePayload, target); + if (!intentDigest.equals(PreseededActorAssignmentGrantIntentDigest.compute(request))) { + throw invalidCapability(); + } + return new RunOwnedPreseededActorAssignmentCapability( + runId, + composeProjectName, + trustedUri, + trustedNamespace, + request, + intentDigest, + entityTrustRoot); + } + + private static PreseededActorAssignmentExpectedTarget parseTarget(JsonNode value) { + if (value == null || !value.isObject() || !hasExactFields(value, TARGET_FIELDS)) { + throw invalidCapability(); + } + PlayableStateScope scope; + try { + scope = PlayableStateScope.valueOf(requiredText(value, "playableStateScope")); + } catch (IllegalArgumentException exception) { + throw invalidCapability(); + } + try { + return new PreseededActorAssignmentExpectedTarget( + requiredCanonicalUuid(value, "canonicalTenantUuid"), + requiredCanonicalUuid(value, "realmUuid"), + requiredText(value, "worldSlug"), + requiredText(value, "realmSlug"), + requiredText(value, "gameInstanceId"), + requiredPositiveLong(value, "catalogRevision"), + requiredCanonicalUuid(value, "canonicalVersionUuid"), + requiredText(value, "frozenPolicyDigest"), + requiredCanonicalUuid(value, "playableStateNamespaceUuid"), + requiredText(value, "publishedReleaseBundleRef"), + scope); + } catch (IllegalArgumentException exception) { + throw invalidCapability(); + } + } + + private static PreseededActorCorePayload parseCorePayload(JsonNode value) { + if (value == null || !value.isObject() || !hasExactFields(value, CORE_FIELDS)) { + throw invalidCapability(); + } + if (!"PLAYER".equals(requiredText(value, "actorKind"))) { + throw invalidCapability(); + } + try { + return new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, requiredText(value, "displayName")); + } catch (IllegalArgumentException exception) { + throw invalidCapability(); + } + } + + public static String configuredTrustRootFingerprint(String configuredPath) { + if (configuredPath == null || configuredPath.isBlank()) { + throw invalidCapability(); + } + byte[] pemBytes = readConfiguredTrustRoot(configuredPath); + try { + Collection certificates = + CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(pemBytes)); + return fingerprintValidatedTrustRoot(certificates); + } catch (java.security.cert.CertificateException exception) { + throw invalidCapability(); + } + } + + /** + * Pins the exact CA currently installed in the active Entity gRPC server SSL bundle and rejects + * stale, unsupported, or replaced source configuration before the grant is read. + */ + public static String activeTrustRootFingerprint( + SslBundles sslBundles, String activeServerBundleName, String configuredPath) { + if (sslBundles == null || !"firemud-grpc".equals(activeServerBundleName)) { + throw invalidCapability(); + } + try { + String configuredFingerprint = configuredTrustRootFingerprint(configuredPath); + TrustManager[] trustManagers = + sslBundles.getBundle(activeServerBundleName).getManagers().getTrustManagers(); + String activeFingerprint = activeTrustRootFingerprint(trustManagers, configuredFingerprint); + if (!activeFingerprint.equals(configuredFingerprint)) { + throw invalidCapability(); + } + return activeFingerprint; + } catch (RuntimeException exception) { + throw invalidCapability(); + } + } + + static String activeTrustRootFingerprint( + TrustManager[] trustManagers, String configuredFingerprint) { + if (configuredFingerprint == null || !configuredFingerprint.matches(DIGEST_PATTERN)) { + throw invalidCapability(); + } + if (trustManagers == null + || trustManagers.length != 1 + || !(trustManagers[0] instanceof X509TrustManager trustManager)) { + throw invalidCapability(); + } + X509Certificate[] acceptedIssuers = trustManager.getAcceptedIssuers(); + if (acceptedIssuers == null || acceptedIssuers.length != 1) { + throw invalidCapability(); + } + String activeFingerprint = fingerprintValidatedTrustRoot(Arrays.asList(acceptedIssuers)); + if (!activeFingerprint.equals(configuredFingerprint)) { + throw invalidCapability(); + } + return activeFingerprint; + } + + static String fingerprintValidatedTrustRoot(Collection certificates) { + try { + List roots = + certificates.stream() + .filter(X509Certificate.class::isInstance) + .map(X509Certificate.class::cast) + .toList(); + if (certificates.size() != 1 || roots.size() != 1) { + throw invalidCapability(); + } + X509Certificate root = roots.getFirst(); + root.checkValidity(); + if (root.getBasicConstraints() < 0) { + throw invalidCapability(); + } + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(root.getEncoded())); + } catch (java.security.cert.CertificateException | NoSuchAlgorithmException exception) { + throw invalidCapability(); + } + } + + private static byte[] readConfiguredTrustRoot(String configuredPath) { + try { + if (configuredPath.startsWith("classpath:")) { + ClassPathResource resource = + new ClassPathResource(configuredPath.substring("classpath:".length())); + try (InputStream input = resource.getInputStream()) { + byte[] bytes = input.readNBytes(MAX_TRUST_ROOT_BYTES + 1); + if (bytes.length == 0 || bytes.length > MAX_TRUST_ROOT_BYTES) { + throw invalidCapability(); + } + return bytes; + } + } + Path configuredFile = + configuredPath.startsWith("file:") + ? Path.of(java.net.URI.create(configuredPath)) + : Path.of(configuredPath); + if (!configuredFile.isAbsolute()) { + configuredFile = configuredFile.toAbsolutePath().normalize(); + } + return readBoundedRegularFile(configuredFile, MAX_TRUST_ROOT_BYTES, false); + } catch (IOException | RuntimeException exception) { + throw invalidCapability(); + } + } + + static byte[] readCapability(Path path) { + return readBoundedRegularFile(path, MAX_CAPABILITY_BYTES, true); + } + + private static byte[] readBoundedRegularFile(Path path, int maxBytes, boolean strictCapability) { + if (path == null || !path.isAbsolute()) { + throw invalidCapability(); + } + Path normalized = path.normalize(); + Path parent = normalized.getParent(); + if (!normalized.equals(path) || parent == null) { + throw invalidCapability(); + } + try { + requireNoSymlinkComponents(normalized); + BasicFileAttributes parentBefore = + Files.readAttributes(parent, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + BasicFileAttributes before = + Files.readAttributes(normalized, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + long processUid = processUid(); + long ownerUid = unixUid(normalized); + if (!parentBefore.isDirectory() + || Files.isSymbolicLink(parent) + || !before.isRegularFile() + || Files.isSymbolicLink(normalized) + || before.fileKey() == null + || before.size() <= 0L + || before.size() > maxBytes + || (strictCapability && ownerUid != processUid) + || !safeReadPermissions(normalized, strictCapability) + || (strictCapability && !safeCapabilityDirectory(parent, processUid))) { + throw invalidCapability(); + } + + ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) before.size()); + try (SeekableByteChannel channel = + Files.newByteChannel( + normalized, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)); + InputStream input = Channels.newInputStream(channel)) { + byte[] buffer = new byte[1024]; + int read; + while ((read = input.read(buffer)) >= 0) { + if (read == 0) { + continue; + } + if (bytes.size() + read > maxBytes) { + throw invalidCapability(); + } + bytes.write(buffer, 0, read); + } + } + + BasicFileAttributes after = + Files.readAttributes(normalized, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + BasicFileAttributes parentAfter = + Files.readAttributes(parent, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || Files.isSymbolicLink(normalized) + || after.fileKey() == null + || !before.fileKey().equals(after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime()) + || !sameFileKey(parentBefore.fileKey(), parentAfter.fileKey()) + || ownerUid != unixUid(normalized) + || !safeReadPermissions(normalized, strictCapability) + || (strictCapability && !safeCapabilityDirectory(parent, processUid))) { + throw invalidCapability(); + } + return bytes.toByteArray(); + } catch (IOException | SecurityException exception) { + throw invalidCapability(); + } + } + + private static void requireNoSymlinkComponents(Path path) throws IOException { + for (Path component = path; component != null; component = component.getParent()) { + if (Files.isSymbolicLink(component)) { + throw invalidCapability(); + } + BasicFileAttributes attributes = + Files.readAttributes(component, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (component.equals(path) ? !attributes.isRegularFile() : !attributes.isDirectory()) { + throw invalidCapability(); + } + } + } + + private static boolean safeReadPermissions(Path path, boolean strictCapability) + throws IOException { + Set permissions = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + if (strictCapability) { + return permissions.equals( + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + } + return permissions.contains(PosixFilePermission.OWNER_READ) + && !permissions.contains(PosixFilePermission.OWNER_WRITE) + && !permissions.contains(PosixFilePermission.GROUP_WRITE) + && !permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static boolean safeCapabilityDirectory(Path path, long processUid) throws IOException { + Set permissions = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + Set privateDirectoryPermissions = + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.OWNER_WRITE); + Set readOnlyPrivateDirectoryPermissions = + Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_EXECUTE); + return unixUid(path) == processUid + && (permissions.equals(privateDirectoryPermissions) + || permissions.equals(readOnlyPrivateDirectoryPermissions)); + } + + private static long unixUid(Path path) throws IOException { + Object uid = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (!(uid instanceof Number number)) { + throw new IOException("Owner identity is unavailable"); + } + return number.longValue(); + } + + private static long processUid() throws IOException { + Path processDirectory = Path.of("/proc", Long.toString(ProcessHandle.current().pid())); + return unixUid(processDirectory); + } + + private static boolean sameFileKey(Object before, Object after) { + return before != null && before.equals(after); + } + + private static boolean hasExactFields(JsonNode node, Set expectedFields) { + Set actualFields = new HashSet<>(); + node.properties().forEach(property -> actualFields.add(property.getKey())); + return actualFields.equals(expectedFields); + } + + private static long requiredPositiveLong(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw invalidCapability(); + } + long parsed = value.longValue(); + if (parsed <= 0L) { + throw invalidCapability(); + } + return parsed; + } + + private static UUID requiredCanonicalUuid(JsonNode root, String field) { + String value = requiredText(root, field); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) + || (parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L)) { + throw invalidCapability(); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw invalidCapability(); + } + } + + private static String requiredText(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isString()) { + throw invalidCapability(); + } + String parsed = value.textValue(); + if (parsed.isBlank() + || parsed.length() > 1024 + || !parsed.equals(parsed.trim()) + || parsed.indexOf('\n') >= 0 + || parsed.indexOf('\r') >= 0) { + throw invalidCapability(); + } + return parsed; + } + + private static String decodeUtf8(byte[] bytes) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + } + + private static void requireExpectedRunBinding(String runId, String composeProjectName) { + if (!isSafeId(runId) || !isSafeId(composeProjectName)) { + throw invalidCapability(); + } + } + + private static void requireGameSessionNamespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw invalidCapability(); + } + } + + private static boolean isSafeId(String value) { + return value != null && value.matches(SAFE_ID_PATTERN); + } + + private static boolean isExpectedGameSessionUri(String uri, String namespace) { + return uri != null + && uri.equals(URI_PREFIX + namespace + URI_SUFFIX) + && GrpcPeerIdentity.parseUri(uri) + .filter(identity -> identity.isInNamespace(namespace)) + .filter(identity -> identity.isService(GAME_SESSION_SERVICE)) + .isPresent(); + } + + boolean matchesRequest(PreseededActorAssignmentRequest candidate) { + return candidate != null + && request.assignmentUuid().equals(candidate.assignmentUuid()) + && request.canonicalAccountUuid().equals(candidate.canonicalAccountUuid()) + && request.corePayload().equals(candidate.corePayload()) + && request.expectedTarget().equals(candidate.expectedTarget()) + && intentDigest.equals(PreseededActorAssignmentGrantIntentDigest.compute(candidate)); + } + + boolean matchesOwnerTarget( + PreseededActorAssignmentRequest candidate, + PreseededActorAssignmentOwnerEvidence ownerEvidence) { + return matchesRequest(candidate) + && ownerEvidence != null + && candidate.assignmentUuid().equals(ownerEvidence.assignmentUuid()) + && candidate.canonicalAccountUuid().equals(ownerEvidence.canonicalAccountUuid()) + && candidate.expectedTarget().exactlyMatches(ownerEvidence) + && intentDigest.equals( + PreseededActorAssignmentIntentDigest.compute(candidate, ownerEvidence)); + } + + private static InvalidCapabilityException invalidCapability() { + return new InvalidCapabilityException(); + } + + /** Generic content-free denial marker; callers must not log capability contents. */ + static final class InvalidCapabilityException extends IllegalArgumentException { + private InvalidCapabilityException() { + super("Run-owned PRESEEDED assignment capability is invalid"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededAssignmentAuthority.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededAssignmentAuthority.java new file mode 100644 index 0000000000..b600bd605e --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededAssignmentAuthority.java @@ -0,0 +1,34 @@ +package net.firedevops.firemud.entitymanagement.service; + +/** + * Verifies the exact dedicated run-owned assignment action and target-bound grant. + * + *

The production adapter validates the TLS-authenticated caller and a separately provisioned + * run-owned read-only capability, then binds the dedicated action to the stable assignment UUID, + * Account UUID, caller-echoed expected target, owner-resolved target, and complete core payload. + * The expected target is a correlation/precondition only; it does not authorize its own values. + * Run/project labels, fixture operation IDs, initial-bind authority, and numeric defaults are not + * grants. The adapter remains explicitly disabled by default. + */ +public interface RunOwnedPreseededAssignmentAuthority { + enum Action { + PRESEEDED_ACTOR_ASSIGNMENT + } + + /** + * Authenticates the caller and dedicated action before any owner reads or replay lookup. A + * same-assignment grant mismatch must fail as an intent conflict without disclosing stored data. + * The grant must bind the full request, including its expected target and payload. + */ + void requireAuthorized(PreseededActorAssignmentRequest request, Action dedicatedAction); + + /** + * Rechecks the same authenticated grant against the current complete owner target and payload. A + * mismatch with either the owner target or caller-echoed expected target must fail as an intent + * conflict without returning an actor identity or stored outcome. + */ + void requireTargetBoundAuthorized( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence exactTarget, + Action dedicatedAction); +} diff --git a/services/entity-management-service/src/main/resources/application-prod.yml b/services/entity-management-service/src/main/resources/application-prod.yml index fd6533c6f2..3e6052e2ea 100644 --- a/services/entity-management-service/src/main/resources/application-prod.yml +++ b/services/entity-management-service/src/main/resources/application-prod.yml @@ -7,6 +7,8 @@ spring: schemas: ${SERVICE_SCHEMA:public} locations: classpath:db/migration,classpath:db/migration/saga defaultSchema: ${SERVICE_SCHEMA:public} + postgresql: + transactional-lock: false placeholders: serviceSchema: ${SERVICE_SCHEMA:public} ssl: diff --git a/services/entity-management-service/src/main/resources/application.yml b/services/entity-management-service/src/main/resources/application.yml index d3b5e99641..6770b26bf7 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -7,6 +7,8 @@ spring: locations: classpath:db/migration,classpath:db/migration/saga defaultSchema: ${SERVICE_SCHEMA:public} table: ${SPRING_FLYWAY_TABLE:flyway_schema_history_${SERVICE_SCHEMA:public}} + postgresql: + transactional-lock: false placeholders: serviceSchema: ${SERVICE_SCHEMA:public} ssl: diff --git a/services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql b/services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql new file mode 100644 index 0000000000..2022ded057 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql @@ -0,0 +1,172 @@ +CREATE TABLE entity_playable_state_namespace_scopes ( + tenant_uuid UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(40) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_entity_playable_state_namespace_scopes + PRIMARY KEY (tenant_uuid, playable_state_namespace_id), + CONSTRAINT ck_entity_playable_state_namespace_scope + CHECK (playable_state_scope IN ( + 'PLAYABLE_STATE_SCOPE_SHARED', + 'PLAYABLE_STATE_SCOPE_ISOLATED' + )), + CONSTRAINT ck_entity_playable_state_namespace_tenant_non_nil + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_playable_state_namespace_id_non_nil + CHECK (playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ux_entity_playable_state_namespace_scope + UNIQUE (tenant_uuid, playable_state_namespace_id, playable_state_scope) +); + +/* [jooq ignore start] */ +CREATE FUNCTION reject_entity_playable_state_namespace_scope_change() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF (NEW.tenant_uuid, NEW.playable_state_namespace_id, NEW.playable_state_scope) + IS DISTINCT FROM + (OLD.tenant_uuid, OLD.playable_state_namespace_id, OLD.playable_state_scope) THEN + RAISE EXCEPTION 'entity playable-state namespace identity is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_entity_playable_state_namespace_scopes_immutable + BEFORE UPDATE OF tenant_uuid, playable_state_namespace_id, playable_state_scope + ON entity_playable_state_namespace_scopes + FOR EACH ROW + EXECUTE FUNCTION reject_entity_playable_state_namespace_scope_change(); +/* [jooq ignore stop] */ + +ALTER TABLE characters + ADD COLUMN character_uuid UUID, + ADD COLUMN account_uuid UUID, + ADD COLUMN tenant_uuid UUID, + ADD COLUMN playable_state_namespace_id UUID, + ADD COLUMN playable_state_scope VARCHAR(40), + ADD COLUMN actor_identity_status VARCHAR(24) NOT NULL DEFAULT 'QUARANTINED', + ADD COLUMN actor_identity_quarantine_reason VARCHAR(80) + DEFAULT 'OWNER_PROVENANCE_MISSING'; + +UPDATE characters +SET character_uuid = gen_random_uuid(), + actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING'; + +-- This retained-row backfill updates every existing character in one migration transaction. +-- Quiesce Entity character writes for this migration; it is not an online activation procedure. +ALTER TABLE characters + ALTER COLUMN character_uuid SET DEFAULT gen_random_uuid(); + +/* [jooq ignore start] */ +ALTER TABLE characters + ADD CONSTRAINT ck_characters_character_uuid_nonnull + CHECK (character_uuid IS NOT NULL) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_character_uuid_non_nil + CHECK (character_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_status + CHECK (actor_identity_status IN ('OWNER_RESOLVED', 'QUARANTINED')) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_quarantine_reason + CHECK ( + (actor_identity_status = 'QUARANTINED' + AND actor_identity_quarantine_reason IS NOT NULL + AND length(trim(actor_identity_quarantine_reason)) > 0) + OR (actor_identity_status = 'OWNER_RESOLVED' + AND actor_identity_quarantine_reason IS NULL) + ) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_uuid_non_nil + CHECK ( + (account_uuid IS NULL OR account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (tenant_uuid IS NULL OR tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (playable_state_namespace_id IS NULL OR playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID) + ) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_scope + CHECK ( + playable_state_scope IS NULL + OR playable_state_scope IN ( + 'PLAYABLE_STATE_SCOPE_SHARED', + 'PLAYABLE_STATE_SCOPE_ISOLATED' + ) + ) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_owner_resolved_provenance + CHECK ( + actor_identity_status <> 'OWNER_RESOLVED' + OR ( + account_uuid IS NOT NULL + AND tenant_uuid IS NOT NULL + AND playable_state_namespace_id IS NOT NULL + AND playable_state_scope IS NOT NULL + ) + ) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT fk_characters_owner_resolved_namespace_scope + FOREIGN KEY (tenant_uuid, playable_state_namespace_id, playable_state_scope) + REFERENCES entity_playable_state_namespace_scopes ( + tenant_uuid, + playable_state_namespace_id, + playable_state_scope + ) NOT VALID; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +CREATE VIEW entity_quarantined_actor_item_instances AS +WITH RECURSIVE retained_item_instances(tenant_id, item_instance_id) AS ( + SELECT item_instance.tenant_id, item_instance.id + FROM item_instances item_instance + JOIN characters actor + ON actor.id = item_instance.character_id + AND actor.actor_identity_status = 'QUARANTINED' + + UNION + + SELECT container.tenant_id, container.item_instance_id + FROM container_instances container + JOIN characters actor + ON actor.id = container.character_id + AND actor.actor_identity_status = 'QUARANTINED' + WHERE container.item_instance_id IS NOT NULL + + UNION + + SELECT child_item.tenant_id, child_item.id + FROM retained_item_instances retained_parent + JOIN container_instances parent_container + ON parent_container.tenant_id = retained_parent.tenant_id + AND parent_container.item_instance_id = retained_parent.item_instance_id + JOIN item_instances child_item + ON child_item.tenant_id = parent_container.tenant_id + AND child_item.container_instance_id = parent_container.id +) +SELECT DISTINCT tenant_id, item_instance_id +FROM retained_item_instances; + +CREATE VIEW entity_quarantined_actor_container_instances AS +SELECT DISTINCT container.tenant_id, container.id AS container_instance_id +FROM container_instances container +JOIN characters actor + ON actor.id = container.character_id + AND actor.actor_identity_status = 'QUARANTINED' + +UNION + +SELECT DISTINCT container.tenant_id, container.id AS container_instance_id +FROM container_instances container +JOIN entity_quarantined_actor_item_instances retained_item + ON retained_item.tenant_id = container.tenant_id + AND retained_item.item_instance_id = container.item_instance_id; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V1004__build_actor_identity_indexes_concurrently.sql b/services/entity-management-service/src/main/resources/db/migration/V1004__build_actor_identity_indexes_concurrently.sql new file mode 100644 index 0000000000..da86ec481a --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1004__build_actor_identity_indexes_concurrently.sql @@ -0,0 +1,20 @@ +/* [jooq ignore start] */ +CREATE UNIQUE INDEX CONCURRENTLY ux_characters_character_uuid_idx + ON characters (character_uuid); + +CREATE INDEX CONCURRENTLY idx_characters_owner_resolved_roster + ON characters ( + tenant_uuid, + account_uuid, + playable_state_namespace_id, + playable_state_scope, + character_uuid + ) + WHERE actor_identity_status = 'OWNER_RESOLVED'; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +ALTER TABLE characters + ADD CONSTRAINT ux_characters_character_uuid + UNIQUE USING INDEX ux_characters_character_uuid_idx; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V1004__build_actor_identity_indexes_concurrently.sql.conf b/services/entity-management-service/src/main/resources/db/migration/V1004__build_actor_identity_indexes_concurrently.sql.conf new file mode 100644 index 0000000000..73bd53a146 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1004__build_actor_identity_indexes_concurrently.sql.conf @@ -0,0 +1 @@ +executeInTransaction=false diff --git a/services/entity-management-service/src/main/resources/db/migration/V1005__validate_actor_identity_constraints.sql b/services/entity-management-service/src/main/resources/db/migration/V1005__validate_actor_identity_constraints.sql new file mode 100644 index 0000000000..0a927a7853 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1005__validate_actor_identity_constraints.sql @@ -0,0 +1,34 @@ +/* [jooq ignore start] */ +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_character_uuid_nonnull; +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_character_uuid_non_nil; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_status; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_quarantine_reason; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_uuid_non_nil; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_scope; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_owner_resolved_provenance; + +ALTER TABLE characters + VALIDATE CONSTRAINT fk_characters_owner_resolved_namespace_scope; +/* [jooq ignore stop] */ + +-- Take the stronger lock only after all validation scans have completed. The validated +-- non-null check remains present so PostgreSQL can avoid another full-table scan. +ALTER TABLE characters + ALTER COLUMN character_uuid SET NOT NULL; + +/* [jooq ignore start] */ +ALTER TABLE characters + DROP CONSTRAINT ck_characters_character_uuid_nonnull; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql b/services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql new file mode 100644 index 0000000000..99008404ac --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql @@ -0,0 +1,208 @@ +CREATE TABLE entity_tenant_identities ( + entity_tenant_row_id BIGSERIAL PRIMARY KEY, + canonical_tenant_uuid UUID NOT NULL UNIQUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT ck_entity_tenant_identity_non_nil + CHECK (canonical_tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) +); + +-- Legacy owner-resolved fixture/data rows are not trusted when one account has multiple actors +-- in one durable namespace. Quarantine every member of an ambiguous group; never pick a winner. +/* [jooq ignore start] */ +WITH ambiguous_account_namespaces AS ( + SELECT tenant_uuid, account_uuid, playable_state_namespace_id + FROM characters + WHERE actor_identity_status = 'OWNER_RESOLVED' + GROUP BY tenant_uuid, account_uuid, playable_state_namespace_id + HAVING COUNT(*) > 1 +) +UPDATE characters AS actor +SET actor_identity_status = 'QUARANTINED', + actor_identity_quarantine_reason = 'AMBIGUOUS_ACCOUNT_NAMESPACE' +FROM ambiguous_account_namespaces AS ambiguous +WHERE actor.actor_identity_status = 'OWNER_RESOLVED' + AND actor.tenant_uuid = ambiguous.tenant_uuid + AND actor.account_uuid = ambiguous.account_uuid + AND actor.playable_state_namespace_id = ambiguous.playable_state_namespace_id; + +CREATE UNIQUE INDEX ux_characters_owner_resolved_account_namespace + ON characters (tenant_uuid, account_uuid, playable_state_namespace_id) + WHERE actor_identity_status = 'OWNER_RESOLVED'; +/* [jooq ignore stop] */ + +CREATE TABLE entity_preseeded_actor_assignment_operations ( + assignment_uuid UUID PRIMARY KEY, + intent_digest VARCHAR(64) NOT NULL, + account_uuid UUID NOT NULL, + account_uuid_provenance VARCHAR(32) NOT NULL, + eligibility_evaluated_at TIMESTAMPTZ NOT NULL, + membership_authority_generation BIGINT NOT NULL, + eligibility_evidence_digest VARCHAR(64) NOT NULL, + tenant_uuid UUID NOT NULL, + realm_uuid UUID NOT NULL, + world_slug VARCHAR(64) NOT NULL, + realm_slug VARCHAR(64) NOT NULL, + game_instance_id VARCHAR(255) NOT NULL, + catalog_revision BIGINT NOT NULL, + published_version_id BIGINT NOT NULL, + published_version_number INTEGER NOT NULL, + frozen_policy_digest VARCHAR(64) NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(40) NOT NULL, + entry_policy VARCHAR(32) NOT NULL DEFAULT 'PRESEEDED_ONLY', + actor_kind VARCHAR(16) NOT NULL, + display_name VARCHAR(100) NOT NULL, + status VARCHAR(32) NOT NULL DEFAULT 'PENDING', + character_uuid UUID, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + completed_at TIMESTAMPTZ, + CONSTRAINT ck_entity_preseeded_assignment_uuid_non_nil + CHECK (assignment_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_preseeded_assignment_account_non_nil + CHECK (account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_preseeded_assignment_tenant_non_nil + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_preseeded_assignment_realm_non_nil + CHECK (realm_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_preseeded_assignment_namespace_non_nil + CHECK (playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_preseeded_assignment_digest + CHECK (intent_digest ~ '^[0-9a-f]{64}$' + AND eligibility_evidence_digest ~ '^[0-9a-f]{64}$' + AND frozen_policy_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT ck_entity_preseeded_assignment_account_provenance + CHECK (account_uuid_provenance IN ( + 'ACCOUNT_V29_MIGRATION', + 'ACCOUNT_REPOSITORY_INSERT', + 'ACCOUNT_DATABASE_INSERT' + )), + CONSTRAINT ck_entity_preseeded_assignment_authority_generation + CHECK (membership_authority_generation > 0), + CONSTRAINT ck_entity_preseeded_assignment_scope + CHECK (playable_state_scope IN ( + 'PLAYABLE_STATE_SCOPE_SHARED', + 'PLAYABLE_STATE_SCOPE_ISOLATED' + )), + CONSTRAINT ck_entity_preseeded_assignment_policy + CHECK (entry_policy = 'PRESEEDED_ONLY'), + CONSTRAINT ck_entity_preseeded_assignment_actor_kind + CHECK (actor_kind = 'PLAYER'), + CONSTRAINT ck_entity_preseeded_assignment_status + CHECK (status IN ('PENDING', 'ASSIGNED', 'IDEMPOTENCY_CONFLICT')), + CONSTRAINT ck_entity_preseeded_assignment_result + CHECK ( + (status = 'PENDING' AND character_uuid IS NULL AND completed_at IS NULL) + OR (status = 'ASSIGNED' AND character_uuid IS NOT NULL AND completed_at IS NOT NULL) + OR (status = 'IDEMPOTENCY_CONFLICT' AND character_uuid IS NULL + AND completed_at IS NOT NULL) + ), + CONSTRAINT ck_entity_preseeded_assignment_positive_versions + CHECK (catalog_revision > 0 AND published_version_id > 0 + AND published_version_number > 0), + CONSTRAINT ck_entity_preseeded_assignment_slugs + CHECK (world_slug ~ '^[a-z0-9][a-z0-9-]{0,63}$' + AND realm_slug ~ '^[a-z0-9][a-z0-9-]{0,63}$'), + CONSTRAINT ck_entity_preseeded_assignment_game_instance + CHECK (length(game_instance_id) > 0 AND game_instance_id = btrim(game_instance_id)), + CONSTRAINT ck_entity_preseeded_assignment_display_name + CHECK (length(display_name) > 0 AND display_name = btrim(display_name)), + CONSTRAINT ux_entity_preseeded_assignment_character UNIQUE (character_uuid) +); + +/* [jooq ignore start] */ +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD CONSTRAINT fk_entity_preseeded_assignment_tenant_identity + FOREIGN KEY (tenant_uuid) + REFERENCES entity_tenant_identities (canonical_tenant_uuid) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD CONSTRAINT fk_entity_preseeded_assignment_namespace + FOREIGN KEY (tenant_uuid, playable_state_namespace_id, playable_state_scope) + REFERENCES entity_playable_state_namespace_scopes ( + tenant_uuid, playable_state_namespace_id, playable_state_scope + ) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD CONSTRAINT fk_entity_preseeded_assignment_character + FOREIGN KEY (character_uuid) + REFERENCES characters (character_uuid) + DEFERRABLE INITIALLY DEFERRED; +/* [jooq ignore stop] */ + +CREATE INDEX idx_entity_preseeded_assignment_account_target + ON entity_preseeded_actor_assignment_operations ( + tenant_uuid, playable_state_namespace_id, account_uuid, created_at + ); + +/* [jooq ignore start] */ +CREATE FUNCTION reject_entity_tenant_identity_change() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Entity canonical tenant mapping is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER trg_entity_tenant_identity_immutable + BEFORE UPDATE OR DELETE ON entity_tenant_identities + FOR EACH ROW + EXECUTE FUNCTION reject_entity_tenant_identity_change(); + +CREATE FUNCTION reject_entity_assignment_history_removal() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Entity assignment evidence cannot be removed' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER trg_entity_tenant_identity_no_truncate + BEFORE TRUNCATE ON entity_tenant_identities + FOR EACH STATEMENT + EXECUTE FUNCTION reject_entity_assignment_history_removal(); + +CREATE FUNCTION protect_entity_preseeded_actor_assignment_operation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF (NEW.assignment_uuid, NEW.intent_digest, NEW.account_uuid, NEW.account_uuid_provenance, + NEW.eligibility_evaluated_at, NEW.membership_authority_generation, + NEW.eligibility_evidence_digest, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_id, NEW.catalog_revision, + NEW.published_version_id, NEW.published_version_number, NEW.frozen_policy_digest, + NEW.playable_state_namespace_id, NEW.playable_state_scope, NEW.entry_policy, + NEW.actor_kind, NEW.display_name, NEW.created_at) + IS DISTINCT FROM + (OLD.assignment_uuid, OLD.intent_digest, OLD.account_uuid, OLD.account_uuid_provenance, + OLD.eligibility_evaluated_at, OLD.membership_authority_generation, + OLD.eligibility_evidence_digest, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_id, OLD.catalog_revision, + OLD.published_version_id, OLD.published_version_number, OLD.frozen_policy_digest, + OLD.playable_state_namespace_id, OLD.playable_state_scope, OLD.entry_policy, + OLD.actor_kind, OLD.display_name, OLD.created_at) + OR OLD.status <> 'PENDING' + OR NEW.status NOT IN ('ASSIGNED', 'IDEMPOTENCY_CONFLICT') THEN + RAISE EXCEPTION 'pre-seeded actor assignment intent is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_entity_preseeded_actor_assignment_operation_immutable + BEFORE UPDATE ON entity_preseeded_actor_assignment_operations + FOR EACH ROW + EXECUTE FUNCTION protect_entity_preseeded_actor_assignment_operation(); + +CREATE TRIGGER trg_entity_preseeded_assignment_no_removal + BEFORE DELETE OR TRUNCATE ON entity_preseeded_actor_assignment_operations + FOR EACH STATEMENT + EXECUTE FUNCTION reject_entity_assignment_history_removal(); +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V1007__preseeded_assignment_owner_snapshot.sql b/services/entity-management-service/src/main/resources/db/migration/V1007__preseeded_assignment_owner_snapshot.sql new file mode 100644 index 0000000000..807b3f9698 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1007__preseeded_assignment_owner_snapshot.sql @@ -0,0 +1,63 @@ +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD COLUMN account_identity_schema_version SMALLINT NOT NULL, + ADD COLUMN account_identity_target_namespace VARCHAR(63) NOT NULL, + ADD COLUMN source_account_row_id BIGINT NOT NULL, + ADD COLUMN eligibility VARCHAR(16) NOT NULL, + ADD COLUMN account_authority_snapshot_digest VARCHAR(64) NOT NULL, + ADD COLUMN account_purpose VARCHAR(40) NOT NULL, + ADD COLUMN account_currentness VARCHAR(40) NOT NULL, + ADD COLUMN published_owner_proof_digest VARCHAR(64) NOT NULL, + ADD COLUMN published_release_bundle_ref VARCHAR(1024) NOT NULL; + +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD CONSTRAINT ck_entity_preseeded_assignment_owner_snapshot + CHECK ( + account_identity_schema_version = 1 + AND account_identity_target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND source_account_row_id > 0 + AND eligibility = 'ELIGIBLE' + AND account_authority_snapshot_digest ~ '^[0-9a-f]{64}$' + AND account_purpose = 'PRESEEDED_ACTOR_STAGING' + AND account_currentness = 'CURRENT_AT_REVALIDATION' + AND published_owner_proof_digest ~ '^[0-9a-f]{64}$' + AND length(btrim(published_release_bundle_ref)) > 0 + ); + +/* [jooq ignore start] */ +CREATE OR REPLACE FUNCTION protect_entity_preseeded_actor_assignment_operation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF (NEW.assignment_uuid, NEW.intent_digest, NEW.account_uuid, NEW.account_uuid_provenance, + NEW.account_identity_schema_version, NEW.account_identity_target_namespace, + NEW.source_account_row_id, NEW.eligibility, + NEW.eligibility_evaluated_at, NEW.membership_authority_generation, + NEW.eligibility_evidence_digest, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_id, NEW.catalog_revision, + NEW.published_version_id, NEW.published_version_number, NEW.frozen_policy_digest, + NEW.playable_state_namespace_id, NEW.playable_state_scope, NEW.entry_policy, + NEW.actor_kind, NEW.display_name, NEW.created_at, + NEW.account_authority_snapshot_digest, NEW.account_purpose, NEW.account_currentness, + NEW.published_owner_proof_digest, NEW.published_release_bundle_ref) + IS DISTINCT FROM + (OLD.assignment_uuid, OLD.intent_digest, OLD.account_uuid, OLD.account_uuid_provenance, + OLD.account_identity_schema_version, OLD.account_identity_target_namespace, + OLD.source_account_row_id, OLD.eligibility, + OLD.eligibility_evaluated_at, OLD.membership_authority_generation, + OLD.eligibility_evidence_digest, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_id, OLD.catalog_revision, + OLD.published_version_id, OLD.published_version_number, OLD.frozen_policy_digest, + OLD.playable_state_namespace_id, OLD.playable_state_scope, OLD.entry_policy, + OLD.actor_kind, OLD.display_name, OLD.created_at, + OLD.account_authority_snapshot_digest, OLD.account_purpose, OLD.account_currentness, + OLD.published_owner_proof_digest, OLD.published_release_bundle_ref) + OR OLD.status <> 'PENDING' + OR NEW.status NOT IN ('ASSIGNED', 'IDEMPOTENCY_CONFLICT') THEN + RAISE EXCEPTION 'pre-seeded actor assignment intent is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V1008__canonical_gameplay_roster_snapshots.sql b/services/entity-management-service/src/main/resources/db/migration/V1008__canonical_gameplay_roster_snapshots.sql new file mode 100644 index 0000000000..13dcdddbb9 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1008__canonical_gameplay_roster_snapshots.sql @@ -0,0 +1,221 @@ +CREATE TABLE entity_canonical_gameplay_roster_snapshots ( + snapshot_uuid UUID PRIMARY KEY, + snapshot_digest VARCHAR(64) NOT NULL UNIQUE, + canonical_account_uuid UUID NOT NULL, + tenant_uuid UUID NOT NULL, + realm_uuid UUID NOT NULL, + world_slug VARCHAR(64) NOT NULL, + realm_slug VARCHAR(64) NOT NULL, + game_instance_uuid UUID NOT NULL, + catalog_revision BIGINT NOT NULL, + published_version_id BIGINT NOT NULL, + published_version_number INTEGER NOT NULL, + published_policy_digest VARCHAR(64) NOT NULL, + published_release_bundle_ref VARCHAR(1024) NOT NULL, + admission_pointer_snapshot_digest VARCHAR(64) NOT NULL, + published_owner_proof_digest VARCHAR(64) NOT NULL, + playable_state_namespace_uuid UUID NOT NULL, + playable_state_scope VARCHAR(40) NOT NULL, + entry_policy VARCHAR(32) NOT NULL, + roster_count SMALLINT NOT NULL, + construction_state VARCHAR(8) NOT NULL DEFAULT 'BUILDING', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT ck_entity_canonical_roster_snapshot_uuid_non_nil + CHECK (snapshot_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_account_non_nil + CHECK (canonical_account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_tenant_non_nil + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_realm_non_nil + CHECK (realm_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_instance_non_nil + CHECK (game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_namespace_non_nil + CHECK (playable_state_namespace_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_digests + CHECK (snapshot_digest ~ '^[0-9a-f]{64}$' + AND published_policy_digest ~ '^[0-9a-f]{64}$' + AND admission_pointer_snapshot_digest ~ '^[0-9a-f]{64}$' + AND published_owner_proof_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT ck_entity_canonical_roster_slug + CHECK (world_slug ~ '^[a-z0-9][a-z0-9-]{0,63}$' + AND realm_slug ~ '^[a-z0-9][a-z0-9-]{0,63}$'), + CONSTRAINT ck_entity_canonical_roster_release_ref + CHECK (length(btrim(published_release_bundle_ref)) > 0), + CONSTRAINT ck_entity_canonical_roster_scope + CHECK (playable_state_scope IN ( + 'PLAYABLE_STATE_SCOPE_SHARED', 'PLAYABLE_STATE_SCOPE_ISOLATED')), + CONSTRAINT ck_entity_canonical_roster_policy + CHECK (entry_policy = 'PRESEEDED_ONLY'), + CONSTRAINT ck_entity_canonical_roster_versions + CHECK (catalog_revision > 0 AND published_version_id > 0 + AND published_version_number > 0), + CONSTRAINT ck_entity_canonical_roster_count + CHECK (roster_count BETWEEN 0 AND 100), + CONSTRAINT ck_entity_canonical_roster_construction_state + CHECK (construction_state IN ('BUILDING', 'SEALED')) +); + +CREATE TABLE entity_canonical_gameplay_roster_snapshot_actors ( + snapshot_uuid UUID NOT NULL, + ordinal_position SMALLINT NOT NULL, + character_uuid UUID NOT NULL, + display_name VARCHAR(100) NOT NULL, + actor_kind VARCHAR(16) NOT NULL, + CONSTRAINT pk_entity_canonical_roster_snapshot_actors + PRIMARY KEY (snapshot_uuid, ordinal_position), + CONSTRAINT ux_entity_canonical_roster_snapshot_actor + UNIQUE (snapshot_uuid, character_uuid), + CONSTRAINT ck_entity_canonical_roster_actor_ordinal + CHECK (ordinal_position BETWEEN 0 AND 99), + CONSTRAINT ck_entity_canonical_roster_actor_uuid_non_nil + CHECK (character_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_canonical_roster_actor_name + CHECK (length(btrim(display_name)) > 0), + CONSTRAINT ck_entity_canonical_roster_actor_kind + CHECK (actor_kind = 'PLAYER') +); + +/* [jooq ignore start] */ +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD CONSTRAINT fk_entity_canonical_roster_tenant + FOREIGN KEY (tenant_uuid) + REFERENCES entity_tenant_identities (canonical_tenant_uuid) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD CONSTRAINT fk_entity_canonical_roster_namespace_scope + FOREIGN KEY (tenant_uuid, playable_state_namespace_uuid, playable_state_scope) + REFERENCES entity_playable_state_namespace_scopes ( + tenant_uuid, playable_state_namespace_id, playable_state_scope + ) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE entity_canonical_gameplay_roster_snapshot_actors + ADD CONSTRAINT fk_entity_canonical_roster_snapshot + FOREIGN KEY (snapshot_uuid) + REFERENCES entity_canonical_gameplay_roster_snapshots (snapshot_uuid) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE entity_canonical_gameplay_roster_snapshot_actors + ADD CONSTRAINT fk_entity_canonical_roster_character + FOREIGN KEY (character_uuid) + REFERENCES characters (character_uuid) + DEFERRABLE INITIALLY DEFERRED; + +CREATE FUNCTION protect_entity_canonical_gameplay_roster_snapshot() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + actor_count INTEGER; + minimum_position SMALLINT; + maximum_position SMALLINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'canonical gameplay roster snapshots cannot be removed' + USING ERRCODE = '23514'; + END IF; + + IF OLD.construction_state <> 'BUILDING' + OR NEW.construction_state <> 'SEALED' + OR (NEW.snapshot_uuid, NEW.snapshot_digest, NEW.canonical_account_uuid, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_uuid, + NEW.catalog_revision, NEW.published_version_id, NEW.published_version_number, + NEW.published_policy_digest, NEW.published_release_bundle_ref, + NEW.admission_pointer_snapshot_digest, NEW.published_owner_proof_digest, + NEW.playable_state_namespace_uuid, NEW.playable_state_scope, NEW.entry_policy, + NEW.roster_count, NEW.created_at) + IS DISTINCT FROM + (OLD.snapshot_uuid, OLD.snapshot_digest, OLD.canonical_account_uuid, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_uuid, + OLD.catalog_revision, OLD.published_version_id, OLD.published_version_number, + OLD.published_policy_digest, OLD.published_release_bundle_ref, + OLD.admission_pointer_snapshot_digest, OLD.published_owner_proof_digest, + OLD.playable_state_namespace_uuid, OLD.playable_state_scope, OLD.entry_policy, + OLD.roster_count, OLD.created_at) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is immutable' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*), min(ordinal_position), max(ordinal_position) + INTO actor_count, minimum_position, maximum_position + FROM entity_canonical_gameplay_roster_snapshot_actors + WHERE snapshot_uuid = OLD.snapshot_uuid; + IF actor_count <> OLD.roster_count + OR (actor_count = 0 AND (minimum_position IS NOT NULL OR maximum_position IS NOT NULL)) + OR (actor_count > 0 AND (minimum_position <> 0 OR maximum_position <> actor_count - 1)) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is incomplete' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION protect_entity_canonical_gameplay_roster_snapshot_actor() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + snapshot_row entity_canonical_gameplay_roster_snapshots%ROWTYPE; + actor_row characters%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot actors are immutable' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO snapshot_row + FROM entity_canonical_gameplay_roster_snapshots + WHERE snapshot_uuid = NEW.snapshot_uuid + FOR UPDATE; + IF NOT FOUND OR snapshot_row.construction_state <> 'BUILDING' THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is not being constructed' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO actor_row + FROM characters + WHERE character_uuid = NEW.character_uuid + FOR SHARE; + IF NOT FOUND + OR actor_row.actor_identity_status <> 'OWNER_RESOLVED' + OR actor_row.actor_identity_quarantine_reason IS NOT NULL + OR actor_row.account_uuid <> snapshot_row.canonical_account_uuid + OR actor_row.tenant_uuid <> snapshot_row.tenant_uuid + OR actor_row.playable_state_namespace_id <> snapshot_row.playable_state_namespace_uuid + OR actor_row.playable_state_scope <> snapshot_row.playable_state_scope + OR actor_row.name <> NEW.display_name + OR NEW.actor_kind <> 'PLAYER' THEN + RAISE EXCEPTION 'canonical gameplay roster actor provenance mismatch' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_entity_canonical_roster_snapshot_guard + BEFORE UPDATE OR DELETE ON entity_canonical_gameplay_roster_snapshots + FOR EACH ROW + EXECUTE FUNCTION protect_entity_canonical_gameplay_roster_snapshot(); + +CREATE TRIGGER trg_entity_canonical_roster_snapshot_no_truncate + BEFORE TRUNCATE ON entity_canonical_gameplay_roster_snapshots + FOR EACH STATEMENT + EXECUTE FUNCTION reject_entity_assignment_history_removal(); + +CREATE TRIGGER trg_entity_canonical_roster_actor_guard + BEFORE INSERT OR UPDATE OR DELETE ON entity_canonical_gameplay_roster_snapshot_actors + FOR EACH ROW + EXECUTE FUNCTION protect_entity_canonical_gameplay_roster_snapshot_actor(); + +CREATE TRIGGER trg_entity_canonical_roster_actor_no_truncate + BEFORE TRUNCATE ON entity_canonical_gameplay_roster_snapshot_actors + FOR EACH STATEMENT + EXECUTE FUNCTION reject_entity_assignment_history_removal(); +/* [jooq ignore stop] */ + +CREATE INDEX idx_entity_canonical_roster_account_target + ON entity_canonical_gameplay_roster_snapshots ( + tenant_uuid, canonical_account_uuid, playable_state_namespace_uuid, created_at + ); diff --git a/services/entity-management-service/src/main/resources/db/migration/V1009__canonical_publication_uuid_actor_evidence.sql b/services/entity-management-service/src/main/resources/db/migration/V1009__canonical_publication_uuid_actor_evidence.sql new file mode 100644 index 0000000000..22234a4584 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1009__canonical_publication_uuid_actor_evidence.sql @@ -0,0 +1,162 @@ +-- V5-V7 evidence remains immutable history. Its numeric publication identifiers do not +-- establish a canonical version UUID and must never be upgraded by inference. +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD COLUMN canonical_version_uuid UUID; +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD COLUMN publication_evidence_format VARCHAR(24) NOT NULL DEFAULT 'LEGACY_NUMERIC'; + +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD COLUMN canonical_version_uuid UUID; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD COLUMN publication_evidence_format VARCHAR(24) NOT NULL DEFAULT 'LEGACY_NUMERIC'; + +ALTER TABLE entity_preseeded_actor_assignment_operations + ALTER COLUMN published_version_id DROP NOT NULL; +ALTER TABLE entity_preseeded_actor_assignment_operations + ALTER COLUMN published_version_number DROP NOT NULL; +ALTER TABLE entity_preseeded_actor_assignment_operations + ALTER COLUMN publication_evidence_format SET DEFAULT 'CANONICAL_UUID'; +ALTER TABLE entity_preseeded_actor_assignment_operations + DROP CONSTRAINT ck_entity_preseeded_assignment_positive_versions; +ALTER TABLE entity_preseeded_actor_assignment_operations + ADD CONSTRAINT ck_entity_preseeded_assignment_publication_evidence + CHECK ( + catalog_revision > 0 AND ( + (publication_evidence_format = 'LEGACY_NUMERIC' + AND canonical_version_uuid IS NULL + AND published_version_id > 0 AND published_version_number > 0) + OR (publication_evidence_format = 'CANONICAL_UUID' + AND canonical_version_uuid IS NOT NULL + AND canonical_version_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND published_version_id IS NULL AND published_version_number IS NULL) + ) + ); + +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ALTER COLUMN published_version_id DROP NOT NULL; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ALTER COLUMN published_version_number DROP NOT NULL; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ALTER COLUMN publication_evidence_format SET DEFAULT 'CANONICAL_UUID'; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + DROP CONSTRAINT ck_entity_canonical_roster_versions; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD CONSTRAINT ck_entity_canonical_roster_publication_evidence + CHECK ( + catalog_revision > 0 AND ( + (publication_evidence_format = 'LEGACY_NUMERIC' + AND canonical_version_uuid IS NULL + AND published_version_id > 0 AND published_version_number > 0) + OR (publication_evidence_format = 'CANONICAL_UUID' + AND canonical_version_uuid IS NOT NULL + AND canonical_version_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND published_version_id IS NULL AND published_version_number IS NULL) + ) + ); + +/* [jooq ignore start] */ +CREATE FUNCTION require_current_entity_publication_evidence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.publication_evidence_format <> 'CANONICAL_UUID' THEN + RAISE EXCEPTION 'new Entity publication evidence requires canonical UUID format' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_entity_preseeded_assignment_current_publication + BEFORE INSERT ON entity_preseeded_actor_assignment_operations + FOR EACH ROW + EXECUTE FUNCTION require_current_entity_publication_evidence(); + +CREATE TRIGGER trg_entity_canonical_roster_current_publication + BEFORE INSERT ON entity_canonical_gameplay_roster_snapshots + FOR EACH ROW + EXECUTE FUNCTION require_current_entity_publication_evidence(); + +CREATE OR REPLACE FUNCTION protect_entity_preseeded_actor_assignment_operation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF (NEW.assignment_uuid, NEW.intent_digest, NEW.account_uuid, NEW.account_uuid_provenance, + NEW.account_identity_schema_version, NEW.account_identity_target_namespace, + NEW.source_account_row_id, NEW.eligibility, + NEW.eligibility_evaluated_at, NEW.membership_authority_generation, + NEW.eligibility_evidence_digest, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_id, NEW.catalog_revision, + NEW.published_version_id, NEW.published_version_number, NEW.canonical_version_uuid, + NEW.publication_evidence_format, NEW.frozen_policy_digest, + NEW.playable_state_namespace_id, NEW.playable_state_scope, NEW.entry_policy, + NEW.actor_kind, NEW.display_name, NEW.created_at, + NEW.account_authority_snapshot_digest, NEW.account_purpose, NEW.account_currentness, + NEW.published_owner_proof_digest, NEW.published_release_bundle_ref) + IS DISTINCT FROM + (OLD.assignment_uuid, OLD.intent_digest, OLD.account_uuid, OLD.account_uuid_provenance, + OLD.account_identity_schema_version, OLD.account_identity_target_namespace, + OLD.source_account_row_id, OLD.eligibility, + OLD.eligibility_evaluated_at, OLD.membership_authority_generation, + OLD.eligibility_evidence_digest, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_id, OLD.catalog_revision, + OLD.published_version_id, OLD.published_version_number, OLD.canonical_version_uuid, + OLD.publication_evidence_format, OLD.frozen_policy_digest, + OLD.playable_state_namespace_id, OLD.playable_state_scope, OLD.entry_policy, + OLD.actor_kind, OLD.display_name, OLD.created_at, + OLD.account_authority_snapshot_digest, OLD.account_purpose, OLD.account_currentness, + OLD.published_owner_proof_digest, OLD.published_release_bundle_ref) + OR OLD.status <> 'PENDING' + OR NEW.status NOT IN ('ASSIGNED', 'IDEMPOTENCY_CONFLICT') THEN + RAISE EXCEPTION 'pre-seeded actor assignment intent is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION protect_entity_canonical_gameplay_roster_snapshot() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + actor_count INTEGER; + minimum_position SMALLINT; + maximum_position SMALLINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'canonical gameplay roster snapshots cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF OLD.construction_state <> 'BUILDING' + OR NEW.construction_state <> 'SEALED' + OR (NEW.snapshot_uuid, NEW.snapshot_digest, NEW.canonical_account_uuid, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_uuid, + NEW.catalog_revision, NEW.published_version_id, NEW.published_version_number, + NEW.canonical_version_uuid, NEW.publication_evidence_format, + NEW.published_policy_digest, NEW.published_release_bundle_ref, + NEW.admission_pointer_snapshot_digest, NEW.published_owner_proof_digest, + NEW.playable_state_namespace_uuid, NEW.playable_state_scope, NEW.entry_policy, + NEW.roster_count, NEW.created_at) + IS DISTINCT FROM + (OLD.snapshot_uuid, OLD.snapshot_digest, OLD.canonical_account_uuid, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_uuid, + OLD.catalog_revision, OLD.published_version_id, OLD.published_version_number, + OLD.canonical_version_uuid, OLD.publication_evidence_format, + OLD.published_policy_digest, OLD.published_release_bundle_ref, + OLD.admission_pointer_snapshot_digest, OLD.published_owner_proof_digest, + OLD.playable_state_namespace_uuid, OLD.playable_state_scope, OLD.entry_policy, + OLD.roster_count, OLD.created_at) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is immutable' + USING ERRCODE = '23514'; + END IF; + SELECT count(*), min(ordinal_position), max(ordinal_position) + INTO actor_count, minimum_position, maximum_position + FROM entity_canonical_gameplay_roster_snapshot_actors + WHERE snapshot_uuid = OLD.snapshot_uuid; + IF actor_count <> OLD.roster_count + OR (actor_count = 0 AND (minimum_position IS NOT NULL OR maximum_position IS NOT NULL)) + OR (actor_count > 0 AND (minimum_position <> 0 OR maximum_position <> actor_count - 1)) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is incomplete' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V1010__canonical_roster_owner_counters.sql b/services/entity-management-service/src/main/resources/db/migration/V1010__canonical_roster_owner_counters.sql new file mode 100644 index 0000000000..1fa8a05f38 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1010__canonical_roster_owner_counters.sql @@ -0,0 +1,108 @@ +-- V1-V8 assignment and roster evidence remains immutable history. Older roster rows did not +-- retain these owner counters, so leave them NULL rather than inferring or fabricating values. +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD COLUMN pointer_version BIGINT; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD COLUMN active_world_epoch BIGINT; + +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ALTER COLUMN publication_evidence_format SET DEFAULT 'CANONICAL_UUID_V2'; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + DROP CONSTRAINT ck_entity_canonical_roster_publication_evidence; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD CONSTRAINT ck_entity_canonical_roster_publication_evidence + CHECK ( + catalog_revision > 0 AND ( + (publication_evidence_format = 'LEGACY_NUMERIC' + AND canonical_version_uuid IS NULL + AND published_version_id > 0 AND published_version_number > 0 + AND pointer_version IS NULL AND active_world_epoch IS NULL) + OR (publication_evidence_format = 'CANONICAL_UUID' + AND canonical_version_uuid IS NOT NULL + AND canonical_version_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND published_version_id IS NULL AND published_version_number IS NULL + AND pointer_version IS NULL AND active_world_epoch IS NULL) + OR (publication_evidence_format = 'CANONICAL_UUID_V2' + AND canonical_version_uuid IS NOT NULL + AND canonical_version_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND published_version_id IS NULL AND published_version_number IS NULL + AND pointer_version IS NOT NULL AND pointer_version > 0 + AND active_world_epoch IS NOT NULL AND active_world_epoch > 0) + ) + ); + +/* [jooq ignore start] */ +DROP TRIGGER trg_entity_canonical_roster_current_publication + ON entity_canonical_gameplay_roster_snapshots; + +CREATE FUNCTION require_current_entity_canonical_roster_evidence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.publication_evidence_format <> 'CANONICAL_UUID_V2' + OR NEW.pointer_version IS NULL OR NEW.pointer_version <= 0 + OR NEW.active_world_epoch IS NULL OR NEW.active_world_epoch <= 0 + OR NEW.canonical_version_uuid IS NULL + OR NEW.canonical_version_uuid = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.published_version_id IS NOT NULL + OR NEW.published_version_number IS NOT NULL THEN + RAISE EXCEPTION 'new Entity roster evidence requires exact canonical owner counters' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_entity_canonical_roster_current_publication + BEFORE INSERT ON entity_canonical_gameplay_roster_snapshots + FOR EACH ROW + EXECUTE FUNCTION require_current_entity_canonical_roster_evidence(); + +CREATE OR REPLACE FUNCTION protect_entity_canonical_gameplay_roster_snapshot() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + actor_count INTEGER; + minimum_position SMALLINT; + maximum_position SMALLINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'canonical gameplay roster snapshots cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF OLD.construction_state <> 'BUILDING' + OR NEW.construction_state <> 'SEALED' + OR (NEW.snapshot_uuid, NEW.snapshot_digest, NEW.canonical_account_uuid, NEW.tenant_uuid, + NEW.realm_uuid, NEW.world_slug, NEW.realm_slug, NEW.game_instance_uuid, + NEW.catalog_revision, NEW.published_version_id, NEW.published_version_number, + NEW.canonical_version_uuid, NEW.publication_evidence_format, + NEW.pointer_version, NEW.active_world_epoch, + NEW.published_policy_digest, NEW.published_release_bundle_ref, + NEW.admission_pointer_snapshot_digest, NEW.published_owner_proof_digest, + NEW.playable_state_namespace_uuid, NEW.playable_state_scope, NEW.entry_policy, + NEW.roster_count, NEW.created_at) + IS DISTINCT FROM + (OLD.snapshot_uuid, OLD.snapshot_digest, OLD.canonical_account_uuid, OLD.tenant_uuid, + OLD.realm_uuid, OLD.world_slug, OLD.realm_slug, OLD.game_instance_uuid, + OLD.catalog_revision, OLD.published_version_id, OLD.published_version_number, + OLD.canonical_version_uuid, OLD.publication_evidence_format, + OLD.pointer_version, OLD.active_world_epoch, + OLD.published_policy_digest, OLD.published_release_bundle_ref, + OLD.admission_pointer_snapshot_digest, OLD.published_owner_proof_digest, + OLD.playable_state_namespace_uuid, OLD.playable_state_scope, OLD.entry_policy, + OLD.roster_count, OLD.created_at) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is immutable' + USING ERRCODE = '23514'; + END IF; + SELECT count(*), min(ordinal_position), max(ordinal_position) + INTO actor_count, minimum_position, maximum_position + FROM entity_canonical_gameplay_roster_snapshot_actors + WHERE snapshot_uuid = OLD.snapshot_uuid; + IF actor_count <> OLD.roster_count + OR (actor_count = 0 AND (minimum_position IS NOT NULL OR maximum_position IS NOT NULL)) + OR (actor_count > 0 AND (minimum_position <> 0 OR maximum_position <> actor_count - 1)) THEN + RAISE EXCEPTION 'canonical gameplay roster snapshot is incomplete' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java new file mode 100644 index 0000000000..dfcc4310aa --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java @@ -0,0 +1,479 @@ +package net.firedevops.firemud.entitymanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterExecutionContext; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshot; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = WebEnvironment.NONE, + classes = EntityManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class CanonicalGameplayRosterIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "entity_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private CharacterRepository characterRepository; + @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private PlatformTransactionManager transactionManager; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + private UUID accountUuid; + private UUID tenantUuid; + private UUID realmUuid; + private UUID namespaceUuid; + + @BeforeEach + void createIsolatedTarget() { + accountUuid = UUID.randomUUID(); + tenantUuid = UUID.randomUUID(); + realmUuid = UUID.randomUUID(); + namespaceUuid = UUID.randomUUID(); + } + + @Test + void returnsOnlyFreshOwnerResolvedActorsForExactAccountTenantAndNamespace() { + CanonicalGameplayRosterTarget exactTarget = target(namespaceUuid, UUID.randomUUID()); + UUID selected = createPersistedActor(accountUuid, exactTarget, 41L, "Canonical Actor"); + createPersistedActor(UUID.randomUUID(), exactTarget, 42L, "Different Account Actor"); + CanonicalGameplayRosterTarget otherNamespaceTarget = + target(UUID.randomUUID(), exactTarget.gameInstanceUuid()); + UUID crossNamespace = + createPersistedActor(accountUuid, otherNamespaceTarget, 41L, "Other Namespace Actor"); + jdbcTemplate.update( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key) " + + "VALUES (?, ?, ?, ?)", + 41L, + "Legacy numeric actor", + 71L, + "shared-live"); + + CanonicalGameplayRosterSnapshot roster = readRoster(accountUuid, exactTarget); + CanonicalGameplayRosterSnapshot otherNamespaceRoster = + readRoster(accountUuid, otherNamespaceTarget); + + assertThat(roster.target()).isEqualTo(exactTarget); + assertThat(roster.actors()) + .containsExactly(new CanonicalGameplayRosterActor(selected, "Canonical Actor")); + assertThat(roster.actors()).noneMatch(actor -> actor.characterUuid().equals(crossNamespace)); + assertThat(otherNamespaceRoster.actors()) + .containsExactly(new CanonicalGameplayRosterActor(crossNamespace, "Other Namespace Actor")); + + jdbcTemplate.update( + "UPDATE characters SET actor_identity_status = 'QUARANTINED', " + + "actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING' " + + "WHERE character_uuid = ?", + selected); + CanonicalGameplayRosterSnapshot afterQuarantine = readRoster(accountUuid, exactTarget); + assertThat(afterQuarantine.actors()).isEmpty(); + assertThat(afterQuarantine.snapshotDigest()).isNotEqualTo(roster.snapshotDigest()); + } + + @Test + void snapshotsPersistedPreseededDisplayNameAtOneHundredUnicodeCodePoints() { + CanonicalGameplayRosterTarget exactTarget = target(namespaceUuid, UUID.randomUUID()); + String displayName = "\uD83D\uDE00".repeat(100); + UUID characterUuid = createPersistedActor(accountUuid, exactTarget, 43L, displayName); + + CanonicalGameplayRosterSnapshot roster = readRoster(accountUuid, exactTarget); + + assertThat(roster.actors()) + .containsExactly(new CanonicalGameplayRosterActor(characterUuid, displayName)); + } + + @Test + void reusesExactSnapshotAndChangesIdentityForRosterOrTargetChanges() { + CanonicalGameplayRosterTarget exactTarget = target(namespaceUuid, UUID.randomUUID()); + UUID actor = createPersistedActor(accountUuid, exactTarget, 51L, "Before Rename"); + + CanonicalGameplayRosterSnapshot first = readRoster(accountUuid, exactTarget); + CanonicalGameplayRosterSnapshot identical = readRoster(accountUuid, exactTarget); + assertThat(identical.snapshotUuid()).isEqualTo(first.snapshotUuid()); + assertThat(identical.snapshotDigest()).isEqualTo(first.snapshotDigest()); + CanonicalGameplayRosterSnapshotReference expectedReference = + new CanonicalGameplayRosterSnapshotReference(first.snapshotUuid(), first.snapshotDigest()); + assertThat( + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + accountUuid, exactTarget, expectedReference)) + .isEqualTo(first); + assertThatThrownBy( + () -> + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + accountUuid, + exactTarget, + new CanonicalGameplayRosterSnapshotReference( + UUID.randomUUID(), first.snapshotDigest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_READBACK_UNAVAILABLE"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT canonical_version_uuid FROM entity_canonical_gameplay_roster_snapshots " + + "WHERE snapshot_uuid = ?", + UUID.class, + first.snapshotUuid())) + .isEqualTo(exactTarget.canonicalVersionUuid()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT publication_evidence_format FROM entity_canonical_gameplay_roster_snapshots " + + "WHERE snapshot_uuid = ?", + String.class, + first.snapshotUuid())) + .isEqualTo("CANONICAL_UUID_V2"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT pointer_version FROM entity_canonical_gameplay_roster_snapshots " + + "WHERE snapshot_uuid = ?", + Long.class, + first.snapshotUuid())) + .isEqualTo(exactTarget.pointerVersion()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT active_world_epoch FROM entity_canonical_gameplay_roster_snapshots " + + "WHERE snapshot_uuid = ?", + Long.class, + first.snapshotUuid())) + .isEqualTo(exactTarget.activeWorldEpoch()); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET canonical_version_uuid = ? WHERE snapshot_uuid = ?", + UUID.randomUUID(), + first.snapshotUuid())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET pointer_version = ? WHERE snapshot_uuid = ?", + exactTarget.pointerVersion() + 1, + first.snapshotUuid())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET active_world_epoch = ? WHERE snapshot_uuid = ?", + exactTarget.activeWorldEpoch() + 1, + first.snapshotUuid())) + .isInstanceOf(RuntimeException.class); + + jdbcTemplate.update( + "UPDATE characters SET name = ? WHERE character_uuid = ?", "After Rename", actor); + CanonicalGameplayRosterSnapshot changedRoster = readRoster(accountUuid, exactTarget); + assertThat(changedRoster.snapshotUuid()).isNotEqualTo(first.snapshotUuid()); + assertThat(changedRoster.snapshotDigest()).isNotEqualTo(first.snapshotDigest()); + assertThat(changedRoster.actors()) + .containsExactly(new CanonicalGameplayRosterActor(actor, "After Rename")); + assertThatThrownBy( + () -> + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + accountUuid, exactTarget, expectedReference)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_STALE"); + + CanonicalGameplayRosterTarget changedRuntimeFence = target(namespaceUuid, UUID.randomUUID()); + CanonicalGameplayRosterSnapshot changedTarget = readRoster(accountUuid, changedRuntimeFence); + assertThat(changedTarget.snapshotUuid()).isNotEqualTo(changedRoster.snapshotUuid()); + assertThat(changedTarget.snapshotDigest()).isNotEqualTo(changedRoster.snapshotDigest()); + + CanonicalGameplayRosterTarget changedPointer = + withCounters(exactTarget, exactTarget.pointerVersion() + 1, exactTarget.activeWorldEpoch()); + CanonicalGameplayRosterSnapshot changedPointerSnapshot = + readRoster(accountUuid, changedPointer); + assertThat(changedPointerSnapshot.snapshotUuid()).isNotEqualTo(first.snapshotUuid()); + assertThat(changedPointerSnapshot.snapshotDigest()).isNotEqualTo(first.snapshotDigest()); + assertThat(changedPointerSnapshot.target().pointerVersion()) + .isEqualTo(changedPointer.pointerVersion()); + + CanonicalGameplayRosterTarget changedEpoch = + withCounters(exactTarget, exactTarget.pointerVersion(), exactTarget.activeWorldEpoch() + 1); + CanonicalGameplayRosterSnapshot changedEpochSnapshot = readRoster(accountUuid, changedEpoch); + assertThat(changedEpochSnapshot.snapshotUuid()).isNotEqualTo(first.snapshotUuid()); + assertThat(changedEpochSnapshot.snapshotDigest()).isNotEqualTo(first.snapshotDigest()); + assertThat(changedEpochSnapshot.target().activeWorldEpoch()) + .isEqualTo(changedEpoch.activeWorldEpoch()); + + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET world_slug = 'changed' WHERE snapshot_uuid = ?", + first.snapshotUuid())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshot_actors " + + "SET display_name = 'tampered' " + + "WHERE snapshot_uuid = ? AND character_uuid = ?", + first.snapshotUuid(), + actor)) + .isInstanceOf(RuntimeException.class); + } + + @Test + void concurrentIdenticalReadsReuseOnePersistedSnapshotIdentity() throws Exception { + CanonicalGameplayRosterTarget exactTarget = target(namespaceUuid, UUID.randomUUID()); + createPersistedActor(accountUuid, exactTarget, 61L, "Concurrent Actor"); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + start.await(); + return readRoster(accountUuid, exactTarget); + }); + Future second = + executor.submit( + () -> { + start.await(); + return readRoster(accountUuid, exactTarget); + }); + start.countDown(); + + CanonicalGameplayRosterSnapshot firstResult = first.get(15, TimeUnit.SECONDS); + CanonicalGameplayRosterSnapshot secondResult = second.get(15, TimeUnit.SECONDS); + assertThat(secondResult.snapshotUuid()).isEqualTo(firstResult.snapshotUuid()); + assertThat(secondResult.snapshotDigest()).isEqualTo(firstResult.snapshotDigest()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_canonical_gameplay_roster_snapshots " + + "WHERE snapshot_digest = ?", + Integer.class, + firstResult.snapshotDigest())) + .isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void differentAccountRosterCaptureCanFinishWhileAnotherReaderHoldsItsTransaction() + throws Exception { + CanonicalGameplayRosterTarget exactTarget = target(namespaceUuid, UUID.randomUUID()); + UUID otherAccountUuid = UUID.randomUUID(); + createPersistedActor(accountUuid, exactTarget, 71L, "First Actor"); + createPersistedActor(otherAccountUuid, exactTarget, 72L, "Second Actor"); + CountDownLatch firstRead = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + new TransactionTemplate(transactionManager) + .execute( + ignored -> { + CanonicalGameplayRosterSnapshot snapshot = + readRoster(accountUuid, exactTarget); + firstRead.countDown(); + try { + if (!releaseFirst.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "First roster transaction was not released"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return snapshot; + })); + assertThat(firstRead.await(10, TimeUnit.SECONDS)).isTrue(); + + Future second = + executor.submit(() -> readRoster(otherAccountUuid, exactTarget)); + CanonicalGameplayRosterSnapshot secondResult = second.get(5, TimeUnit.SECONDS); + assertThat(secondResult.actors()).hasSize(1); + releaseFirst.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS).actors()).hasSize(1); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + } + } + + private CanonicalGameplayRosterSnapshot readRoster( + UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target) { + UUID requestUuid = UUID.randomUUID(); + CanonicalGameplayRosterReadRequest request = + new CanonicalGameplayRosterReadRequest( + requestUuid, + canonicalAccountUuid, + target, + new CanonicalGameplayRosterExecutionContext( + canonicalAccountUuid, + target.tenantUuid(), + target.playableStateNamespaceId(), + target.gameInstanceUuid(), + null, + UUID.randomUUID(), + target.realmUuid(), + requestUuid, + target.playableStateScope())); + return characterRepository.captureCanonicalGameplayRosterSnapshot( + request, + new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), canonicalAccountUuid, target, Instant.now())); + } + + private UUID createPersistedActor( + UUID canonicalAccountUuid, + CanonicalGameplayRosterTarget target, + long accountRowId, + String displayName) { + UUID assignmentUuid = UUID.randomUUID(); + PreseededActorAssignmentOwnerEvidence ownerEvidence = + new PreseededActorAssignmentOwnerEvidence( + assignmentUuid, + canonicalAccountUuid, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 4L, + "1".repeat(64), + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "2".repeat(64), + target.publishedOwnerProofDigest(), + target.publishedReleaseBundleRef()); + PreseededActorAssignmentRequest request = + new PreseededActorAssignmentRequest( + assignmentUuid, + canonicalAccountUuid, + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, displayName), + new PreseededActorAssignmentExpectedTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope())); + PreseededActorAssignmentResult result = + characterRepository.assignPreseededActor( + request, + ownerEvidence, + new RuntimeAccountIdentityEvidence( + 1, + "dev", + assignmentUuid, + canonicalAccountUuid, + accountRowId, + "ACCOUNT_DATABASE_INSERT"), + request.mutationIntentDigest()); + assertThat(result.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + return result.characterUuid(); + } + + private CanonicalGameplayRosterTarget target(UUID namespace, UUID instance) { + return new CanonicalGameplayRosterTarget( + tenantUuid, + realmUuid, + "world", + "realm", + instance, + 7L, + 13L, + 19L, + UUID.fromString("21000000-0000-4000-8000-000000000021"), + "3".repeat(64), + "release/roster-test", + "4".repeat(64), + "5".repeat(64), + namespace, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + } + + private CanonicalGameplayRosterTarget withCounters( + CanonicalGameplayRosterTarget target, long pointerVersion, long activeWorldEpoch) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + pointerVersion, + activeWorldEpoch, + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.entryPolicy()); + } +} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java index c93c1e6813..4b1f58ada9 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java @@ -22,7 +22,6 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.data.domain.Pageable; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; -import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; @@ -38,7 +37,7 @@ classes = EntityManagementServiceApplication.class, properties = "spring.grpc.server.port=0") class ContainerInstanceLocationIntegrationTest { - private static final Long TENANT_ID = 1L; + private Long tenantId; private static final String GAME_INSTANCE_ID = "GI-1"; private static final String ROOM_INSTANCE_ID = "R-1"; private static final PlayableStateScope PLAYABLE_STATE_SCOPE = @@ -66,14 +65,12 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private ItemInstanceRepository itemInstanceRepository; @Autowired private ItemStackRepository itemStackRepository; @Autowired private ContainerInstanceRepository containerInstanceRepository; - @Autowired private JdbcTemplate jdbcTemplate; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; @BeforeEach - void cleanDatabase() { - jdbcTemplate.execute( - "TRUNCATE TABLE item_stacks, item_instances, container_instances, items, characters RESTART IDENTITY CASCADE"); + void allocateIsolatedFixtureTenant() { + tenantId = java.util.concurrent.ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); } @Test @@ -84,13 +81,13 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { Item torch = itemRepository.save(ordinaryItem("Torch")); inventoryService.addItem( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, backpack.getId(), 1); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, backpack.getId(), 1); inventoryService.addItem( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, torch.getId(), 1); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, torch.getId(), 1); var inventory = inventoryService.listInventory( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, Pageable.unpaged()); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, Pageable.unpaged()); var backpackEntry = inventory.getContent().stream() .filter(entry -> entry.itemId().equals(backpack.getId())) @@ -103,7 +100,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { .orElseThrow(); containerService.putItemIntoContainer( - TENANT_ID, + tenantId, alice.getId(), backpackEntry.containerInstanceId(), GAME_INSTANCE_ID, @@ -117,7 +114,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { null); inventoryService.dropItemToRoom( - TENANT_ID, + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, @@ -132,7 +129,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { var roomGround = inventoryService.listRoomGroundItems( - TENANT_ID, GAME_INSTANCE_ID, ROOM_INSTANCE_ID, Pageable.unpaged()); + tenantId, GAME_INSTANCE_ID, ROOM_INSTANCE_ID, Pageable.unpaged()); var droppedBackpack = roomGround.getContent().stream() .filter(entry -> entry.itemId().equals(backpack.getId())) @@ -144,7 +141,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { var roomContents = containerService.listContainerContents( - TENANT_ID, + tenantId, alice.getId(), backpackEntry.containerInstanceId(), GAME_INSTANCE_ID, @@ -156,7 +153,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { .satisfies(item -> assertThat(item.itemName()).isEqualTo("Torch")); inventoryService.pickupItemFromRoom( - TENANT_ID, + tenantId, bob.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, @@ -171,7 +168,7 @@ void nonEmptyContainerSurvivesDropAndPickupBetweenHolders() { var bobContents = containerService.listContainerContents( - TENANT_ID, + tenantId, bob.getId(), backpackEntry.containerInstanceId(), GAME_INSTANCE_ID, @@ -191,15 +188,15 @@ void identicalContainersKeepDistinctContentsByContainerInstance() { Item ration = itemRepository.save(ordinaryItem("Ration")); inventoryService.addItem( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, backpack.getId(), 2); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, backpack.getId(), 2); inventoryService.addItem( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, torch.getId(), 1); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, torch.getId(), 1); inventoryService.addItem( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, ration.getId(), 1); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, ration.getId(), 1); var inventory = inventoryService.listInventory( - TENANT_ID, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, Pageable.unpaged()); + tenantId, alice.getId(), GAME_INSTANCE_ID, PLAYABLE_STATE_SCOPE, Pageable.unpaged()); var backpacks = inventory.getContent().stream() .filter(entry -> entry.itemId().equals(backpack.getId())) @@ -220,7 +217,7 @@ void identicalContainersKeepDistinctContentsByContainerInstance() { .isNotEqualTo(backpacks.get(1).containerInstanceId()); containerService.putItemIntoContainer( - TENANT_ID, + tenantId, alice.getId(), backpacks.get(0).containerInstanceId(), GAME_INSTANCE_ID, @@ -233,7 +230,7 @@ void identicalContainersKeepDistinctContentsByContainerInstance() { null, null); containerService.putItemIntoContainer( - TENANT_ID, + tenantId, alice.getId(), backpacks.get(1).containerInstanceId(), GAME_INSTANCE_ID, @@ -248,7 +245,7 @@ void identicalContainersKeepDistinctContentsByContainerInstance() { var firstContents = containerService.listContainerContents( - TENANT_ID, + tenantId, alice.getId(), backpacks.get(0).containerInstanceId(), GAME_INSTANCE_ID, @@ -257,7 +254,7 @@ void identicalContainersKeepDistinctContentsByContainerInstance() { Pageable.unpaged()); var secondContents = containerService.listContainerContents( - TENANT_ID, + tenantId, alice.getId(), backpacks.get(1).containerInstanceId(), GAME_INSTANCE_ID, @@ -275,7 +272,7 @@ void identicalContainersKeepDistinctContentsByContainerInstance() { private Character character(String name) { Character character = new Character(); - character.setTenantId(TENANT_ID); + character.setTenantId(tenantId); character.setAccountId((long) name.length() + 1L); character.setPlayableStateKey("shared-live"); character.setName(name); @@ -299,7 +296,7 @@ private Item containerItem(String name) { private Item ordinaryItem(String name) { Item item = new Item(); - item.setTenantId(TENANT_ID); + item.setTenantId(tenantId); item.setVersionId(1L); item.setName(name); item.setDescription(name + " desc"); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java new file mode 100644 index 0000000000..5726f1b3a9 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -0,0 +1,1636 @@ +package net.firedevops.firemud.entitymanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; +import net.firedevops.firemud.entitymanagement.entity.ActorResourceState; +import net.firedevops.firemud.entitymanagement.entity.Character; +import net.firedevops.firemud.entitymanagement.entity.CharacterFriend; +import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; +import net.firedevops.firemud.entitymanagement.repository.ActorActiveConditionRepository; +import net.firedevops.firemud.entitymanagement.repository.ActorResourceStateRepository; +import net.firedevops.firemud.entitymanagement.repository.CharacterEquipmentRepository; +import net.firedevops.firemud.entitymanagement.repository.CharacterFriendRepository; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.repository.InventoryEntryRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterExecutionContext; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceipt; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceiptRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.dao.DataAccessException; +import org.springframework.data.domain.Pageable; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.IllegalTransactionStateException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = WebEnvironment.NONE, + classes = EntityManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class PreseededActorAssignmentIntegrationTest { + private UUID assignmentUuid; + private UUID secondAssignmentUuid; + private UUID accountUuid; + private UUID secondAccountUuid; + private UUID tenantUuid; + private UUID realmUuid; + private UUID namespaceUuid; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "entity_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private CharacterRepository characterRepository; + @Autowired private CharacterFriendRepository characterFriendRepository; + @Autowired private ActorResourceStateRepository actorResourceStateRepository; + @Autowired private ActorActiveConditionRepository actorActiveConditionRepository; + @Autowired private InventoryEntryRepository inventoryEntryRepository; + @Autowired private CharacterEquipmentRepository characterEquipmentRepository; + @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @BeforeEach + void createIsolatedOwnerProofIdentities() { + assignmentUuid = UUID.randomUUID(); + secondAssignmentUuid = UUID.randomUUID(); + accountUuid = UUID.randomUUID(); + secondAccountUuid = UUID.randomUUID(); + tenantUuid = UUID.randomUUID(); + realmUuid = UUID.randomUUID(); + namespaceUuid = UUID.randomUUID(); + } + + @Test + void receiptLockRequiresCallerOwnedWritableTransactionThroughRepositoryProxy() { + UUID absentActor = UUID.randomUUID(); + assertThatThrownBy( + () -> + characterRepository.lockCurrentPreseededActorAssignmentReceipt( + assignmentUuid, accountUuid, absentActor, "a".repeat(64))) + .isInstanceOf(IllegalTransactionStateException.class); + + TransactionTemplate writable = new TransactionTemplate(transactionManager); + Optional absentReceipt = + writable.execute( + ignored -> + characterRepository.lockCurrentPreseededActorAssignmentReceipt( + assignmentUuid, accountUuid, absentActor, "a".repeat(64))); + assertThat(absentReceipt).isEmpty(); + + TransactionTemplate readOnly = new TransactionTemplate(transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute( + ignored -> + characterRepository.lockCurrentPreseededActorAssignmentReceipt( + assignmentUuid, accountUuid, absentActor, "a".repeat(64)))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable hold transaction"); + } + + @Test + void postgresMigrationInstallsAndEnforcesDeferredAssignmentForeignKeys() { + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor"); + + UUID missingCharacterUuid = UUID.randomUUID(); + UUID invalidOperationUuid = UUID.randomUUID(); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "INSERT INTO entity_preseeded_actor_assignment_operations (" + + "assignment_uuid, intent_digest, account_uuid, account_uuid_provenance, " + + "account_identity_schema_version, account_identity_target_namespace, " + + "source_account_row_id, eligibility, " + + "eligibility_evaluated_at, membership_authority_generation, " + + "eligibility_evidence_digest, tenant_uuid, realm_uuid, world_slug, " + + "realm_slug, game_instance_id, catalog_revision, canonical_version_uuid, " + + "publication_evidence_format, frozen_policy_digest, " + + "playable_state_namespace_id, playable_state_scope, entry_policy, " + + "actor_kind, display_name, status, character_uuid, completed_at, " + + "account_authority_snapshot_digest, account_purpose, account_currentness, " + + "published_owner_proof_digest, published_release_bundle_ref) " + + "SELECT ?, intent_digest, account_uuid, account_uuid_provenance, " + + "account_identity_schema_version, account_identity_target_namespace, " + + "source_account_row_id, eligibility, " + + "eligibility_evaluated_at, membership_authority_generation, " + + "eligibility_evidence_digest, tenant_uuid, realm_uuid, world_slug, " + + "realm_slug, game_instance_id, catalog_revision, canonical_version_uuid, " + + "publication_evidence_format, frozen_policy_digest, " + + "playable_state_namespace_id, playable_state_scope, entry_policy, " + + "actor_kind, display_name, 'ASSIGNED', ?, CURRENT_TIMESTAMP " + + ", account_authority_snapshot_digest, account_purpose, " + + "account_currentness, published_owner_proof_digest, " + + "published_release_bundle_ref " + + "FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + invalidOperationUuid, + missingCharacterUuid, + assignmentUuid)) + .isInstanceOf(DataAccessException.class); + + assertThat( + jdbcTemplate.queryForList( + "SELECT conname FROM pg_constraint " + + "WHERE conname IN (?, ?, ?) AND contype = 'f' AND convalidated " + + "AND condeferrable AND condeferred " + + "AND conrelid = 'entity_preseeded_actor_assignment_operations'::regclass", + String.class, + "fk_entity_preseeded_assignment_tenant_identity", + "fk_entity_preseeded_assignment_namespace", + "fk_entity_preseeded_assignment_character")) + .containsExactlyInAnyOrder( + "fk_entity_preseeded_assignment_tenant_identity", + "fk_entity_preseeded_assignment_namespace", + "fk_entity_preseeded_assignment_character"); + } + + @Test + void migrationRetainsOlderRosterEvidenceWithoutBackfillingOwnerCounters() throws Exception { + String schema = "ph_" + UUID.randomUUID().toString().replace("-", ""); + UUID historicalSnapshot = UUID.randomUUID(); + UUID v8Snapshot = UUID.randomUUID(); + UUID historicalTenant = UUID.randomUUID(); + UUID historicalNamespace = UUID.randomUUID(); + UUID v8CanonicalVersion = UUID.randomUUID(); + + migrationFlyway(schema).target(MigrationVersion.fromVersion("1008")).load().migrate(); + try (Connection connection = connectToSchema(schema)) { + try (PreparedStatement tenant = + connection.prepareStatement( + "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?)")) { + tenant.setObject(1, historicalTenant); + tenant.executeUpdate(); + } + try (PreparedStatement namespace = + connection.prepareStatement( + "INSERT INTO entity_playable_state_namespace_scopes " + + "(tenant_uuid, playable_state_namespace_id, playable_state_scope) " + + "VALUES (?, ?, ?)")) { + namespace.setObject(1, historicalTenant); + namespace.setObject(2, historicalNamespace); + namespace.setString(3, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + namespace.executeUpdate(); + } + try (PreparedStatement snapshot = + connection.prepareStatement( + "INSERT INTO entity_canonical_gameplay_roster_snapshots " + + "(snapshot_uuid, snapshot_digest, canonical_account_uuid, tenant_uuid, " + + "realm_uuid, world_slug, realm_slug, game_instance_uuid, catalog_revision, " + + "published_version_id, published_version_number, published_policy_digest, " + + "published_release_bundle_ref, admission_pointer_snapshot_digest, " + + "published_owner_proof_digest, playable_state_namespace_uuid, " + + "playable_state_scope, entry_policy, roster_count, construction_state) " + + "VALUES (?, ?, ?, ?, ?, 'world', 'realm', ?, 7, 17, 2, ?, " + + "'release/test', ?, ?, ?, ?, 'PRESEEDED_ONLY', 0, 'SEALED')")) { + snapshot.setObject(1, historicalSnapshot); + snapshot.setString(2, "a".repeat(64)); + snapshot.setObject(3, UUID.randomUUID()); + snapshot.setObject(4, historicalTenant); + snapshot.setObject(5, UUID.randomUUID()); + snapshot.setObject(6, UUID.randomUUID()); + snapshot.setString(7, "b".repeat(64)); + snapshot.setString(8, "c".repeat(64)); + snapshot.setString(9, "d".repeat(64)); + snapshot.setObject(10, historicalNamespace); + snapshot.setString(11, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + snapshot.executeUpdate(); + } + } + + migrationFlyway(schema).target(MigrationVersion.fromVersion("1009")).load().migrate(); + try (Connection connection = connectToSchema(schema); + PreparedStatement snapshot = + connection.prepareStatement( + "INSERT INTO entity_canonical_gameplay_roster_snapshots " + + "(snapshot_uuid, snapshot_digest, canonical_account_uuid, tenant_uuid, " + + "realm_uuid, world_slug, realm_slug, game_instance_uuid, catalog_revision, " + + "published_version_id, published_version_number, canonical_version_uuid, " + + "publication_evidence_format, published_policy_digest, " + + "published_release_bundle_ref, admission_pointer_snapshot_digest, " + + "published_owner_proof_digest, playable_state_namespace_uuid, " + + "playable_state_scope, entry_policy, roster_count, construction_state) " + + "VALUES (?, ?, ?, ?, ?, 'world', 'realm', ?, 7, NULL, NULL, ?, " + + "'CANONICAL_UUID', ?, 'release/v8', ?, ?, ?, ?, " + + "'PRESEEDED_ONLY', 0, 'SEALED')")) { + snapshot.setObject(1, v8Snapshot); + snapshot.setString(2, "e".repeat(64)); + snapshot.setObject(3, UUID.randomUUID()); + snapshot.setObject(4, historicalTenant); + snapshot.setObject(5, UUID.randomUUID()); + snapshot.setObject(6, UUID.randomUUID()); + snapshot.setObject(7, v8CanonicalVersion); + snapshot.setString(8, "f".repeat(64)); + snapshot.setString(9, "a".repeat(64)); + snapshot.setString(10, "b".repeat(64)); + snapshot.setObject(11, historicalNamespace); + snapshot.setString(12, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + snapshot.executeUpdate(); + } + + migrationFlyway(schema).load().migrate(); + try (Connection connection = connectToSchema(schema); + PreparedStatement retained = + connection.prepareStatement( + "SELECT snapshot_digest, publication_evidence_format, canonical_version_uuid, " + + "published_version_id, published_version_number, pointer_version, " + + "active_world_epoch " + + "FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?")) { + retained.setObject(1, historicalSnapshot); + try (ResultSet row = retained.executeQuery()) { + assertThat(row.next()).isTrue(); + assertThat(row.getString(1)).isEqualTo("a".repeat(64)); + assertThat(row.getString(2)).isEqualTo("LEGACY_NUMERIC"); + assertThat(row.getObject(3)).isNull(); + assertThat(row.getLong(4)).isEqualTo(17L); + assertThat(row.getInt(5)).isEqualTo(2); + assertThat(row.getObject(6)).isNull(); + assertThat(row.getObject(7)).isNull(); + } + } + try (Connection connection = connectToSchema(schema); + PreparedStatement retained = + connection.prepareStatement( + "SELECT snapshot_digest, publication_evidence_format, canonical_version_uuid, " + + "published_version_id, published_version_number, pointer_version, " + + "active_world_epoch " + + "FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?")) { + retained.setObject(1, v8Snapshot); + try (ResultSet row = retained.executeQuery()) { + assertThat(row.next()).isTrue(); + assertThat(row.getString(1)).isEqualTo("e".repeat(64)); + assertThat(row.getString(2)).isEqualTo("CANONICAL_UUID"); + assertThat(row.getObject(3)).isEqualTo(v8CanonicalVersion); + assertThat(row.getObject(4)).isNull(); + assertThat(row.getObject(5)).isNull(); + assertThat(row.getObject(6)).isNull(); + assertThat(row.getObject(7)).isNull(); + } + } + } + + @Test + void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace() + throws Exception { + String schema = "pa_" + UUID.randomUUID().toString().replace("-", ""); + UUID retainedAccountUuid = UUID.randomUUID(); + UUID retainedTenantUuid = UUID.randomUUID(); + UUID retainedNamespaceUuid = UUID.randomUUID(); + + migrationFlyway(schema).target(MigrationVersion.fromVersion("1005")).load().migrate(); + List parentHistory = appliedMigrationHistory(schema); + assertThat(parentHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); + assertThat(parentHistory) + .extracting(AppliedMigration::version) + .containsExactly("1", "1000", "1001", "1002", "1003", "1004", "1005"); + assertThat(parentHistory) + .extracting(AppliedMigration::script) + .containsExactly( + "V1__baseline.sql", + "saga/V1000__create_saga_schema.sql", + "saga/V1001__saga_instance_table.sql", + "saga/V1002__saga_step_table.sql", + "V1003__quarantine_unresolved_actor_identity.sql", + "V1004__build_actor_identity_indexes_concurrently.sql", + "V1005__validate_actor_identity_constraints.sql"); + assertThat(parentHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); + try (Connection connection = connectToSchema(schema)) { + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO entity_playable_state_namespace_scopes " + + "(tenant_uuid, playable_state_namespace_id, playable_state_scope) " + + "VALUES (?, ?, ?)")) { + statement.setObject(1, retainedTenantUuid); + statement.setObject(2, retainedNamespaceUuid); + statement.setString(3, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + statement.executeUpdate(); + } + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key, " + + "character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, " + + "playable_state_scope, actor_identity_status, " + + "actor_identity_quarantine_reason) " + + "VALUES (23, ?, 41, ?, ?, ?, ?, ?, ?, 'OWNER_RESOLVED', NULL)")) { + for (String retainedName : List.of("Retained duplicate A", "Retained duplicate B")) { + statement.setString(1, retainedName); + statement.setString(2, retainedNamespaceUuid.toString()); + statement.setObject(3, UUID.randomUUID()); + statement.setObject(4, retainedAccountUuid); + statement.setObject(5, retainedTenantUuid); + statement.setObject(6, retainedNamespaceUuid); + statement.setString(7, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + statement.executeUpdate(); + } + } + } + + migrationFlyway(schema).load().migrate(); + + List upgradedHistory = appliedMigrationHistory(schema); + assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); + assertThat(upgradedHistory.subList(0, parentHistory.size())) + .containsExactlyElementsOf(parentHistory); + List successorHistory = + upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); + assertThat(successorHistory) + .extracting(AppliedMigration::version) + .containsExactly("1006", "1007", "1008", "1009", "1010"); + assertThat(successorHistory) + .extracting(AppliedMigration::script) + .containsExactly( + "V1006__preseeded_actor_assignment.sql", + "V1007__preseeded_assignment_owner_snapshot.sql", + "V1008__canonical_gameplay_roster_snapshots.sql", + "V1009__canonical_publication_uuid_actor_evidence.sql", + "V1010__canonical_roster_owner_counters.sql"); + assertThat(successorHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); + + try (Connection connection = connectToSchema(schema)) { + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT count(*) FROM characters WHERE account_uuid = ? " + + "AND actor_identity_status = 'QUARANTINED' " + + "AND actor_identity_quarantine_reason = 'AMBIGUOUS_ACCOUNT_NAMESPACE'")) { + statement.setObject(1, retainedAccountUuid); + try (ResultSet rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + assertThat(rows.getLong(1)).isEqualTo(2L); + } + } + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT count(*) FROM pg_indexes WHERE schemaname = ? " + + "AND indexname = 'ux_characters_owner_resolved_account_namespace'")) { + statement.setString(1, schema); + try (ResultSet rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + assertThat(rows.getLong(1)).isEqualTo(1L); + } + } + try (PreparedStatement insert = + connection.prepareStatement( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key, " + + "character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, " + + "playable_state_scope, actor_identity_status, " + + "actor_identity_quarantine_reason) " + + "VALUES (23, 'New verified assignment', 41, ?, ?, ?, ?, ?, ?, " + + "'OWNER_RESOLVED', NULL)")) { + insert.setString(1, retainedNamespaceUuid.toString()); + insert.setObject(2, UUID.randomUUID()); + insert.setObject(3, retainedAccountUuid); + insert.setObject(4, retainedTenantUuid); + insert.setObject(5, retainedNamespaceUuid); + insert.setString(6, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + assertThat(insert.executeUpdate()).isEqualTo(1); + } + try (PreparedStatement duplicate = + connection.prepareStatement( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key, " + + "character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, " + + "playable_state_scope, actor_identity_status, " + + "actor_identity_quarantine_reason) " + + "VALUES (23, 'Duplicate live actor', 41, ?, ?, ?, ?, ?, ?, " + + "'OWNER_RESOLVED', NULL)")) { + duplicate.setString(1, retainedNamespaceUuid.toString()); + duplicate.setObject(2, UUID.randomUUID()); + duplicate.setObject(3, retainedAccountUuid); + duplicate.setObject(4, retainedTenantUuid); + duplicate.setObject(5, retainedNamespaceUuid); + duplicate.setString(6, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED.name()); + assertThatThrownBy(duplicate::executeUpdate).isInstanceOf(SQLException.class); + } + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT count(*) FILTER (WHERE actor_identity_status = 'QUARANTINED'), " + + "count(*) FILTER (WHERE actor_identity_status = 'OWNER_RESOLVED') " + + "FROM characters WHERE account_uuid = ?")) { + statement.setObject(1, retainedAccountUuid); + try (ResultSet rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + assertThat(rows.getLong(1)).isEqualTo(2L); + assertThat(rows.getLong(2)).isEqualTo(1L); + } + } + } + } + + @Test + void exactRetryReturnsSamePersistedActorAndChangedIntentConflictsBeforeAllocation() { + PreseededActorAssignmentResult first = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor"); + PreseededActorAssignmentResult retry = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor"); + PreseededActorAssignmentResult changedIntent = + assign( + assignmentUuid, + accountUuid, + 5L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor"); + + assertThat(first.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertThat(retry).isEqualTo(first); + assertThat(retry.characterUuid()).isEqualTo(first.characterUuid()); + assertConflictWithoutActorDisclosure(changedIntent); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE character_uuid = ? " + + "AND account_uuid = ? AND tenant_uuid = ? " + + "AND playable_state_namespace_id = ? AND actor_identity_status = 'OWNER_RESOLVED'", + Integer.class, + first.characterUuid(), + accountUuid, + tenantUuid, + namespaceUuid)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + Integer.class, + assignmentUuid)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters c " + + "JOIN entity_tenant_identities t " + + "ON c.tenant_id = t.entity_tenant_row_id " + + "WHERE c.character_uuid = ? AND t.canonical_tenant_uuid = ?", + Integer.class, + first.characterUuid(), + tenantUuid)) + .isEqualTo(1); + } + + @Test + void committedReceiptIsExactReplayStableAndDeniedForChangedOrQuarantinedActor() { + PreseededActorAssignmentResult assigned = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor"); + var evidence = + evidence(assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + var expectedTarget = + new PreseededActorAssignmentExpectedTarget( + tenantUuid, + realmUuid, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + namespaceUuid, + "release-bundle/test", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + var exactRequest = + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + assigned.characterUuid(), + assigned.intentDigest(), + expectedTarget); + + var receipt = + characterRepository.readPreseededActorAssignmentReceipt(exactRequest).orElseThrow(); + assertThat(characterRepository.readPreseededActorAssignmentReceipt(exactRequest)) + .contains(receipt); + assertThat(receipt.assignmentUuid()).isEqualTo(assignmentUuid); + assertThat(receipt.canonicalAccountUuid()).isEqualTo(accountUuid); + assertThat(receipt.characterUuid()).isEqualTo(assigned.characterUuid()); + assertThat(receipt.intentDigest()).isEqualTo(assigned.intentDigest()); + assertThat(receipt.target()).isEqualTo(expectedTarget); + assertThat(receipt.accountPurpose()) + .isEqualTo(PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING); + assertThat(receipt.accountCurrentness()) + .isEqualTo( + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION); + assertThat(receipt.accountIdentitySchemaVersion()).isEqualTo(1); + assertThat(receipt.accountIdentityTargetNamespace()).isEqualTo("dev"); + assertThat(receipt.sourceAccountRowId()).isEqualTo(23L); + assertThat(receipt.accountUuidProvenance()).isEqualTo("ACCOUNT_DATABASE_INSERT"); + assertThat(receipt.eligibility()) + .isEqualTo(PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE); + assertThat(receipt.eligibleAtRevalidation()).isTrue(); + assertThat(receipt.publishedReleaseBundleRef()).isEqualTo("release-bundle/test"); + assertThat( + jdbcTemplate.queryForObject( + "SELECT canonical_version_uuid FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + UUID.class, + assignmentUuid)) + .isEqualTo(expectedTarget.canonicalVersionUuid()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT publication_evidence_format FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + String.class, + assignmentUuid)) + .isEqualTo("CANONICAL_UUID"); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "UPDATE entity_preseeded_actor_assignment_operations " + + "SET canonical_version_uuid = ? WHERE assignment_uuid = ?", + UUID.randomUUID(), + assignmentUuid)) + .isInstanceOf(DataAccessException.class); + + assertThat( + characterRepository.readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + assigned.characterUuid(), + "f".repeat(64), + expectedTarget))) + .isEmpty(); + assertThat( + characterRepository.readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + secondAccountUuid, + assigned.characterUuid(), + assigned.intentDigest(), + expectedTarget))) + .isEmpty(); + assertThat( + characterRepository.readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + UUID.randomUUID(), + assigned.intentDigest(), + expectedTarget))) + .isEmpty(); + + jdbcTemplate.update( + "UPDATE characters SET account_id = 24 WHERE character_uuid = ?", assigned.characterUuid()); + assertThat(characterRepository.readPreseededActorAssignmentReceipt(exactRequest)).isEmpty(); + jdbcTemplate.update( + "UPDATE characters SET account_id = 23 WHERE character_uuid = ?", assigned.characterUuid()); + + jdbcTemplate.update( + "UPDATE characters SET actor_identity_status = 'QUARANTINED', " + + "actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING' " + + "WHERE character_uuid = ?", + assigned.characterUuid()); + assertThat(characterRepository.readPreseededActorAssignmentReceipt(exactRequest)).isEmpty(); + + PreseededActorAssignmentOwnerEvidence changedReleaseRef = + withPublishedReleaseBundleRef(evidence, "release-bundle/changed"); + PreseededActorAssignmentRequest replayRequest = assignmentRequest(changedReleaseRef); + PreseededActorAssignmentResult changedRelease = + characterRepository.assignPreseededActor( + replayRequest, + changedReleaseRef, + accountIdentity(assignmentUuid, accountUuid), + replayRequest.mutationIntentDigest()); + assertConflictWithoutActorDisclosure(changedRelease); + } + + @Test + void numericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters() { + assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters(false); + } + + @Test + void numericTenantCollisionKeepsQuarantinedCanonicalActorOutOfLegacyReadersAndWriters() { + assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters(true); + } + + private void assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters( + boolean quarantined) { + PreseededActorAssignmentResult assigned = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Canonical Actor"); + Long entityTenantRowId = + jdbcTemplate.queryForObject( + "SELECT entity_tenant_row_id FROM entity_tenant_identities " + + "WHERE canonical_tenant_uuid = ?", + Long.class, + tenantUuid); + Long canonicalCharacterId = + jdbcTemplate.queryForObject( + "SELECT id FROM characters WHERE character_uuid = ?", + Long.class, + assigned.characterUuid()); + if (quarantined) { + jdbcTemplate.update( + "UPDATE characters SET actor_identity_status = 'QUARANTINED', " + + "actor_identity_quarantine_reason = 'AMBIGUOUS_ACCOUNT_NAMESPACE' WHERE id = ?", + canonicalCharacterId); + } + assertThat( + jdbcTemplate.queryForObject( + "SELECT tenant_uuid FROM characters WHERE id = ?", + UUID.class, + canonicalCharacterId)) + .isEqualTo(tenantUuid); + assertThat( + jdbcTemplate.queryForObject( + "SELECT actor_identity_status FROM characters WHERE id = ?", + String.class, + canonicalCharacterId)) + .isEqualTo(quarantined ? "QUARANTINED" : "OWNER_RESOLVED"); + Long legacyCharacterId = + jdbcTemplate.queryForObject( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key) " + + "VALUES (23, 'Legacy Actor', ?, 'shared-live') RETURNING id", + Long.class, + entityTenantRowId); + assertThat( + jdbcTemplate.queryForObject( + "SELECT tenant_uuid IS NULL AND actor_identity_status = 'QUARANTINED' " + + "FROM characters WHERE id = ?", + Boolean.class, + legacyCharacterId)) + .isTrue(); + Long itemId = + jdbcTemplate.queryForObject( + "INSERT INTO items (name, tenant_id) VALUES ('Legacy Item', ?) RETURNING id", + Long.class, + entityTenantRowId); + for (Long characterId : List.of(canonicalCharacterId, legacyCharacterId)) { + jdbcTemplate.update( + "INSERT INTO inventory (character_id, item_id, quantity) VALUES (?, ?, 1)", + characterId, + itemId); + jdbcTemplate.update( + "INSERT INTO character_equipment (character_id, slot, item_id) " + + "VALUES (?, 'hand', ?)", + characterId, + itemId); + } + Long legacyFriendId = + jdbcTemplate.queryForObject( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key) " + + "VALUES (24, 'Legacy Friend', ?, 'shared-live') RETURNING id", + Long.class, + entityTenantRowId); + jdbcTemplate.update( + "INSERT INTO character_friend (character_id, friend_id, tenant_id) VALUES (?, ?, ?)", + legacyCharacterId, + legacyFriendId, + entityTenantRowId); + jdbcTemplate.update( + "INSERT INTO character_friend (character_id, friend_id, tenant_id) VALUES (?, ?, ?)", + canonicalCharacterId, + legacyFriendId, + entityTenantRowId); + jdbcTemplate.update( + "INSERT INTO character_friend (character_id, friend_id, tenant_id) VALUES (?, ?, ?)", + legacyCharacterId, + canonicalCharacterId, + entityTenantRowId); + Long canonicalResourceId = + jdbcTemplate.queryForObject( + "INSERT INTO actor_resource_states " + + "(tenant_id, playable_state_key, character_id, stat_key, current_value) " + + "VALUES (?, ?, ?, 'focus', 5) RETURNING id", + Long.class, + entityTenantRowId, + namespaceUuid.toString(), + canonicalCharacterId); + Long legacyResourceId = + jdbcTemplate.queryForObject( + "INSERT INTO actor_resource_states " + + "(tenant_id, playable_state_key, character_id, stat_key, current_value) " + + "VALUES (?, 'shared-live', ?, 'focus', 7) RETURNING id", + Long.class, + entityTenantRowId, + legacyCharacterId); + Instant expiry = Instant.parse("2030-01-01T00:00:00Z"); + Long canonicalConditionId = + jdbcTemplate.queryForObject( + "INSERT INTO actor_active_conditions " + + "(tenant_id, playable_state_key, character_id, condition_key, source_type, " + + "source_id, expires_at) VALUES (?, ?, ?, 'shielded', 'fixture', 'canonical', ?) " + + "RETURNING id", + Long.class, + entityTenantRowId, + namespaceUuid.toString(), + canonicalCharacterId, + java.time.OffsetDateTime.ofInstant(expiry, java.time.ZoneOffset.UTC)); + Long legacyConditionId = + jdbcTemplate.queryForObject( + "INSERT INTO actor_active_conditions " + + "(tenant_id, playable_state_key, character_id, condition_key, source_type, " + + "source_id, expires_at) VALUES (?, 'shared-live', ?, 'shielded', 'fixture', " + + "'legacy', ?) RETURNING id", + Long.class, + entityTenantRowId, + legacyCharacterId, + java.time.OffsetDateTime.ofInstant(expiry, java.time.ZoneOffset.UTC)); + + assertThat(characterRepository.findById(canonicalCharacterId)).isEmpty(); + assertThat(characterRepository.findWithInventoryById(canonicalCharacterId)).isEmpty(); + assertThat(characterRepository.findByIdAndTenantId(canonicalCharacterId, entityTenantRowId)) + .isEmpty(); + assertThat( + characterRepository.findByIdAndTenantIdAndPlayableStateKey( + canonicalCharacterId, entityTenantRowId, namespaceUuid.toString())) + .isEmpty(); + assertThat( + characterRepository.findByTenantIdAndAccountIdAndPlayableStateKey( + entityTenantRowId, 23L, namespaceUuid.toString(), Pageable.unpaged())) + .isEmpty(); + assertThat( + characterRepository.findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( + entityTenantRowId, namespaceUuid.toString(), "Canonical Actor")) + .isEmpty(); + assertThat(characterRepository.countByTenantId(entityTenantRowId)).isEqualTo(2); + assertThat(characterRepository.countQuarantinedByTenantId(entityTenantRowId)).isEqualTo(2); + assertThat(inventoryEntryRepository.countByCharacterTenantId(entityTenantRowId)).isEqualTo(1); + assertThat(characterEquipmentRepository.countByCharacterTenantId(entityTenantRowId)) + .isEqualTo(1); + assertThat( + inventoryEntryRepository.findByIdCharacterId(canonicalCharacterId, Pageable.unpaged())) + .isEmpty(); + assertThat( + inventoryEntryRepository.findByIdCharacterIdAndCharacterTenantId( + canonicalCharacterId, entityTenantRowId, Pageable.unpaged())) + .isEmpty(); + assertThat( + characterEquipmentRepository.findByIdCharacterIdAndCharacterTenantId( + canonicalCharacterId, entityTenantRowId, Pageable.unpaged())) + .isEmpty(); + + Character legacy = characterRepository.findById(legacyCharacterId).orElseThrow(); + assertThat(legacy.getName()).isEqualTo("Legacy Actor"); + assertThat(characterRepository.findWithInventoryById(legacyCharacterId)).isPresent(); + assertThat(characterRepository.findByIdAndTenantId(legacyCharacterId, entityTenantRowId)) + .isPresent(); + assertThat( + characterRepository.findByTenantIdAndAccountIdAndPlayableStateKey( + entityTenantRowId, 23L, "shared-live", Pageable.unpaged())) + .hasSize(1); + assertThat( + inventoryEntryRepository.findByIdCharacterIdAndCharacterTenantId( + legacyCharacterId, entityTenantRowId, Pageable.unpaged())) + .hasSize(1); + assertThat( + characterEquipmentRepository.findByIdCharacterIdAndCharacterTenantId( + legacyCharacterId, entityTenantRowId, Pageable.unpaged())) + .hasSize(1); + legacy.setName("Updated Legacy Actor"); + assertThat(characterRepository.save(legacy).getName()).isEqualTo("Updated Legacy Actor"); + + CharacterFriendKey legacyFriendKey = new CharacterFriendKey(); + legacyFriendKey.setCharacterId(legacyCharacterId); + legacyFriendKey.setFriendId(legacyFriendId); + CharacterFriendKey canonicalFriendKey = new CharacterFriendKey(); + canonicalFriendKey.setCharacterId(canonicalCharacterId); + canonicalFriendKey.setFriendId(legacyFriendId); + CharacterFriendKey canonicalTargetKey = new CharacterFriendKey(); + canonicalTargetKey.setCharacterId(legacyCharacterId); + canonicalTargetKey.setFriendId(canonicalCharacterId); + assertThat(characterFriendRepository.countByTenantId(entityTenantRowId)).isEqualTo(1); + assertThat(characterFriendRepository.findByIdCharacterId(legacyCharacterId, Pageable.unpaged())) + .hasSize(1); + assertThat(characterFriendRepository.findById(legacyFriendKey)).isPresent(); + assertThat(characterFriendRepository.findById(canonicalFriendKey)).isEmpty(); + assertThat(characterFriendRepository.findById(canonicalTargetKey)).isEmpty(); + CharacterFriend forbiddenFriend = new CharacterFriend(); + forbiddenFriend.setId(canonicalFriendKey); + forbiddenFriend.setTenantId(entityTenantRowId); + forbiddenFriend.setCreatedAt(Instant.now()); + assertThatThrownBy(() -> characterFriendRepository.save(forbiddenFriend)) + .isInstanceOf(IllegalStateException.class); + forbiddenFriend.setId(canonicalTargetKey); + assertThatThrownBy(() -> characterFriendRepository.save(forbiddenFriend)) + .isInstanceOf(IllegalStateException.class); + characterFriendRepository.deleteById(canonicalFriendKey); + characterFriendRepository.deleteById(canonicalTargetKey); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM character_friend WHERE character_id = ? OR friend_id = ?", + Integer.class, + canonicalCharacterId, + canonicalCharacterId)) + .isEqualTo(2); + characterFriendRepository.deleteById(legacyFriendKey); + assertThat(characterFriendRepository.countByTenantId(entityTenantRowId)).isZero(); + CharacterFriend restoredLegacyFriend = new CharacterFriend(); + restoredLegacyFriend.setId(legacyFriendKey); + restoredLegacyFriend.setTenantId(entityTenantRowId); + restoredLegacyFriend.setCreatedAt(Instant.now()); + assertThat(characterFriendRepository.save(restoredLegacyFriend)).isNotNull(); + + assertThat( + actorResourceStateRepository + .findByTenantIdAndPlayableStateKeyAndCharacterIdOrderByStatKeyAsc( + entityTenantRowId, namespaceUuid.toString(), canonicalCharacterId)) + .isEmpty(); + ActorResourceState legacyResource = + actorResourceStateRepository + .findByTenantIdAndPlayableStateKeyAndCharacterIdOrderByStatKeyAsc( + entityTenantRowId, "shared-live", legacyCharacterId) + .getFirst(); + legacyResource.setCurrentValue(8L); + actorResourceStateRepository.save(legacyResource); + assertThat( + jdbcTemplate.queryForObject( + "SELECT current_value FROM actor_resource_states WHERE id = ?", + Long.class, + legacyResourceId)) + .isEqualTo(8L); + ActorResourceState canonicalResourceWrite = new ActorResourceState(); + canonicalResourceWrite.setId(canonicalResourceId); + canonicalResourceWrite.setCharacterId(legacyCharacterId); + canonicalResourceWrite.setCurrentValue(99L); + assertThatThrownBy(() -> actorResourceStateRepository.save(canonicalResourceWrite)) + .isInstanceOf(IllegalStateException.class); + ActorResourceState addedLegacyResource = new ActorResourceState(); + addedLegacyResource.setTenantId(entityTenantRowId); + addedLegacyResource.setPlayableStateKey("shared-live"); + addedLegacyResource.setCharacterId(legacyCharacterId); + addedLegacyResource.setStatKey("new-focus"); + addedLegacyResource.setCurrentValue(11L); + Long addedLegacyResourceId = actorResourceStateRepository.save(addedLegacyResource).getId(); + assertThat(addedLegacyResourceId).isNotNull(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT current_value FROM actor_resource_states WHERE id = ?", + Long.class, + addedLegacyResourceId)) + .isEqualTo(11L); + canonicalResourceWrite.setId(null); + canonicalResourceWrite.setTenantId(entityTenantRowId); + canonicalResourceWrite.setCharacterId(canonicalCharacterId); + canonicalResourceWrite.setPlayableStateKey(namespaceUuid.toString()); + canonicalResourceWrite.setStatKey("new-focus"); + assertThatThrownBy(() -> actorResourceStateRepository.save(canonicalResourceWrite)) + .isInstanceOf(IllegalStateException.class); + assertThat( + jdbcTemplate.queryForObject( + "SELECT current_value FROM actor_resource_states WHERE id = ?", + Long.class, + canonicalResourceId)) + .isEqualTo(5L); + + Instant beforeExpiry = Instant.parse("2026-01-01T00:00:00Z"); + assertThat( + actorActiveConditionRepository.findActiveForCharacter( + entityTenantRowId, namespaceUuid.toString(), canonicalCharacterId, beforeExpiry)) + .isEmpty(); + assertThat( + actorActiveConditionRepository + .findFirstByTenantIdAndPlayableStateKeyAndCharacterIdAndSourceTypeAndSourceIdOrderByIdAsc( + entityTenantRowId, + namespaceUuid.toString(), + canonicalCharacterId, + "fixture", + "canonical")) + .isEmpty(); + ActorActiveCondition legacyCondition = + actorActiveConditionRepository + .findActiveForCharacter( + entityTenantRowId, "shared-live", legacyCharacterId, beforeExpiry) + .getFirst(); + legacyCondition.setStackCount(2); + actorActiveConditionRepository.save(legacyCondition); + assertThat( + jdbcTemplate.queryForObject( + "SELECT stack_count FROM actor_active_conditions WHERE id = ?", + Integer.class, + legacyConditionId)) + .isEqualTo(2); + ActorActiveCondition canonicalConditionWrite = new ActorActiveCondition(); + canonicalConditionWrite.setId(canonicalConditionId); + canonicalConditionWrite.setCharacterId(legacyCharacterId); + canonicalConditionWrite.setStackCount(9); + assertThatThrownBy(() -> actorActiveConditionRepository.save(canonicalConditionWrite)) + .isInstanceOf(IllegalStateException.class); + ActorActiveCondition addedLegacyCondition = new ActorActiveCondition(); + addedLegacyCondition.setTenantId(entityTenantRowId); + addedLegacyCondition.setPlayableStateKey("shared-live"); + addedLegacyCondition.setCharacterId(legacyCharacterId); + addedLegacyCondition.setConditionKey("new-shield"); + addedLegacyCondition.setSourceType("fixture"); + addedLegacyCondition.setSourceId("new-legacy"); + addedLegacyCondition.setExpiresAt(expiry.plusSeconds(60)); + Long addedLegacyConditionId = actorActiveConditionRepository.save(addedLegacyCondition).getId(); + assertThat(addedLegacyConditionId).isNotNull(); + assertThat( + actorActiveConditionRepository + .findFirstByTenantIdAndPlayableStateKeyAndCharacterIdAndSourceTypeAndSourceIdOrderByIdAsc( + entityTenantRowId, "shared-live", legacyCharacterId, "fixture", "new-legacy")) + .isPresent(); + canonicalConditionWrite.setId(null); + canonicalConditionWrite.setTenantId(entityTenantRowId); + canonicalConditionWrite.setCharacterId(canonicalCharacterId); + canonicalConditionWrite.setPlayableStateKey(namespaceUuid.toString()); + canonicalConditionWrite.setConditionKey("new-shield"); + canonicalConditionWrite.setSourceType("fixture"); + assertThatThrownBy(() -> actorActiveConditionRepository.save(canonicalConditionWrite)) + .isInstanceOf(IllegalStateException.class); + assertThat(actorActiveConditionRepository.deleteExpired(expiry.plusSeconds(1))).isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM actor_active_conditions WHERE id = ?", + Integer.class, + addedLegacyConditionId)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM actor_active_conditions WHERE id = ?", + Integer.class, + canonicalConditionId)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM actor_active_conditions WHERE id = ?", + Integer.class, + legacyConditionId)) + .isZero(); + + Character canonicalIdWrite = new Character(); + canonicalIdWrite.setId(canonicalCharacterId); + canonicalIdWrite.setTenantId(entityTenantRowId); + canonicalIdWrite.setAccountId(23L); + canonicalIdWrite.setPlayableStateKey(namespaceUuid.toString()); + canonicalIdWrite.setName("Changed Canonical Actor"); + assertThatThrownBy(() -> characterRepository.save(canonicalIdWrite)) + .isInstanceOf(java.util.NoSuchElementException.class); + assertThat( + jdbcTemplate.queryForObject( + "SELECT name FROM characters WHERE id = ?", String.class, canonicalCharacterId)) + .isEqualTo("Canonical Actor"); + + PreseededActorAssignmentOwnerEvidence owner = + evidence(assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat( + characterRepository + .readPreseededActorAssignmentReceipt( + new PreseededActorAssignmentReceiptRequest( + assignmentUuid, + accountUuid, + assigned.characterUuid(), + assigned.intentDigest(), + assignmentRequest(owner).expectedTarget())) + .isPresent()) + .isEqualTo(!quarantined); + CanonicalGameplayRosterTarget rosterTarget = + new CanonicalGameplayRosterTarget( + tenantUuid, + realmUuid, + "world", + "realm", + UUID.randomUUID(), + 4L, + 1L, + 1L, + owner.canonicalVersionUuid(), + owner.frozenPolicyDigest(), + owner.publishedReleaseBundleRef(), + "5".repeat(64), + owner.publishedOwnerProofDigest(), + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + UUID rosterRequestUuid = UUID.randomUUID(); + CanonicalGameplayRosterReadRequest rosterRequest = + new CanonicalGameplayRosterReadRequest( + rosterRequestUuid, + accountUuid, + rosterTarget, + new CanonicalGameplayRosterExecutionContext( + accountUuid, + tenantUuid, + namespaceUuid, + rosterTarget.gameInstanceUuid(), + null, + UUID.randomUUID(), + realmUuid, + rosterRequestUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + assertThat( + characterRepository + .captureCanonicalGameplayRosterSnapshot( + rosterRequest, + new CanonicalGameplayRosterOwnerEvidence( + rosterRequestUuid, accountUuid, rosterTarget, Instant.now())) + .actors()) + .extracting(actor -> actor.characterUuid()) + .containsExactly(quarantined ? new UUID[0] : new UUID[] {assigned.characterUuid()}); + } + + @Test + void selectedAssignmentReadRequiresExactOwnerTargetAndCurrentActorProvenance() { + PreseededActorAssignmentResult assigned = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Selected Actor"); + var ownerEvidence = + evidence(assignmentUuid, accountUuid, 4L, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + var expectedTarget = assignmentRequest(ownerEvidence).expectedTarget(); + + var receipt = + characterRepository + .readSelectedPreseededActorAssignmentReceipt( + accountUuid, + assigned.characterUuid(), + expectedTarget, + ownerEvidence.publishedOwnerProofDigest()) + .orElseThrow(); + assertThat(receipt.assignmentUuid()).isEqualTo(assignmentUuid); + assertThat(receipt.canonicalAccountUuid()).isEqualTo(accountUuid); + assertThat(receipt.characterUuid()).isEqualTo(assigned.characterUuid()); + assertThat(receipt.intentDigest()).isEqualTo(assigned.intentDigest()); + + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + secondAccountUuid, + assigned.characterUuid(), + expectedTarget, + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, + UUID.randomUUID(), + expectedTarget, + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, + assigned.characterUuid(), + new PreseededActorAssignmentExpectedTarget( + tenantUuid, + realmUuid, + "world", + "realm", + "game-instance", + 5L, + expectedTarget.canonicalVersionUuid(), + expectedTarget.frozenPolicyDigest(), + namespaceUuid, + expectedTarget.publishedReleaseBundleRef(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, + assigned.characterUuid(), + new PreseededActorAssignmentExpectedTarget( + tenantUuid, + realmUuid, + "world", + "realm", + "game-instance", + 4L, + expectedTarget.canonicalVersionUuid(), + expectedTarget.frozenPolicyDigest(), + namespaceUuid, + expectedTarget.publishedReleaseBundleRef(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED), + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, assigned.characterUuid(), expectedTarget, "f".repeat(64))) + .isEmpty(); + + jdbcTemplate.update( + "UPDATE characters SET account_uuid = ? WHERE character_uuid = ?", + secondAccountUuid, + assigned.characterUuid()); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, + assigned.characterUuid(), + expectedTarget, + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + jdbcTemplate.update( + "UPDATE characters SET account_uuid = ? WHERE character_uuid = ?", + accountUuid, + assigned.characterUuid()); + jdbcTemplate.update( + "UPDATE characters SET actor_identity_status = 'QUARANTINED', " + + "actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING' " + + "WHERE character_uuid = ?", + assigned.characterUuid()); + assertThat( + characterRepository.readSelectedPreseededActorAssignmentReceipt( + accountUuid, + assigned.characterUuid(), + expectedTarget, + ownerEvidence.publishedOwnerProofDigest())) + .isEmpty(); + } + + @Test + void sameAssignmentUuidConflictsForChangedAccountScopeOrPayloadWithoutReturningActor() { + PreseededActorAssignmentResult original = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor"); + PreseededActorAssignmentResult changedAccount = + assign( + assignmentUuid, + secondAccountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor"); + PreseededActorAssignmentResult changedScope = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, + "Assigned Actor"); + PreseededActorAssignmentResult changedPayload = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Renamed Actor"); + + assertThat(original.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertConflictWithoutActorDisclosure(changedAccount); + assertConflictWithoutActorDisclosure(changedScope); + assertConflictWithoutActorDisclosure(changedPayload); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE actor_identity_status = 'OWNER_RESOLVED' " + + "AND tenant_uuid = ?", + Integer.class, + tenantUuid)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ? AND status = 'ASSIGNED'", + Integer.class, + assignmentUuid)) + .isEqualTo(1); + } + + @Test + void separateAuthorizedAssignmentsCanCreateMultipleActorsEvenWithSameDisplayName() { + PreseededActorAssignmentResult first = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor"); + PreseededActorAssignmentResult second = + assign( + secondAssignmentUuid, + secondAccountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor"); + + assertThat(first.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertThat(second.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertThat(second.characterUuid()).isNotEqualTo(first.characterUuid()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE tenant_uuid = ? " + + "AND playable_state_namespace_id = ? AND account_uuid = ? " + + "AND name = 'Assigned Actor' AND actor_identity_status = 'OWNER_RESOLVED'", + Integer.class, + tenantUuid, + namespaceUuid, + accountUuid)) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE tenant_uuid = ? " + + "AND playable_state_namespace_id = ? AND account_uuid = ? " + + "AND name = 'Assigned Actor' AND actor_identity_status = 'OWNER_RESOLVED'", + Integer.class, + tenantUuid, + namespaceUuid, + secondAccountUuid)) + .isEqualTo(1); + } + + @Test + void distinctConcurrentAssignmentsPersistOneWinnerAndOneReplayableConflict() throws Exception { + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Assignment race did not start"); + } + return assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Concurrent Actor"); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Assignment race did not start"); + } + return assign( + secondAssignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Concurrent Actor"); + }); + + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + List results = + List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); + PreseededActorAssignmentResult winner = + results.stream() + .filter(result -> result.outcome() == PreseededActorAssignmentResult.Outcome.ASSIGNED) + .findFirst() + .orElseThrow(); + PreseededActorAssignmentResult loser = + results.stream() + .filter( + result -> + result.outcome() + == PreseededActorAssignmentResult.Outcome.IDEMPOTENCY_CONFLICT) + .findFirst() + .orElseThrow(); + + assertThat(winner.characterUuid()).isNotNull(); + assertThat(loser.characterUuid()).isNull(); + assertThat( + assign( + loser.assignmentUuid(), + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Concurrent Actor")) + .isEqualTo(loser); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ? AND status = 'IDEMPOTENCY_CONFLICT' " + + "AND character_uuid IS NULL " + + "AND completed_at IS NOT NULL", + Integer.class, + loser.assignmentUuid())) + .isEqualTo(1); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE tenant_uuid = ? " + + "AND playable_state_namespace_id = ? AND account_uuid = ? " + + "AND actor_identity_status = 'OWNER_RESOLVED'", + Integer.class, + tenantUuid, + namespaceUuid, + accountUuid)) + .isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void conflictingNamespaceScopeProofRollsBackGuardAndDoesNotPromoteOrAllocateActor() { + jdbcTemplate.update( + "INSERT INTO entity_playable_state_namespace_scopes " + + "(tenant_uuid, playable_state_namespace_id, playable_state_scope) " + + "VALUES (?, ?, ?)", + tenantUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED.name()); + + assertThatThrownBy( + () -> + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor")) + .isInstanceOf(RuntimeException.class); + + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE tenant_uuid = ?", Integer.class, tenantUuid)) + .isZero(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + Integer.class, + assignmentUuid)) + .isZero(); + } + + @Test + void assignmentReplayAndOwnerMappingsRejectDeleteAndTruncate() { + PreseededActorAssignmentResult assigned = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor"); + + assertThatThrownBy( + () -> + jdbcTemplate.update( + "DELETE FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + assignmentUuid)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + jdbcTemplate.update( + "DELETE FROM entity_tenant_identities WHERE canonical_tenant_uuid = ?", + tenantUuid)) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + jdbcTemplate.execute( + "TRUNCATE TABLE entity_preseeded_actor_assignment_operations CASCADE")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> jdbcTemplate.execute("TRUNCATE TABLE entity_tenant_identities")) + .isInstanceOf(DataAccessException.class); + + assertThat( + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor")) + .isEqualTo(assigned); + } + + private PreseededActorAssignmentResult assign( + UUID operationUuid, + UUID actorAccountUuid, + long catalogRevision, + PlayableStateScope scope, + String displayName) { + PreseededActorAssignmentOwnerEvidence target = + evidence(operationUuid, actorAccountUuid, catalogRevision, scope); + PreseededActorAssignmentRequest request = assignmentRequest(target, displayName); + return characterRepository.assignPreseededActor( + request, + target, + accountIdentity(operationUuid, actorAccountUuid), + request.mutationIntentDigest()); + } + + private PreseededActorAssignmentRequest assignmentRequest( + PreseededActorAssignmentOwnerEvidence target) { + return assignmentRequest(target, "Assigned Actor"); + } + + private PreseededActorAssignmentRequest assignmentRequest( + PreseededActorAssignmentOwnerEvidence target, String displayName) { + return new PreseededActorAssignmentRequest( + target.assignmentUuid(), + target.canonicalAccountUuid(), + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, displayName), + new PreseededActorAssignmentExpectedTarget( + target.canonicalTenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + "game-instance", + target.catalogRevision(), + target.canonicalVersionUuid(), + target.frozenPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope())); + } + + private static PreseededActorAssignmentOwnerEvidence withPublishedReleaseBundleRef( + PreseededActorAssignmentOwnerEvidence evidence, String releaseRef) { + return new PreseededActorAssignmentOwnerEvidence( + evidence.assignmentUuid(), + evidence.canonicalAccountUuid(), + evidence.eligibility(), + evidence.eligibilityEvaluatedAt(), + evidence.membershipAuthorityGeneration(), + evidence.eligibilityEvidenceDigest(), + evidence.canonicalTenantUuid(), + evidence.realmUuid(), + evidence.worldSlug(), + evidence.realmSlug(), + "game-instance", + evidence.catalogRevision(), + evidence.canonicalVersionUuid(), + evidence.frozenPolicyDigest(), + evidence.playableStateNamespaceId(), + evidence.playableStateScope(), + evidence.entryPolicy(), + evidence.accountPurpose(), + evidence.accountCurrentness(), + evidence.accountAuthoritySnapshotDigest(), + evidence.publishedOwnerProofDigest(), + releaseRef); + } + + private PreseededActorAssignmentOwnerEvidence evidence( + UUID operationUuid, UUID actorAccountUuid, long catalogRevision, PlayableStateScope scope) { + return new PreseededActorAssignmentOwnerEvidence( + operationUuid, + actorAccountUuid, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 9L, + "1".repeat(64), + tenantUuid, + realmUuid, + "world", + "realm", + "game-instance", + catalogRevision, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + namespaceUuid, + scope, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "3".repeat(64), + "4".repeat(64), + "release-bundle/test"); + } + + private RuntimeAccountIdentityEvidence accountIdentity(UUID requestUuid, UUID actorAccountUuid) { + return new RuntimeAccountIdentityEvidence( + 1, + "dev", + requestUuid, + actorAccountUuid, + actorAccountUuid.equals(accountUuid) ? 23L : 24L, + "ACCOUNT_DATABASE_INSERT"); + } + + private void assertConflictWithoutActorDisclosure(PreseededActorAssignmentResult result) { + assertThat(result.outcome()) + .isEqualTo(PreseededActorAssignmentResult.Outcome.IDEMPOTENCY_CONFLICT); + assertThat(result.characterUuid()).isNull(); + } + + private FluentConfiguration migrationFlyway(String schema) { + assertThat(("flyway_schema_history_" + schema + "_s_idx").length()).isLessThanOrEqualTo(63); + FluentConfiguration configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .table("flyway_schema_history_" + schema) + .outOfOrder(false) + .placeholders(Map.of("serviceSchema", schema)); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + return configuration; + } + + private List appliedMigrationHistory(String schema) throws SQLException { + List migrations = new ArrayList<>(); + try (Connection connection = connectToSchema(schema); + Statement statement = connection.createStatement(); + ResultSet rows = + statement.executeQuery( + "SELECT installed_rank, version, script, checksum, success FROM flyway_schema_history_" + + schema + + " WHERE version IS NOT NULL ORDER BY installed_rank")) { + while (rows.next()) { + migrations.add( + new AppliedMigration( + rows.getInt(1), + rows.getString(2), + rows.getString(3), + rows.getObject(4, Integer.class), + rows.getBoolean(5))); + } + } + return migrations; + } + + private record AppliedMigration( + int installedRank, String version, String script, Integer checksum, boolean success) {} + + private Connection connectToSchema(String schema) throws SQLException { + Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + try (Statement statement = connection.createStatement()) { + statement.execute("SET search_path TO " + schema); + return connection; + } catch (SQLException failure) { + connection.close(); + throw failure; + } + } +} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java new file mode 100644 index 0000000000..df51b1a7b4 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -0,0 +1,903 @@ +package net.firedevops.firemud.entitymanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; +import net.firedevops.firemud.entitymanagement.entity.ActorResourceState; +import net.firedevops.firemud.entitymanagement.entity.Character; +import net.firedevops.firemud.entitymanagement.entity.CharacterFriend; +import net.firedevops.firemud.entitymanagement.entity.CharacterFriendKey; +import net.firedevops.firemud.entitymanagement.repository.ActorActiveConditionRepository; +import net.firedevops.firemud.entitymanagement.repository.ActorIdentityRepository; +import net.firedevops.firemud.entitymanagement.repository.ActorResourceStateRepository; +import net.firedevops.firemud.entitymanagement.repository.CharacterFriendRepository; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationState; +import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + webEnvironment = WebEnvironment.NONE, + classes = EntityManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class RetainedActorIdentityIntegrationTest { + private long tenantId; + private long accountId; + private String instanceId; + private UUID tenantUuid; + private UUID accountUuid; + private UUID namespaceUuid; + private String testServiceSchema; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "entity_management_service"); + registry.add( + "spring.flyway.locations", () -> "classpath:db/migration,classpath:db/migration/saga"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private CharacterRepository characterRepository; + @Autowired private ActorIdentityRepository actorIdentityRepository; + @Autowired private ActorActiveConditionRepository conditionRepository; + @Autowired private ActorResourceStateRepository resourceRepository; + @Autowired private JdbcTemplate jdbcTemplate; + @Autowired private CharacterFriendRepository friendRepository; + @Autowired private Flyway flyway; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @BeforeEach + void allocateIsolatedFixtureIdentities() { + tenantId = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); + accountId = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); + instanceId = "GI-RETAINED-" + UUID.randomUUID(); + tenantUuid = UUID.randomUUID(); + accountUuid = UUID.randomUUID(); + namespaceUuid = UUID.randomUUID(); + } + + @Test + void legacySaveAllocatesQuarantinedUuidAndPreservesLegacyReadbackAndUpdates() { + Character actor = new Character(); + actor.setTenantId(tenantId); + actor.setAccountId(accountId); + actor.setPlayableStateKey("instance:" + instanceId); + actor.setName("Retained actor"); + actor.setExperience(17); + actor = characterRepository.save(actor); + long actorId = actor.getId(); + UUID characterUuid = actor.getActorIdentity().characterUuid(); + assertThat(characterUuid).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(actor.getActorIdentity().status().name()).isEqualTo("QUARANTINED"); + assertThat(actor.getActorIdentity().quarantineReason()).isEqualTo("OWNER_PROVENANCE_MISSING"); + assertThat(actor.getActorIdentity().accountUuid()).isNull(); + assertThat(actor.getActorIdentity().tenantUuid()).isNull(); + assertThat(actor.getActorIdentity().playableStateNamespaceId()).isNull(); + assertThat(actor.getActorIdentity().playableStateScope()).isNull(); + assertThat(characterRepository.findById(actorId)).isPresent(); + assertThat(characterRepository.findWithInventoryById(actorId)).isPresent(); + assertThat(characterRepository.findByIdAndTenantId(actorId, tenantId)).isPresent(); + assertThat( + characterRepository.findByIdAndTenantIdAndPlayableStateKey( + actorId, tenantId, actor.getPlayableStateKey())) + .isPresent(); + assertThat( + characterRepository + .findByTenantIdAndAccountIdAndPlayableStateKey( + tenantId, accountId, actor.getPlayableStateKey(), null) + .getContent()) + .extracting(Character::getId) + .containsExactly(actorId); + assertThat( + characterRepository.findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( + tenantId, actor.getPlayableStateKey(), "retained ACTOR")) + .isPresent(); + + int originalVersion = actor.getVersion(); + actor.setName("Retained actor updated"); + actor.setExperience(18); + Character saved = characterRepository.save(actor); + assertThat(saved.getName()).isEqualTo("Retained actor updated"); + assertThat(saved.getExperience()).isEqualTo(18); + assertThat(saved.getVersion()).isEqualTo(originalVersion + 1); + assertThat(saved.getActorIdentity()).isEqualTo(actor.getActorIdentity()); + assertThat( + jdbcTemplate.queryForObject( + "SELECT character_uuid FROM characters WHERE id = ?", UUID.class, actorId)) + .isEqualTo(characterUuid); + } + + @Test + void legacyConditionalInsertsPreserveNullablePostgresColumnTypes() { + Character actor = new Character(); + actor.setTenantId(tenantId); + actor.setAccountId(accountId); + actor.setPlayableStateKey("instance:" + instanceId); + actor.setName("Nullable legacy values"); + actor = characterRepository.save(actor); + + ActorActiveCondition condition = new ActorActiveCondition(); + condition.setTenantId(tenantId); + condition.setPlayableStateKey(actor.getPlayableStateKey()); + condition.setCharacterId(actor.getId()); + condition.setConditionKey("permanent-condition"); + condition.setSourceType("TEST"); + conditionRepository.save(condition); + assertThat(condition.getId()).isNotNull(); + var conditions = + conditionRepository.findActiveForCharacter( + tenantId, actor.getPlayableStateKey(), actor.getId(), java.time.Instant.now()); + assertThat(conditions).hasSize(1); + assertThat(conditions.getFirst().getExpiresAt()).isNull(); + assertThat(conditions.getFirst().getSourceId()).isNull(); + assertThat(conditions.getFirst().getEffectPayloadJson()).isNull(); + + ActorResourceState resource = new ActorResourceState(); + resource.setTenantId(tenantId); + resource.setPlayableStateKey(actor.getPlayableStateKey()); + resource.setCharacterId(actor.getId()); + resource.setStatKey("nullable-stat"); + resource.setCurrentValue(5L); + resourceRepository.save(resource); + assertThat(resource.getId()).isNotNull(); + var resources = + resourceRepository.findByTenantIdAndPlayableStateKeyAndCharacterIdOrderByStatKeyAsc( + tenantId, actor.getPlayableStateKey(), actor.getId()); + assertThat(resources).hasSize(1); + assertThat(resources.getFirst().getCurrentValue()).isEqualTo(5L); + assertThat(resources.getFirst().getMaxValue()).isNull(); + assertThat(resources.getFirst().getBaseValue()).isNull(); + assertThat(resources.getFirst().getSourceId()).isNull(); + } + + @Test + void legacyFriendInsertUsesGeneratedColumnTypesAndRejectsOwnerResolvedEndpoints() { + Character character = new Character(); + character.setTenantId(tenantId); + character.setAccountId(accountId); + character.setPlayableStateKey("instance:" + instanceId); + character.setName("Legacy friend source"); + character = characterRepository.save(character); + + Character friendActor = new Character(); + friendActor.setTenantId(tenantId); + friendActor.setAccountId(accountId); + friendActor.setPlayableStateKey("instance:" + instanceId); + friendActor.setName("Legacy friend target"); + friendActor = characterRepository.save(friendActor); + + Instant createdAt = Instant.parse("2026-10-15T12:34:56Z"); + CharacterFriendKey friendKey = new CharacterFriendKey(); + friendKey.setCharacterId(character.getId()); + friendKey.setFriendId(friendActor.getId()); + CharacterFriend friend = new CharacterFriend(); + friend.setId(friendKey); + friend.setTenantId(tenantId); + friend.setCreatedAt(createdAt); + + friendRepository.save(friend); + + CharacterFriend readBack = friendRepository.findById(friendKey).orElseThrow(); + assertThat(readBack.getId().getCharacterId()).isEqualTo(character.getId()); + assertThat(readBack.getId().getFriendId()).isEqualTo(friendActor.getId()); + assertThat(readBack.getTenantId()).isEqualTo(tenantId); + assertThat(readBack.getCreatedAt()).isEqualTo(createdAt); + assertThat(friendRepository.countByTenantId(tenantId)).isEqualTo(1L); + + insertNamespace(tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + long ownerResolvedId = + insertActor( + "Owner-resolved friend endpoint", + UUID.randomUUID(), + accountUuid, + tenantUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + CharacterFriendKey rejectedKey = new CharacterFriendKey(); + rejectedKey.setCharacterId(character.getId()); + rejectedKey.setFriendId(ownerResolvedId); + CharacterFriend rejectedFriend = new CharacterFriend(); + rejectedFriend.setId(rejectedKey); + rejectedFriend.setTenantId(tenantId); + rejectedFriend.setCreatedAt(createdAt); + + assertThatThrownBy(() -> friendRepository.save(rejectedFriend)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Legacy friend endpoints are unavailable"); + } + + @Test + void storedCanonicalIdentityRequiresExactTupleWithoutPromotingLegacyRows() { + // SQL fixtures prove storage isolation only; they provide no owner authority or runtime + // admission. + insertNamespace(tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + UUID legacyActorUuid = UUID.randomUUID(); + long legacyId = + insertActor( + "legacy-shared", + legacyActorUuid, + null, + null, + null, + null, + "shared-live", + "QUARANTINED", + "OWNER_PROVENANCE_MISSING", + accountId, + tenantId); + UUID resolvedActorUuid = UUID.randomUUID(); + long resolvedId = + insertActor( + "owner-resolved", + resolvedActorUuid, + accountUuid, + tenantUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + assertThat( + storedActorUuids( + tenantUuid, + accountUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .containsExactly(resolvedActorUuid); + assertThat( + storedActorUuids( + UUID.randomUUID(), + accountUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat( + storedActorUuids( + tenantUuid, + UUID.randomUUID(), + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat( + storedActorUuids( + tenantUuid, + accountUuid, + UUID.randomUUID(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat( + storedActorUuids( + tenantUuid, + accountUuid, + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .isEmpty(); + assertThat(characterRepository.findById(resolvedId)).isEmpty(); + var resolved = + actorIdentityRepository + .findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + resolvedActorUuid.toString()) + .orElseThrow(); + assertThat(resolved.characterUuid()).isEqualTo(resolvedActorUuid); + assertThat(resolved.accountUuid()).isEqualTo(accountUuid); + assertThat(resolved.tenantUuid()).isEqualTo(tenantUuid); + assertThat(resolved.playableStateNamespaceId()).isEqualTo(namespaceUuid); + assertThat(resolved.playableStateScope()) + .isEqualTo(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(resolved.status().name()).isEqualTo("OWNER_RESOLVED"); + assertThat( + characterRepository.findById(legacyId).orElseThrow().getActorIdentity().status().name()) + .isEqualTo("QUARANTINED"); + assertThatThrownBy( + () -> + insertActor( + "duplicate UUID", + resolvedActorUuid, + null, + null, + null, + null, + "shared-live", + "QUARANTINED", + "OWNER_PROVENANCE_MISSING", + accountId, + tenantId)) + .isInstanceOf(org.springframework.dao.DuplicateKeyException.class) + .hasMessageContaining("ux_characters_character_uuid"); + assertThatThrownBy( + () -> + insertNamespace( + tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .isInstanceOf(org.springframework.dao.DuplicateKeyException.class) + .hasMessageContaining("pk_entity_playable_state_namespace_scopes"); + } + + private List storedActorUuids( + UUID tenantUuid, UUID accountUuid, UUID namespaceUuid, PlayableStateScope scope) { + return jdbcTemplate.queryForList( + "SELECT character_uuid FROM characters WHERE tenant_uuid = ? AND account_uuid = ? " + + "AND playable_state_namespace_id = ? AND playable_state_scope = ? " + + "AND actor_identity_status = 'OWNER_RESOLVED' " + + "AND actor_identity_quarantine_reason IS NULL ORDER BY character_uuid", + UUID.class, + tenantUuid, + accountUuid, + namespaceUuid, + scope.name()); + } + + @Test + void namespaceIdentityAndScopeAreImmutableWithoutActorReferences() { + for (PlayableStateScope scope : + new PlayableStateScope[] { + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED + }) { + UUID tenantUuid = UUID.randomUUID(); + UUID namespaceUuid = UUID.randomUUID(); + UUID changedTenantUuid = UUID.randomUUID(); + UUID changedNamespaceUuid = UUID.randomUUID(); + PlayableStateScope changedScope = + scope == PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + ? PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED + : PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + insertNamespace(tenantUuid, namespaceUuid, scope); + + assertThat( + jdbcTemplate.queryForObject( + "SELECT count(*) FROM characters WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + Integer.class, + tenantUuid, + namespaceUuid)) + .isZero(); + assertThat( + jdbcTemplate.update( + "UPDATE entity_playable_state_namespace_scopes " + + "SET tenant_uuid = ?, playable_state_namespace_id = ?, playable_state_scope = ? " + + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + tenantUuid, + namespaceUuid, + scope.name(), + tenantUuid, + namespaceUuid)) + .isOne(); + + assertNamespaceIdentityUpdateRejected( + "UPDATE entity_playable_state_namespace_scopes SET tenant_uuid = ? " + + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + changedTenantUuid, + tenantUuid, + namespaceUuid); + assertNamespaceIdentityUpdateRejected( + "UPDATE entity_playable_state_namespace_scopes SET playable_state_namespace_id = ? " + + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + changedNamespaceUuid, + tenantUuid, + namespaceUuid); + assertNamespaceIdentityUpdateRejected( + "UPDATE entity_playable_state_namespace_scopes SET playable_state_scope = ? " + + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + changedScope.name(), + tenantUuid, + namespaceUuid); + + assertThat( + jdbcTemplate.queryForObject( + "SELECT playable_state_scope FROM entity_playable_state_namespace_scopes " + + "WHERE tenant_uuid = ? AND playable_state_namespace_id = ?", + String.class, + tenantUuid, + namespaceUuid)) + .isEqualTo(scope.name()); + } + } + + @Test + void freshDefaultFlywayInstallsCompleteCombinedManifest() { + // Flyway normalizes the declared Saga sub-location into its recursive parent location. + assertThat(flyway.getConfiguration().getLocations()) + .extracting(location -> location.getDescriptor()) + .containsExactly("classpath:db/migration"); + assertThat(flyway.getConfiguration().getTable()) + .isEqualTo("flyway_schema_history_entity_management_service"); + assertThat(flyway.getConfiguration().isOutOfOrder()).isFalse(); + assertThat(flyway.info().applied()) + .filteredOn(migration -> migration.getVersion() != null) + .extracting(migration -> migration.getVersion().getVersion()) + .containsExactly( + "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", + "1010"); + assertThat(flyway.info().applied()) + .filteredOn(migration -> migration.getVersion() != null) + .extracting(migration -> migration.getScript()) + .containsExactly( + "V1__baseline.sql", + "saga/V1000__create_saga_schema.sql", + "saga/V1001__saga_instance_table.sql", + "saga/V1002__saga_step_table.sql", + "V1003__quarantine_unresolved_actor_identity.sql", + "V1004__build_actor_identity_indexes_concurrently.sql", + "V1005__validate_actor_identity_constraints.sql", + "V1006__preseeded_actor_assignment.sql", + "V1007__preseeded_assignment_owner_snapshot.sql", + "V1008__canonical_gameplay_roster_snapshots.sql", + "V1009__canonical_publication_uuid_actor_evidence.sql", + "V1010__canonical_roster_owner_counters.sql"); + assertThat(flyway.info().current().getVersion()) + .isEqualTo(MigrationVersion.fromVersion("1010")); + assertThat(flyway.info().applied()) + .extracting(migration -> migration.getState()) + .doesNotContain(MigrationState.OUT_OF_ORDER); + } + + @Test + @Timeout(value = 3, unit = TimeUnit.MINUTES) + void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() throws SQLException { + migrateLegacySchemaToParentFrontier(); + List parentHistory = readMigrationHistory(); + assertThat(parentHistory) + .extracting(MigrationHistoryEntry::version) + .containsExactly("1", "1000", "1001", "1002"); + assertThat(parentHistory) + .extracting(MigrationHistoryEntry::script) + .containsExactly( + "V1__baseline.sql", + "saga/V1000__create_saga_schema.sql", + "saga/V1001__saga_instance_table.sql", + "saga/V1002__saga_step_table.sql"); + assertThat(parentHistory) + .allSatisfy( + entry -> { + assertThat(entry.success()).isTrue(); + assertThat(entry.checksum()).isNotNull(); + }); + try (Connection connection = connectToMigrationSchema()) { + var statement = connection.createStatement(); + statement.executeUpdate( + "INSERT INTO characters (id, account_id, name, tenant_id, playable_state_key, level, experience, strength, agility, intelligence, stamina, health, mana, version, body_layout_key) " + + "VALUES (101, 81, 'Legacy Shared', 71, 'shared-live', 9, 17, 21, 22, 23, 24, 31, 32, 12, 'LEGACY_BODY'), " + + "(102, 81, 'Legacy Instance', 71, 'instance:44', 3, 7, 11, 12, 13, 14, 15, 16, 5, 'LEGACY_BODY')"); + statement.executeUpdate( + "INSERT INTO items (id, name, tenant_id, is_container) VALUES (201, 'Bag', 71, true), (202, 'Gem', 71, false)"); + statement.executeUpdate( + "INSERT INTO inventory (character_id, item_id, quantity, version) VALUES (101, 202, 6, 3)"); + statement.executeUpdate( + "INSERT INTO character_friend (character_id, friend_id, tenant_id, status) VALUES (101, 102, 71, 'pending')"); + statement.executeUpdate( + "INSERT INTO character_equipment (character_id, slot, item_id, version) VALUES (101, 'hand', 202, 4)"); + statement.executeUpdate( + "INSERT INTO actor_resource_states (id, tenant_id, character_id, stat_key, current_value, max_value, base_value, source_type, source_id, playable_state_key, version) VALUES (301, 71, 101, 'health', 31, 90, 40, 'LEGACY_SOURCE', 'resource-source', 'shared-live', 8)"); + statement.executeUpdate( + "INSERT INTO actor_active_conditions (id, tenant_id, character_id, condition_key, stack_count, source_type, source_id, started_at, expires_at, effect_payload_json, playable_state_key, version) VALUES (302, 71, 101, 'stunned', 3, 'LEGACY_SOURCE', 'condition-source', '2020-01-01T00:00:00Z', '2020-01-02T00:00:00Z', '{\"modifier\":2}', 'shared-live', 9)"); + statement.executeUpdate( + "INSERT INTO container_instances (id, tenant_id, character_id, game_instance_id, item_id, version) VALUES (401, 71, 101, '44', 201, 10)"); + statement.executeUpdate( + "INSERT INTO item_instances (id, tenant_id, character_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) VALUES (501, 71, 101, '44', NULL, 201, 'legacy', 1, 'legacy-bag', 11)"); + statement.executeUpdate( + "UPDATE container_instances SET item_instance_id = 501 WHERE id = 401"); + statement.executeUpdate( + "INSERT INTO item_instances (id, tenant_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) VALUES (502, 71, '44', 401, 202, 'legacy', 2, 'legacy-gem', 12)"); + statement.executeUpdate( + "INSERT INTO item_stacks (id, tenant_id, character_id, game_instance_id, item_id, compatibility_fingerprint, quantity, version, stack_family_key) VALUES (601, 71, 101, '44', 202, 'legacy-fingerprint', 13, 14, 'legacy-family')"); + statement.executeUpdate( + "INSERT INTO room_ground_inventory (tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) VALUES (71, '44', 'room-9', 202, 15, 16)"); + statement.executeUpdate( + "INSERT INTO item_transfer_audits (id, tenant_id, item_id, item_instance_id, quantity, verb, actor_character_id, effect_id, correlation_key, source_holder_kind, source_character_id, source_game_instance_id, destination_holder_kind, destination_game_instance_id, destination_room_instance_id) VALUES (701, 71, 202, 502, 2, 'DROP', 101, 'legacy-effect', 'legacy-correlation', 'CHARACTER', 101, '44', 'ROOM', '44', 'room-9')"); + statement.executeUpdate( + "INSERT INTO entity_mutation_effects (id, tenant_id, effect_id, operation_name, response_type, response_payload, status) VALUES (801, 71, 'legacy-effect', 'DROP', 'DropResponse', decode('cafe', 'hex'), 'APPLIED')"); + statement.close(); + } + + migrateLegacySchemaToLatest(); + + List upgradedHistory = readMigrationHistory(); + assertThat(upgradedHistory.subList(0, parentHistory.size())) + .containsExactlyElementsOf(parentHistory); + assertThat(upgradedHistory) + .extracting(MigrationHistoryEntry::version) + .containsExactly( + "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", + "1010"); + assertThat(upgradedHistory) + .extracting(MigrationHistoryEntry::script) + .containsExactly( + "V1__baseline.sql", + "saga/V1000__create_saga_schema.sql", + "saga/V1001__saga_instance_table.sql", + "saga/V1002__saga_step_table.sql", + "V1003__quarantine_unresolved_actor_identity.sql", + "V1004__build_actor_identity_indexes_concurrently.sql", + "V1005__validate_actor_identity_constraints.sql", + "V1006__preseeded_actor_assignment.sql", + "V1007__preseeded_assignment_owner_snapshot.sql", + "V1008__canonical_gameplay_roster_snapshots.sql", + "V1009__canonical_publication_uuid_actor_evidence.sql", + "V1010__canonical_roster_owner_counters.sql"); + assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); + + try (Connection connection = connectToMigrationSchema(); + var statement = connection.createStatement()) { + assertThat( + readLong( + statement, + "SELECT count(*) FROM pg_constraint " + + "WHERE conrelid = 'characters'::regclass AND convalidated " + + "AND conname IN ('ck_characters_actor_identity_status', " + + "'ck_characters_actor_identity_quarantine_reason', " + + "'ck_characters_actor_identity_uuid_non_nil', " + + "'ck_characters_actor_identity_scope', " + + "'ck_characters_owner_resolved_provenance', " + + "'fk_characters_owner_resolved_namespace_scope', " + + "'ck_characters_character_uuid_non_nil', " + + "'ux_characters_character_uuid')")) + .isEqualTo(8L); + assertThat( + readLong( + statement, + "SELECT count(*) FROM pg_index indexes " + + "JOIN pg_class index_relation ON index_relation.oid = indexes.indexrelid " + + "JOIN pg_namespace index_schema ON index_schema.oid = index_relation.relnamespace " + + "WHERE index_schema.nspname = current_schema() " + + "AND index_relation.relname IN ('ux_characters_character_uuid', " + + "'idx_characters_owner_resolved_roster') " + + "AND indexes.indisvalid AND indexes.indisready")) + .isEqualTo(2L); + assertThat( + readLong( + statement, + "SELECT count(*) FROM pg_attribute " + + "WHERE attrelid = 'characters'::regclass AND attname = 'character_uuid' " + + "AND attnotnull AND NOT attisdropped")) + .isEqualTo(1L); + try (var rows = + statement.executeQuery( + "SELECT id, account_id, name, tenant_id, playable_state_key, level, experience, strength, agility, intelligence, stamina, health, mana, version, body_layout_key, character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason FROM characters ORDER BY id")) { + assertThat(rows.next()).isTrue(); + UUID firstActorUuid = rows.getObject("character_uuid", UUID.class); + assertThat(firstActorUuid).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(rows.getLong("id")).isEqualTo(101L); + assertThat(rows.getLong("account_id")).isEqualTo(81L); + assertThat(rows.getString("name")).isEqualTo("Legacy Shared"); + assertThat(rows.getLong("tenant_id")).isEqualTo(71L); + assertThat(rows.getString("playable_state_key")).isEqualTo("shared-live"); + assertThat(rows.getInt("level")).isEqualTo(9); + assertThat(rows.getInt("experience")).isEqualTo(17); + assertThat(rows.getInt("strength")).isEqualTo(21); + assertThat(rows.getInt("agility")).isEqualTo(22); + assertThat(rows.getInt("intelligence")).isEqualTo(23); + assertThat(rows.getInt("stamina")).isEqualTo(24); + assertThat(rows.getInt("health")).isEqualTo(31); + assertThat(rows.getInt("mana")).isEqualTo(32); + assertThat(rows.getInt("version")).isEqualTo(12); + assertThat(rows.getString("body_layout_key")).isEqualTo("LEGACY_BODY"); + assertThat(rows.getObject("account_uuid")).isNull(); + assertThat(rows.getObject("tenant_uuid")).isNull(); + assertThat(rows.getObject("playable_state_namespace_id")).isNull(); + assertThat(rows.getString("playable_state_scope")).isNull(); + assertThat(rows.getString("actor_identity_status")).isEqualTo("QUARANTINED"); + assertThat(rows.getString("actor_identity_quarantine_reason")) + .isEqualTo("OWNER_PROVENANCE_MISSING"); + assertThat(rows.next()).isTrue(); + UUID secondActorUuid = rows.getObject("character_uuid", UUID.class); + assertThat(secondActorUuid).isNotNull().isNotEqualTo(firstActorUuid); + assertThat(rows.getLong("id")).isEqualTo(102L); + assertThat(rows.getLong("account_id")).isEqualTo(81L); + assertThat(rows.getLong("tenant_id")).isEqualTo(71L); + assertThat(rows.getString("playable_state_key")).isEqualTo("instance:44"); + assertThat(rows.getString("actor_identity_status")).isEqualTo("QUARANTINED"); + assertThat(rows.getObject("account_uuid")).isNull(); + assertThat(rows.getObject("playable_state_namespace_id")).isNull(); + assertThat(rows.next()).isFalse(); + } + assertThat( + readLong( + statement, + "SELECT quantity FROM inventory WHERE character_id = 101 AND item_id = 202")) + .isEqualTo(6L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', character_id, item_id, quantity, version) FROM inventory WHERE character_id = 101 AND item_id = 202")) + .isEqualTo("101|202|6|3"); + assertThat( + readString(statement, "SELECT status FROM character_friend WHERE character_id = 101")) + .isEqualTo("pending"); + assertThat( + readString( + statement, + "SELECT concat_ws('|', character_id, friend_id, tenant_id, status) FROM character_friend WHERE character_id = 101")) + .isEqualTo("101|102|71|pending"); + assertThat( + readLong( + statement, "SELECT version FROM character_equipment WHERE character_id = 101")) + .isEqualTo(4L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', character_id, slot, item_id, version) FROM character_equipment WHERE character_id = 101")) + .isEqualTo("101|hand|202|4"); + assertThat( + readLong(statement, "SELECT current_value FROM actor_resource_states WHERE id = 301")) + .isEqualTo(31L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, stat_key, current_value, max_value, base_value, source_type, source_id, playable_state_key, version) FROM actor_resource_states WHERE id = 301")) + .isEqualTo("301|71|101|health|31|90|40|LEGACY_SOURCE|resource-source|shared-live|8"); + assertThat( + readString( + statement, + "SELECT effect_payload_json FROM actor_active_conditions WHERE id = 302")) + .isEqualTo("{\"modifier\":2}"); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, condition_key, stack_count, source_type, source_id, playable_state_key, version) FROM actor_active_conditions WHERE id = 302")) + .isEqualTo("302|71|101|stunned|3|LEGACY_SOURCE|condition-source|shared-live|9"); + assertThat( + readLong( + statement, + "SELECT extract(epoch FROM started_at)::bigint FROM actor_active_conditions WHERE id = 302")) + .isEqualTo(1577836800L); + assertThat( + readLong( + statement, + "SELECT extract(epoch FROM expires_at)::bigint FROM actor_active_conditions WHERE id = 302")) + .isEqualTo(1577923200L); + assertThat(readLong(statement, "SELECT count(*) FROM item_instances WHERE id IN (501, 502)")) + .isEqualTo(2L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) FROM item_instances WHERE id = 501")) + .isEqualTo("501|71|101|44|201|legacy|1|legacy-bag|11"); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, container_instance_id, item_id, visible_ref_token, visible_ref_sequence, visible_ref, version) FROM item_instances WHERE id = 502")) + .isEqualTo("502|71|44|401|202|legacy|2|legacy-gem|12"); + assertThat( + readLong( + statement, "SELECT container_instance_id FROM item_instances WHERE id = 502")) + .isEqualTo(401L); + assertThat( + readLong( + statement, "SELECT item_instance_id FROM container_instances WHERE id = 401")) + .isEqualTo(501L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, item_id, item_instance_id, version) FROM container_instances WHERE id = 401")) + .isEqualTo("401|71|101|44|201|501|10"); + assertThat(readLong(statement, "SELECT quantity FROM item_stacks WHERE id = 601")) + .isEqualTo(13L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, character_id, game_instance_id, item_id, compatibility_fingerprint, quantity, version, stack_family_key) FROM item_stacks WHERE id = 601")) + .isEqualTo("601|71|101|44|202|legacy-fingerprint|13|14|legacy-family"); + assertThat( + readLong( + statement, + "SELECT quantity FROM room_ground_inventory WHERE room_instance_id = 'room-9'")) + .isEqualTo(15L); + assertThat( + readString( + statement, + "SELECT concat_ws('|', tenant_id, game_instance_id, room_instance_id, item_id, quantity, version) FROM room_ground_inventory WHERE room_instance_id = 'room-9'")) + .isEqualTo("71|44|room-9|202|15|16"); + assertThat( + readString( + statement, "SELECT correlation_key FROM item_transfer_audits WHERE id = 701")) + .isEqualTo("legacy-correlation"); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, item_id, item_instance_id, quantity, verb, actor_character_id, effect_id, correlation_key, source_holder_kind, source_character_id, source_game_instance_id, destination_holder_kind, destination_game_instance_id, destination_room_instance_id) FROM item_transfer_audits WHERE id = 701")) + .isEqualTo( + "701|71|202|502|2|DROP|101|legacy-effect|legacy-correlation|CHARACTER|101|44|ROOM|44|room-9"); + assertThat( + readString( + statement, + "SELECT encode(response_payload, 'hex') FROM entity_mutation_effects WHERE id = 801")) + .isEqualTo("cafe"); + assertThat( + readString( + statement, + "SELECT concat_ws('|', id, tenant_id, effect_id, operation_name, response_type, encode(response_payload, 'hex'), status) FROM entity_mutation_effects WHERE id = 801")) + .isEqualTo("801|71|legacy-effect|DROP|DropResponse|cafe|APPLIED"); + } + } + + private void insertNamespace(UUID tenantUuid, UUID namespaceUuid, PlayableStateScope scope) { + jdbcTemplate.update( + "INSERT INTO entity_playable_state_namespace_scopes " + + "(tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, ?)", + tenantUuid, + namespaceUuid, + scope.name()); + } + + private void assertNamespaceIdentityUpdateRejected(String sql, Object... arguments) { + assertThatThrownBy(() -> jdbcTemplate.update(sql, arguments)) + .hasMessageContaining("entity playable-state namespace identity is immutable"); + } + + private long insertActor( + String name, + UUID characterUuid, + UUID accountUuid, + UUID tenantUuid, + UUID namespaceUuid, + PlayableStateScope scope, + String legacyStateKey, + String status, + String quarantineReason, + long legacyAccountId, + long legacyTenantId) { + Long actorId = + jdbcTemplate.queryForObject( + "INSERT INTO characters (account_id, name, tenant_id, playable_state_key, character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + Long.class, + legacyAccountId, + name, + legacyTenantId, + legacyStateKey, + characterUuid, + accountUuid, + tenantUuid, + namespaceUuid, + scope == null ? null : scope.name(), + status, + quarantineReason); + return Objects.requireNonNull( + actorId, "Character INSERT ... RETURNING id must return the inserted actor ID"); + } + + private void migrateLegacySchemaToParentFrontier() throws SQLException { + testServiceSchema = "rai_" + UUID.randomUUID().toString().replace("-", ""); + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + testServiceSchema); + } + Flyway parentFlyway = migrationFlyway().target(MigrationVersion.fromVersion("1002")).load(); + assertThat(parentFlyway.getConfiguration().isOutOfOrder()).isFalse(); + parentFlyway.migrate(); + assertThat(parentFlyway.info().current().getVersion()) + .isEqualTo(MigrationVersion.fromVersion("1002")); + } + + private void migrateLegacySchemaToLatest() { + Flyway upgradeFlyway = migrationFlyway().load(); + assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse(); + upgradeFlyway.migrate(); + assertThat(upgradeFlyway.info().current().getVersion()) + .isEqualTo(MigrationVersion.fromVersion("1010")); + assertThat(upgradeFlyway.info().applied()) + .extracting(migration -> migration.getState()) + .doesNotContain(MigrationState.OUT_OF_ORDER); + } + + private FluentConfiguration migrationFlyway() { + FluentConfiguration configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(testServiceSchema) + .defaultSchema(testServiceSchema) + .table("flyway_schema_history_" + testServiceSchema) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .placeholders(Map.of("serviceSchema", testServiceSchema)); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + return configuration.jdbcProperties( + Map.of("options", "-c lock_timeout=30s -c statement_timeout=120s")); + } + + private Connection connectToMigrationSchema() throws SQLException { + Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + try (var statement = connection.createStatement()) { + statement.execute("SET search_path TO " + testServiceSchema); + } + return connection; + } + + private List readMigrationHistory() throws SQLException { + List history = new ArrayList<>(); + try (Connection connection = connectToMigrationSchema(); + var statement = connection.createStatement(); + var rows = + statement.executeQuery( + "SELECT installed_rank, version, script, checksum, success FROM flyway_schema_history_" + + testServiceSchema + + " WHERE version IS NOT NULL ORDER BY installed_rank")) { + while (rows.next()) { + history.add( + new MigrationHistoryEntry( + rows.getInt("installed_rank"), + rows.getString("version"), + rows.getString("script"), + rows.getObject("checksum", Integer.class), + rows.getBoolean("success"))); + } + } + return history; + } + + private record MigrationHistoryEntry( + int installedRank, String version, String script, Integer checksum, boolean success) {} + + private long readLong(java.sql.Statement statement, String sql) throws SQLException { + try (var rows = statement.executeQuery(sql)) { + assertThat(rows.next()).isTrue(); + return rows.getLong(1); + } + } + + private String readString(java.sql.Statement statement, String sql) throws SQLException { + try (var rows = statement.executeQuery(sql)) { + assertThat(rows.next()).isTrue(); + return rows.getString(1); + } + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java new file mode 100644 index 0000000000..b83ab5338e --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.entitymanagement; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.flyway.autoconfigure.FlywayProperties; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.FileSystemResource; + +class FlywayPostgresqlLockConfigurationTest { + @Test + void identityValidationScansFinishBeforeStrongLockFinalization() throws IOException { + String migration = + Files.readString( + Path.of( + "src/main/resources/db/migration/V1005__validate_actor_identity_constraints.sql")); + int lastValidation = migration.lastIndexOf("VALIDATE CONSTRAINT "); + int setNotNull = migration.indexOf("ALTER COLUMN character_uuid SET NOT NULL"); + int dropProofCheck = migration.indexOf("DROP CONSTRAINT ck_characters_character_uuid_nonnull"); + + assertThat(lastValidation).isGreaterThanOrEqualTo(0); + assertThat(setNotNull).isGreaterThan(lastValidation); + assertThat(dropProofCheck).isGreaterThan(setNotNull); + assertThat(migration).contains("VALIDATE CONSTRAINT ck_characters_character_uuid_nonnull"); + } + + @Test + void allServiceProfilesBindSessionLevelPostgresqlAdvisoryLocks() throws IOException { + for (Path resourcePath : + List.of( + Path.of("src/main/resources/application.yml"), + Path.of("src/main/resources/application-prod.yml"), + Path.of("src/test/resources/application.yml"))) { + var propertySource = + new YamlPropertySourceLoader() + .load(resourcePath.toString(), new FileSystemResource(resourcePath.toFile())) + .getFirst(); + var environment = new StandardEnvironment(); + environment.getPropertySources().addFirst(propertySource); + + FlywayProperties properties = + Binder.get(environment) + .bind("spring.flyway", FlywayProperties.class) + .orElseThrow( + () -> new AssertionError("Flyway settings did not bind from " + resourcePath)); + + assertThat(properties.getPostgresql().getTransactionalLock()) + .as("PostgreSQL transactional advisory locks in %s", resourcePath) + .isFalse(); + } + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java new file mode 100644 index 0000000000..e4ec45fe07 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java @@ -0,0 +1,108 @@ +package net.firedevops.firemud.entitymanagement.entity; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; + +class ActorIdentityValueTest { + private static final UUID ACTOR_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID NAMESPACE_UUID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void parsesOnlyCompleteNonNilUuidValues() { + assertEquals(ACTOR_UUID, ActorIdentity.parseRequiredUuid(ACTOR_UUID.toString(), "actor")); + assertThrows( + IllegalArgumentException.class, () -> ActorIdentity.parseRequiredUuid(null, "actor")); + assertThrows( + IllegalArgumentException.class, + () -> ActorIdentity.parseRequiredUuid("not-a-uuid", "actor")); + assertThrows( + IllegalArgumentException.class, + () -> ActorIdentity.parseRequiredUuid("00000000-0000-0000-0000-000000000000", "actor")); + } + + @Test + void ownerResolvedIdentityRequiresExactAccountTenantNamespaceAndScope() { + var identity = + new ActorIdentity( + ACTOR_UUID, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + ActorIdentityStatus.OWNER_RESOLVED, + null); + assertEquals(ActorIdentityStatus.OWNER_RESOLVED, identity.status()); + + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, + null, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + ActorIdentityStatus.OWNER_RESOLVED, + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED, + ActorIdentityStatus.OWNER_RESOLVED, + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + ActorIdentityStatus.OWNER_RESOLVED, + "LEGACY_IDENTITY")); + } + + @Test + void quarantineCanRetainIncompleteSourceProvenanceWithoutCreatingAnAlias() { + var quarantined = + new ActorIdentity( + ACTOR_UUID, + null, + null, + null, + null, + ActorIdentityStatus.QUARANTINED, + "OWNER_PROVENANCE_MISSING"); + assertEquals(ActorIdentityStatus.QUARANTINED, quarantined.status()); + + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + new UUID(0L, 0L), + null, + null, + null, + null, + ActorIdentityStatus.QUARANTINED, + "OWNER_PROVENANCE_MISSING")); + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, ACCOUNT_UUID, null, null, null, ActorIdentityStatus.QUARANTINED, " ")); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java new file mode 100644 index 0000000000..9c5ae04f73 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java @@ -0,0 +1,534 @@ +package net.firedevops.firemud.entitymanagement.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalGameplayRosterSelectedAssignmentServiceTest { + @Test + void resolvesCurrentTargetThenReturnsOnlyTheExactHistoricalAssignmentReference() { + assertResolvesCurrentTarget(target()); + assertResolvesCurrentTarget( + withScope(target(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + } + + private static void assertResolvesCurrentTarget(CanonicalGameplayRosterTarget target) { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + CanonicalGameplayRosterOwnerEvidence evidence = + evidence(ownerRequest, request.expectedTarget()); + PreseededActorAssignmentExpectedTarget assignmentTarget = + assignmentTarget(request.expectedTarget()); + PreseededActorAssignmentReceipt receipt = receipt(request, assignmentTarget); + when(ownerPort.resolveCurrentTarget(ownerRequest)).thenReturn(evidence); + when(repository.readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot())) + .thenReturn(snapshot(request)); + when(repository.readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + assignmentTarget, + request.expectedTarget().publishedOwnerProofDigest())) + .thenReturn(Optional.of(receipt)); + + CanonicalGameplayRosterSelectedAssignmentReference result = service.read(request); + + assertThat(result.requestUuid()).isEqualTo(request.requestUuid()); + assertThat(result.canonicalAccountUuid()).isEqualTo(request.canonicalAccountUuid()); + assertThat(result.selectedCharacterUuid()).isEqualTo(request.selectedCharacterUuid()); + assertThat(result.target()).isEqualTo(request.expectedTarget()); + assertThat(result.snapshot()).isEqualTo(request.expectedSnapshot()); + assertThat(result.assignmentUuid()).isEqualTo(receipt.assignmentUuid()); + assertThat(result.intentDigest()).isEqualTo(receipt.intentDigest()); + verify(ownerPort).resolveCurrentTarget(ownerRequest); + verify(repository) + .readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot()); + verify(repository) + .readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + assignmentTarget, + request.expectedTarget().publishedOwnerProofDigest()); + } + + @Test + void ownerFailureAndRequestAccountOrTargetMismatchFailBeforeRepositoryRead() { + CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target()); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + CanonicalGameplayRosterOwnerEvidencePort unavailableOwnerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository unavailableRepository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService unavailableService = + new CanonicalGameplayRosterSelectedAssignmentService( + unavailableOwnerPort, unavailableRepository); + + when(unavailableOwnerPort.resolveCurrentTarget(ownerRequest)) + .thenThrow( + new CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException()); + assertThatThrownBy(() -> unavailableService.read(request)) + .isInstanceOf( + CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException.class); + verifyNoInteractions(unavailableRepository); + + assertOwnerMismatchBeforeRepository( + request, + new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), + UUID.randomUUID(), + request.expectedTarget(), + Instant.parse("2026-10-01T00:00:00Z")), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + assertOwnerMismatchBeforeRepository( + request, + new CanonicalGameplayRosterOwnerEvidence( + UUID.randomUUID(), + request.canonicalAccountUuid(), + request.expectedTarget(), + Instant.parse("2026-10-01T00:00:00Z")), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + assertOwnerMismatchBeforeRepository( + request, + evidence(ownerRequest, withNamespace(request.expectedTarget(), UUID.randomUUID())), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + assertOwnerMismatchBeforeRepository( + request, + evidence( + ownerRequest, + withScope(request.expectedTarget(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + CanonicalGameplayRosterSelectedAssignmentReadRequest isolatedRequest = + request(withScope(target(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + CanonicalGameplayRosterReadRequest isolatedOwnerRequest = + new CanonicalGameplayRosterReadRequest( + isolatedRequest.requestUuid(), + isolatedRequest.canonicalAccountUuid(), + isolatedRequest.expectedTarget(), + isolatedRequest.playerExecutionContext()); + assertOwnerMismatchBeforeRepository( + isolatedRequest, + evidence( + isolatedOwnerRequest, + withScope( + isolatedRequest.expectedTarget(), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + assertOwnerMismatchBeforeRepository( + request, + evidence(ownerRequest, withCatalogRevision(request.expectedTarget(), 4L)), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + } + + @Test + void unsupportedCallerPolicyFailsBeforeOwnerResolution() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + + assertThatThrownBy( + () -> + service.read( + request( + withPolicy(target(), CanonicalGameplayRosterEntryPolicy.AUTO_PROVISIONED)))) + .isInstanceOf(UnsupportedOperationException.class); + verifyNoInteractions(ownerPort, repository); + } + + @Test + void ambientTransactionOrSynchronizationFailsBeforeOwnerAndRepositoryAccess() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target()); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_PRESEEDED_ASSIGNMENT_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } finally { + TransactionSynchronizationManager.clear(); + } + verifyNoInteractions(ownerPort, repository); + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_PRESEEDED_ASSIGNMENT_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } finally { + TransactionSynchronizationManager.clear(); + } + verifyNoInteractions(ownerPort, repository); + } + + @Test + void missingOrInvalidStoredAssignmentFailsClosed() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target()); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + when(ownerPort.resolveCurrentTarget(ownerRequest)) + .thenReturn(evidence(ownerRequest, request.expectedTarget())); + when(repository.readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot())) + .thenReturn(snapshot(request)); + when(repository.readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + assignmentTarget(request.expectedTarget()), + request.expectedTarget().publishedOwnerProofDigest())) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_PRESEEDED_ASSIGNMENT_UNAVAILABLE"); + } + + @Test + void isolatedSelectionRejectsSharedAssignmentReceipt() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterSelectedAssignmentReadRequest request = + request(withScope(target(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + PreseededActorAssignmentExpectedTarget isolatedTarget = + assignmentTarget(request.expectedTarget()); + PreseededActorAssignmentExpectedTarget sharedTarget = + assignmentTarget( + withScope(request.expectedTarget(), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + when(ownerPort.resolveCurrentTarget(ownerRequest)) + .thenReturn(evidence(ownerRequest, request.expectedTarget())); + when(repository.readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot())) + .thenReturn(snapshot(request)); + when(repository.readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + isolatedTarget, + request.expectedTarget().publishedOwnerProofDigest())) + .thenReturn(Optional.of(receipt(request, sharedTarget))); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_PRESEEDED_ASSIGNMENT_RECEIPT_MISMATCH"); + } + + @Test + void actorAbsentFromExpectedSnapshotFailsBeforeReceiptRead() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterSelectedAssignmentReadRequest request = request(target()); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + when(ownerPort.resolveCurrentTarget(ownerRequest)) + .thenReturn(evidence(ownerRequest, request.expectedTarget())); + when(repository.readCurrentCanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), request.expectedTarget(), request.expectedSnapshot())) + .thenReturn( + new CanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), + request.expectedSnapshot().snapshotUuid(), + request.expectedSnapshot().snapshotDigest(), + request.expectedTarget(), + java.util.List.of(new CanonicalGameplayRosterActor(UUID.randomUUID(), "Other")))); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_PRESEEDED_ASSIGNMENT_NOT_IN_EXPECTED_SNAPSHOT"); + verify(repository, never()) + .readSelectedPreseededActorAssignmentReceipt( + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + assignmentTarget(request.expectedTarget()), + request.expectedTarget().publishedOwnerProofDigest()); + } + + private static CanonicalGameplayRosterSelectedAssignmentReadRequest request( + CanonicalGameplayRosterTarget target) { + UUID requestUuid = UUID.randomUUID(); + UUID accountUuid = UUID.randomUUID(); + UUID selectedUuid = UUID.randomUUID(); + return new CanonicalGameplayRosterSelectedAssignmentReadRequest( + requestUuid, + accountUuid, + selectedUuid, + target, + new CanonicalGameplayRosterSnapshotReference(UUID.randomUUID(), "a".repeat(64)), + executionContext(target, requestUuid, accountUuid, selectedUuid)); + } + + private static CanonicalGameplayRosterExecutionContext executionContext( + CanonicalGameplayRosterTarget target, + UUID requestUuid, + UUID accountUuid, + UUID characterUuid) { + return new CanonicalGameplayRosterExecutionContext( + accountUuid, + target.tenantUuid(), + target.playableStateNamespaceId(), + target.gameInstanceUuid(), + characterUuid, + UUID.randomUUID(), + target.realmUuid(), + requestUuid, + target.playableStateScope()); + } + + private static CanonicalGameplayRosterSnapshot snapshot( + CanonicalGameplayRosterSelectedAssignmentReadRequest request) { + return new CanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), + request.expectedSnapshot().snapshotUuid(), + request.expectedSnapshot().snapshotDigest(), + request.expectedTarget(), + java.util.List.of( + new CanonicalGameplayRosterActor(request.selectedCharacterUuid(), "Selected Actor"))); + } + + private static void assertOwnerMismatchBeforeRepository( + CanonicalGameplayRosterSelectedAssignmentReadRequest request, + CanonicalGameplayRosterOwnerEvidence evidence, + Class expectedType, + String expectedMessage) { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterSelectedAssignmentService service = + new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); + CanonicalGameplayRosterReadRequest ownerRequest = + new CanonicalGameplayRosterReadRequest( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + request.playerExecutionContext()); + when(ownerPort.resolveCurrentTarget(ownerRequest)).thenReturn(evidence); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(expectedType) + .hasMessage(expectedMessage); + verifyNoInteractions(repository); + } + + private static CanonicalGameplayRosterOwnerEvidence evidence( + CanonicalGameplayRosterReadRequest request, CanonicalGameplayRosterTarget target) { + return new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), + request.canonicalAccountUuid(), + target, + Instant.parse("2026-10-01T00:00:00Z")); + } + + private static CanonicalGameplayRosterTarget target() { + return new CanonicalGameplayRosterTarget( + UUID.randomUUID(), + UUID.randomUUID(), + "world", + "realm", + UUID.randomUUID(), + 3L, + 17L, + 29L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "1".repeat(64), + "release/test", + "2".repeat(64), + "4".repeat(64), + UUID.randomUUID(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + } + + private static PreseededActorAssignmentExpectedTarget assignmentTarget( + CanonicalGameplayRosterTarget target) { + return new PreseededActorAssignmentExpectedTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope()); + } + + private static PreseededActorAssignmentReceipt receipt( + CanonicalGameplayRosterSelectedAssignmentReadRequest request, + PreseededActorAssignmentExpectedTarget target) { + UUID assignmentUuid = UUID.randomUUID(); + PreseededActorCorePayload corePayload = + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Selected Actor"); + String intentDigest = + new PreseededActorAssignmentRequest( + assignmentUuid, request.canonicalAccountUuid(), corePayload, target) + .mutationIntentDigest(); + return new PreseededActorAssignmentReceipt( + assignmentUuid, + request.canonicalAccountUuid(), + request.selectedCharacterUuid(), + intentDigest, + target, + corePayload, + 1, + "dev", + 23L, + "ACCOUNT_DATABASE_INSERT", + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-01T00:00:00Z"), + 4L, + "5".repeat(64), + "6".repeat(64), + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + request.expectedTarget().publishedOwnerProofDigest(), + target.publishedReleaseBundleRef(), + "PRESEEDED_ONLY", + "ASSIGNED"); + } + + private static CanonicalGameplayRosterTarget withNamespace( + CanonicalGameplayRosterTarget target, UUID namespaceUuid) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + target.pointerVersion(), + target.activeWorldEpoch(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + namespaceUuid, + target.playableStateScope(), + target.entryPolicy()); + } + + private static CanonicalGameplayRosterTarget withScope( + CanonicalGameplayRosterTarget target, PlayableStateScope scope) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + target.pointerVersion(), + target.activeWorldEpoch(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + scope, + target.entryPolicy()); + } + + private static CanonicalGameplayRosterTarget withCatalogRevision( + CanonicalGameplayRosterTarget target, long catalogRevision) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + catalogRevision, + target.pointerVersion(), + target.activeWorldEpoch(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.entryPolicy()); + } + + private static CanonicalGameplayRosterTarget withPolicy( + CanonicalGameplayRosterTarget target, CanonicalGameplayRosterEntryPolicy policy) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + target.pointerVersion(), + target.activeWorldEpoch(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + policy); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java new file mode 100644 index 0000000000..1b5f2b3e43 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java @@ -0,0 +1,318 @@ +package net.firedevops.firemud.entitymanagement.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalGameplayRosterServiceTest { + @Test + void exactOwnerResolvedPreseededTargetReadsPersistedSnapshot() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + CanonicalGameplayRosterReadRequest request = request(target()); + CanonicalGameplayRosterOwnerEvidence evidence = evidence(request, request.expectedTarget()); + CanonicalGameplayRosterSnapshot expected = + new CanonicalGameplayRosterSnapshot( + request.canonicalAccountUuid(), + UUID.randomUUID(), + "a".repeat(64), + request.expectedTarget(), + List.of(new CanonicalGameplayRosterActor(UUID.randomUUID(), "Persisted Actor"))); + when(ownerPort.resolveCurrentTarget(request)).thenReturn(evidence); + when(repository.captureCanonicalGameplayRosterSnapshot(request, evidence)).thenReturn(expected); + + assertThat(service.read(request)).isEqualTo(expected); + + verify(ownerPort).resolveCurrentTarget(request); + verify(repository).captureCanonicalGameplayRosterSnapshot(request, evidence); + } + + @Test + void unsupportedEntryPoliciesFailBeforeOwnerReadsOrRosterLookup() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + + assertThatThrownBy( + () -> + service.read( + request( + withPolicy(target(), CanonicalGameplayRosterEntryPolicy.PLAYER_CREATED)))) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_ENTRY_POLICY_UNSUPPORTED"); + assertThatThrownBy( + () -> + service.read( + request( + withPolicy(target(), CanonicalGameplayRosterEntryPolicy.AUTO_PROVISIONED)))) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + service.read( + request(withPolicy(target(), CanonicalGameplayRosterEntryPolicy.UNSPECIFIED)))) + .isInstanceOf(UnsupportedOperationException.class); + + verifyNoInteractions(ownerPort, repository); + } + + @Test + void independentlyResolvedCrossNamespaceTargetIsRejectedBeforeRepositoryRead() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + CanonicalGameplayRosterReadRequest request = request(target()); + CanonicalGameplayRosterTarget differentNamespace = + new CanonicalGameplayRosterTarget( + request.expectedTarget().tenantUuid(), + request.expectedTarget().realmUuid(), + request.expectedTarget().worldSlug(), + request.expectedTarget().realmSlug(), + request.expectedTarget().gameInstanceUuid(), + request.expectedTarget().catalogRevision(), + request.expectedTarget().pointerVersion(), + request.expectedTarget().activeWorldEpoch(), + request.expectedTarget().canonicalVersionUuid(), + request.expectedTarget().publishedPolicyDigest(), + request.expectedTarget().publishedReleaseBundleRef(), + request.expectedTarget().admissionPointerSnapshotDigest(), + request.expectedTarget().publishedOwnerProofDigest(), + UUID.randomUUID(), + request.expectedTarget().playableStateScope(), + request.expectedTarget().entryPolicy()); + when(ownerPort.resolveCurrentTarget(request)).thenReturn(evidence(request, differentNamespace)); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_OWNER_TARGET_MISMATCH"); + + verify(ownerPort).resolveCurrentTarget(request); + verifyNoInteractions(repository); + } + + @Test + void independentlyResolvedChangedOwnerCountersAreRejectedBeforeRepositoryRead() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + CanonicalGameplayRosterReadRequest request = request(target()); + CanonicalGameplayRosterTarget changedPointer = + withCounters( + request.expectedTarget(), + request.expectedTarget().pointerVersion() + 1, + request.expectedTarget().activeWorldEpoch()); + when(ownerPort.resolveCurrentTarget(request)).thenReturn(evidence(request, changedPointer)); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_OWNER_TARGET_MISMATCH"); + + verify(ownerPort).resolveCurrentTarget(request); + verifyNoInteractions(repository); + } + + @Test + void independentlyResolvedChangedActiveWorldEpochIsRejectedBeforeRepositoryRead() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + CanonicalGameplayRosterReadRequest request = request(target()); + CanonicalGameplayRosterTarget changedEpoch = + withCounters( + request.expectedTarget(), + request.expectedTarget().pointerVersion(), + request.expectedTarget().activeWorldEpoch() + 1); + when(ownerPort.resolveCurrentTarget(request)).thenReturn(evidence(request, changedEpoch)); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_OWNER_TARGET_MISMATCH"); + + verify(ownerPort).resolveCurrentTarget(request); + verifyNoInteractions(repository); + } + + @Test + void canonicalRosterDigestBindsPointerVersionAndActiveWorldEpoch() { + UUID accountUuid = UUID.randomUUID(); + CanonicalGameplayRosterTarget exactTarget = target(); + List actors = + List.of(new CanonicalGameplayRosterActor(UUID.randomUUID(), "Actor")); + + String exactDigest = + CanonicalGameplayRosterSnapshotDigest.compute(accountUuid, exactTarget, actors); + String changedPointerDigest = + CanonicalGameplayRosterSnapshotDigest.compute( + accountUuid, + withCounters( + exactTarget, exactTarget.pointerVersion() + 1, exactTarget.activeWorldEpoch()), + actors); + String changedEpochDigest = + CanonicalGameplayRosterSnapshotDigest.compute( + accountUuid, + withCounters( + exactTarget, exactTarget.pointerVersion(), exactTarget.activeWorldEpoch() + 1), + actors); + + assertThat(changedPointerDigest).isNotEqualTo(exactDigest); + assertThat(changedEpochDigest).isNotEqualTo(exactDigest); + assertThat(changedEpochDigest).isNotEqualTo(changedPointerDigest); + } + + @Test + void missingCurrentOwnerProducerFailsClosedWithoutRepositoryLookup() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + request -> { + throw new CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException(); + }; + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + + assertThatThrownBy(() -> service.read(request(target()))) + .isInstanceOf( + CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException.class); + + verifyNoInteractions(repository); + } + + @Test + void ownerReadCannotRunInsideAmbientTransactionOrSynchronization() { + CanonicalGameplayRosterOwnerEvidencePort ownerPort = + mock(CanonicalGameplayRosterOwnerEvidencePort.class); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterService service = + new CanonicalGameplayRosterService(ownerPort, repository); + CanonicalGameplayRosterReadRequest request = request(target()); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } finally { + TransactionSynchronizationManager.clear(); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_OWNER_READ_REQUIRES_NO_AMBIENT_TRANSACTION"); + } finally { + TransactionSynchronizationManager.clear(); + } + verifyNoInteractions(ownerPort, repository); + } + + private static CanonicalGameplayRosterReadRequest request(CanonicalGameplayRosterTarget target) { + UUID requestUuid = UUID.randomUUID(); + UUID accountUuid = UUID.randomUUID(); + return new CanonicalGameplayRosterReadRequest( + requestUuid, + accountUuid, + target, + new CanonicalGameplayRosterExecutionContext( + accountUuid, + target.tenantUuid(), + target.playableStateNamespaceId(), + target.gameInstanceUuid(), + null, + UUID.randomUUID(), + target.realmUuid(), + requestUuid, + target.playableStateScope())); + } + + private static CanonicalGameplayRosterOwnerEvidence evidence( + CanonicalGameplayRosterReadRequest request, CanonicalGameplayRosterTarget target) { + return new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), + request.canonicalAccountUuid(), + target, + Instant.parse("2026-10-01T00:00:00Z")); + } + + private static CanonicalGameplayRosterTarget target() { + return new CanonicalGameplayRosterTarget( + UUID.randomUUID(), + UUID.randomUUID(), + "world", + "realm", + UUID.randomUUID(), + 3L, + 17L, + 29L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "1".repeat(64), + "release/test", + "2".repeat(64), + "3".repeat(64), + UUID.randomUUID(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + } + + private static CanonicalGameplayRosterTarget withPolicy( + CanonicalGameplayRosterTarget target, CanonicalGameplayRosterEntryPolicy policy) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + target.pointerVersion(), + target.activeWorldEpoch(), + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + policy); + } + + private static CanonicalGameplayRosterTarget withCounters( + CanonicalGameplayRosterTarget target, long pointerVersion, long activeWorldEpoch) { + return new CanonicalGameplayRosterTarget( + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + pointerVersion, + activeWorldEpoch, + target.canonicalVersionUuid(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.entryPolicy()); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java new file mode 100644 index 0000000000..1dfc81483b --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java @@ -0,0 +1,686 @@ +package net.firedevops.firemud.entitymanagement.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; + +class PreseededActorAssignmentServiceTest { + private static final UUID ASSIGNMENT_UUID = + UUID.fromString("10000000-0000-4000-8000-000000000001"); + private static final UUID ACCOUNT_UUID = UUID.fromString("20000000-0000-4000-8000-000000000002"); + private static final UUID TENANT_UUID = UUID.fromString("30000000-0000-4000-8000-000000000003"); + private static final UUID REALM_UUID = UUID.fromString("40000000-0000-4000-8000-000000000004"); + private static final UUID NAMESPACE_UUID = + UUID.fromString("50000000-0000-4000-8000-000000000005"); + private static final UUID CHARACTER_UUID = + UUID.fromString("70000000-0000-4000-8000-000000000007"); + + @Test + void requiresDedicatedRunOwnedActionBeforeCallingAnyOwnerOrStorageBoundary() { + RunOwnedPreseededAssignmentAuthority runAuthority = + new RunOwnedPreseededAssignmentAuthority() { + @Override + public void requireAuthorized( + PreseededActorAssignmentRequest request, Action dedicatedAction) { + assertThat(dedicatedAction).isEqualTo(Action.PRESEEDED_ACTOR_ASSIGNMENT); + assertThat(request.corePayload().actorKind()) + .isEqualTo(PreseededActorCorePayload.ActorKind.PLAYER); + throw new IllegalStateException("fixture capability did not grant this action"); + } + + @Override + public void requireTargetBoundAuthorized( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence exactTarget, + Action dedicatedAction) { + throw new AssertionError("target grant check must follow initial action grant"); + } + }; + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("did not grant this action"); + + verifyNoInteractions(accountClient, ownerPort, characterRepository); + } + + @Test + void bindsDedicatedGrantToExactCurrentTargetAndCorePayloadBeforePersistingActor() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + PreseededActorAssignmentRequest request = request(); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentOwnerEvidence target = ownerEvidence(); + PreseededActorAssignmentResult persisted = + new PreseededActorAssignmentResult( + ASSIGNMENT_UUID, + PreseededActorAssignmentResult.Outcome.ASSIGNED, + CHARACTER_UUID, + "a".repeat(64)); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request, accountProof, stagingEvidence())) + .thenReturn(target); + when(characterRepository.assignPreseededActor( + eq(request), eq(target), eq(accountProof), any(String.class))) + .thenReturn(persisted); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThat(service.assign(request())).isEqualTo(persisted); + + verify(runAuthority) + .requireAuthorized( + request, RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + verify(accountClient) + .resolveRuntimeAccountIdentity(ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString()); + verify(ownerPort).resolveCurrentEligibleTarget(request, accountProof, stagingEvidence()); + verify(runAuthority) + .requireTargetBoundAuthorized( + request, + target, + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + verify(characterRepository) + .assignPreseededActor(eq(request), eq(target), eq(accountProof), any(String.class)); + } + + @Test + void changedGrantTargetOrPayloadIsRejectedBeforeRepositoryReplay() { + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentRequest request = request(); + PreseededActorAssignmentOwnerEvidence target = ownerEvidence(); + RunOwnedPreseededAssignmentAuthority runAuthority = + new RunOwnedPreseededAssignmentAuthority() { + @Override + public void requireAuthorized( + PreseededActorAssignmentRequest authorizedRequest, Action dedicatedAction) { + assertThat(authorizedRequest).isEqualTo(request); + assertThat(dedicatedAction).isEqualTo(Action.PRESEEDED_ACTOR_ASSIGNMENT); + } + + @Override + public void requireTargetBoundAuthorized( + PreseededActorAssignmentRequest authorizedRequest, + PreseededActorAssignmentOwnerEvidence currentTarget, + Action dedicatedAction) { + assertThat(authorizedRequest).isEqualTo(request); + assertThat(currentTarget).isEqualTo(target); + assertThat(dedicatedAction).isEqualTo(Action.PRESEEDED_ACTOR_ASSIGNMENT); + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_GRANT_INTENT_MISMATCH"); + } + }; + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request, accountProof, stagingEvidence())) + .thenReturn(target); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_GRANT_INTENT_MISMATCH"); + + verifyNoInteractions(characterRepository); + } + + @Test + void rejectsUnknownAccountProofBeforeReadingAssignmentTarget() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn( + new RuntimeAccountIdentityEvidence( + 1, + "dev", + UUID.fromString("80000000-0000-4000-8000-000000000008"), + ACCOUNT_UUID, + 23L, + "ACCOUNT_DATABASE_INSERT")); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_ACCOUNT_IDENTITY_PROOF_MISMATCH"); + + verify(ownerPort, never()).resolveCurrentEligibleTarget(any(), any(), any()); + verifyNoInteractions(characterRepository); + } + + @Test + void deniesIneligibleAccountSnapshotBeforeGameSessionOwnerReadOrAllocation() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorStagingEligibilityPort stagingPort = + mock(PreseededActorStagingEligibilityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof()); + when(stagingPort.resolvePreseededActorStagingEligibility( + ACCOUNT_UUID.toString(), TENANT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(stagingEvidence(false)); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort, ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_ACCOUNT_NOT_CURRENTLY_ELIGIBLE"); + + verifyNoInteractions(ownerPort, characterRepository); + } + + @Test + void rejectsOwnerEvidenceNotBoundToTheExactAccountStagingSnapshot() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentRequest request = request(); + PreseededActorAssignmentOwnerEvidence mismatchedTarget = + ownerEvidenceWithAccountSnapshotDigest("5".repeat(64)); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request, accountProof, stagingEvidence())) + .thenReturn(mismatchedTarget); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_ACCOUNT_STAGING_EVIDENCE_MISMATCH"); + + verify(runAuthority, never()).requireTargetBoundAuthorized(any(), any(), any()); + verifyNoInteractions(characterRepository); + } + + @Test + void deniesIneligibleOwnerEvidenceBeforeTargetGrantOrRepositoryAllocation() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentOwnerEvidence ineligible = + new PreseededActorAssignmentOwnerEvidence( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + PreseededActorAssignmentOwnerEvidence.Eligibility.INELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 9L, + "1".repeat(64), + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "3".repeat(64), + "4".repeat(64), + "release-bundle/test"); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request(), accountProof, stagingEvidence())) + .thenReturn(ineligible); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_ACCOUNT_NOT_CURRENTLY_ELIGIBLE"); + + verify(runAuthority, never()).requireTargetBoundAuthorized(any(), any(), any()); + verify(characterRepository, never()).assignPreseededActor(any(), any(), any(), any()); + } + + @Test + void deniesAbsentOwnerProofBeforeRepositoryAllocation() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request(), accountProof, stagingEvidence())) + .thenReturn(null); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_OWNER_PROOF_MISMATCH"); + + verify(characterRepository, never()).assignPreseededActor(any(), any(), any(), any()); + } + + @Test + void deniesUnavailableOwnerEvidenceBeforeRepositoryAllocation() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request(), accountProof, stagingEvidence())) + .thenThrow(new IllegalStateException("PRESEEDED_ASSIGNMENT_OWNER_EVIDENCE_UNAVAILABLE")); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_OWNER_EVIDENCE_UNAVAILABLE"); + + verifyNoInteractions(characterRepository); + } + + @Test + void rejectsEveryChangedExpectedTargetFieldBeforeRepositoryReplay() { + for (int changedField = 0; changedField < 11; changedField++) { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = + mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentOwnerEvidence changedTarget = changedTarget(changedField); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(request(), accountProof, stagingEvidence())) + .thenReturn(changedTarget); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThatThrownBy(() -> service.assign(request())) + .as("changed expected target field index %s", changedField) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + + verify(runAuthority, never()).requireTargetBoundAuthorized(any(), any(), any()); + verifyNoInteractions(characterRepository); + } + } + + @Test + void exactReplayReturnsStoredActorOnlyAfterGrantAndOwnerChecksForCompleteTuple() { + RunOwnedPreseededAssignmentAuthority runAuthority = + mock(RunOwnedPreseededAssignmentAuthority.class); + PreseededActorAccountIdentityPort accountClient = mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerPort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + PreseededActorAssignmentRequest exactRequest = request(); + RuntimeAccountIdentityEvidence accountProof = accountProof(); + PreseededActorAssignmentOwnerEvidence exactTarget = ownerEvidence(); + PreseededActorAssignmentResult storedReplay = + new PreseededActorAssignmentResult( + ASSIGNMENT_UUID, + PreseededActorAssignmentResult.Outcome.ASSIGNED, + CHARACTER_UUID, + "a".repeat(64)); + when(accountClient.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenReturn(accountProof); + when(ownerPort.resolveCurrentEligibleTarget(exactRequest, accountProof, stagingEvidence())) + .thenReturn(exactTarget); + when(characterRepository.assignPreseededActor( + eq(exactRequest), eq(exactTarget), eq(accountProof), any(String.class))) + .thenReturn(storedReplay); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + runAuthority, accountClient, stagingPort(), ownerPort, characterRepository); + + assertThat(service.assign(exactRequest)).isEqualTo(storedReplay); + assertThat(service.assign(exactRequest)).isEqualTo(storedReplay); + + verify(runAuthority, times(2)) + .requireAuthorized( + exactRequest, RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + verify(runAuthority, times(2)) + .requireTargetBoundAuthorized( + exactRequest, + exactTarget, + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + verify(characterRepository, times(2)) + .assignPreseededActor( + eq(exactRequest), eq(exactTarget), eq(accountProof), any(String.class)); + } + + @Test + void intentDigestBindsFullTargetAndPayloadButIgnoresEligibilityRefreshEvidence() { + PreseededActorAssignmentRequest request = request(); + PreseededActorAssignmentOwnerEvidence baseline = ownerEvidence(); + PreseededActorAssignmentOwnerEvidence reevaluated = + new PreseededActorAssignmentOwnerEvidence( + baseline.assignmentUuid(), + baseline.canonicalAccountUuid(), + baseline.eligibility(), + Instant.parse("2026-10-04T00:05:00Z"), + 10L, + "4".repeat(64), + baseline.canonicalTenantUuid(), + baseline.realmUuid(), + baseline.worldSlug(), + baseline.realmSlug(), + "game-instance", + baseline.catalogRevision(), + baseline.canonicalVersionUuid(), + baseline.frozenPolicyDigest(), + baseline.playableStateNamespaceId(), + baseline.playableStateScope(), + baseline.entryPolicy(), + baseline.accountPurpose(), + baseline.accountCurrentness(), + baseline.accountAuthoritySnapshotDigest(), + baseline.publishedOwnerProofDigest(), + baseline.publishedReleaseBundleRef()); + PreseededActorAssignmentOwnerEvidence changedCatalog = + new PreseededActorAssignmentOwnerEvidence( + baseline.assignmentUuid(), + baseline.canonicalAccountUuid(), + baseline.eligibility(), + baseline.eligibilityEvaluatedAt(), + baseline.membershipAuthorityGeneration(), + baseline.eligibilityEvidenceDigest(), + baseline.canonicalTenantUuid(), + baseline.realmUuid(), + baseline.worldSlug(), + baseline.realmSlug(), + "game-instance", + baseline.catalogRevision() + 1, + baseline.canonicalVersionUuid(), + baseline.frozenPolicyDigest(), + baseline.playableStateNamespaceId(), + baseline.playableStateScope(), + baseline.entryPolicy(), + baseline.accountPurpose(), + baseline.accountCurrentness(), + baseline.accountAuthoritySnapshotDigest(), + baseline.publishedOwnerProofDigest(), + baseline.publishedReleaseBundleRef()); + PreseededActorAssignmentOwnerEvidence changedScope = + new PreseededActorAssignmentOwnerEvidence( + baseline.assignmentUuid(), + baseline.canonicalAccountUuid(), + baseline.eligibility(), + baseline.eligibilityEvaluatedAt(), + baseline.membershipAuthorityGeneration(), + baseline.eligibilityEvidenceDigest(), + baseline.canonicalTenantUuid(), + baseline.realmUuid(), + baseline.worldSlug(), + baseline.realmSlug(), + "game-instance", + baseline.catalogRevision(), + baseline.canonicalVersionUuid(), + baseline.frozenPolicyDigest(), + baseline.playableStateNamespaceId(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, + baseline.entryPolicy(), + baseline.accountPurpose(), + baseline.accountCurrentness(), + baseline.accountAuthoritySnapshotDigest(), + baseline.publishedOwnerProofDigest(), + baseline.publishedReleaseBundleRef()); + PreseededActorAssignmentRequest changedPayload = + new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Changed Actor"), + request.expectedTarget()); + PreseededActorAssignmentRequest changedAccount = + new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + UUID.fromString("80000000-0000-4000-8000-000000000008"), + request.corePayload(), + request.expectedTarget()); + + String digest = PreseededActorAssignmentIntentDigest.compute(request, baseline); + assertThat(digest) + .isEqualTo("59f2041020ab6231ec26fe838bb70b25df509bfd0fa7f4bc78fe85575a1286b8"); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, changedScope)) + .isEqualTo("89b56ed7c981e381017285ef4916928e2e357413f11cf909fb6e07f848f86b5c"); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, reevaluated)) + .isEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, changedCatalog)) + .isNotEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, changedScope)) + .isNotEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, changedTarget(4))) + .isNotEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(request, changedTarget(10))) + .isNotEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(changedPayload, baseline)) + .isNotEqualTo(digest); + assertThat(PreseededActorAssignmentIntentDigest.compute(changedAccount, baseline)) + .isNotEqualTo(digest); + } + + private static PreseededActorAssignmentRequest request() { + return new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Assigned Actor"), + expectedTarget()); + } + + private static PreseededActorAssignmentExpectedTarget expectedTarget() { + return new PreseededActorAssignmentExpectedTarget( + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + "release-bundle/test", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + + private static PreseededActorAssignmentOwnerEvidence changedTarget(int field) { + PreseededActorAssignmentOwnerEvidence baseline = ownerEvidence(); + return new PreseededActorAssignmentOwnerEvidence( + baseline.assignmentUuid(), + baseline.canonicalAccountUuid(), + baseline.eligibility(), + baseline.eligibilityEvaluatedAt(), + baseline.membershipAuthorityGeneration(), + baseline.eligibilityEvidenceDigest(), + field == 0 + ? UUID.fromString("80000000-0000-4000-8000-000000000008") + : baseline.canonicalTenantUuid(), + field == 1 ? UUID.fromString("90000000-0000-4000-8000-000000000009") : baseline.realmUuid(), + field == 2 ? "other-world" : baseline.worldSlug(), + field == 3 ? "other-realm" : baseline.realmSlug(), + field == 4 ? "other-game-instance" : baseline.gameInstanceId(), + field == 5 ? baseline.catalogRevision() + 1 : baseline.catalogRevision(), + field == 6 + ? UUID.fromString("18000000-0000-4000-8000-000000000018") + : baseline.canonicalVersionUuid(), + field == 7 ? "3".repeat(64) : baseline.frozenPolicyDigest(), + field == 8 + ? UUID.fromString("a0000000-0000-4000-8000-00000000000a") + : baseline.playableStateNamespaceId(), + field == 10 + ? PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED + : baseline.playableStateScope(), + baseline.entryPolicy(), + baseline.accountPurpose(), + baseline.accountCurrentness(), + baseline.accountAuthoritySnapshotDigest(), + baseline.publishedOwnerProofDigest(), + field == 9 ? "release-bundle/changed" : baseline.publishedReleaseBundleRef()); + } + + private static PreseededActorStagingEligibilityPort stagingPort() { + return (accountUuid, tenantUuid, assignmentUuid) -> { + assertThat(accountUuid).isEqualTo(ACCOUNT_UUID.toString()); + assertThat(tenantUuid).isEqualTo(TENANT_UUID.toString()); + assertThat(assignmentUuid).isEqualTo(ASSIGNMENT_UUID.toString()); + return stagingEvidence(); + }; + } + + private static AccountActorStagingEligibilityEvidence stagingEvidence() { + return stagingEvidence(true); + } + + private static AccountActorStagingEligibilityEvidence stagingEvidence(boolean eligible) { + return AccountActorStagingEligibilityEvidence.seal( + "dev", + ASSIGNMENT_UUID, + ACCOUNT_UUID, + TENANT_UUID, + AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + Instant.parse("2026-10-04T00:00:00Z"), + "ACCOUNT_DATABASE_INSERT", + eligible ? "ACTIVE" : "DEACTIVATED_PENDING_DELETE", + eligible ? "ACTIVE" : "INACTIVE", + eligible, + "EXPLICIT_JOIN", + 17L, + 9L, + "FRESH_GAME_DESIGN", + UUID.fromString("60000000-0000-4000-8000-000000000006"), + "sha256:" + "a".repeat(64), + 23L, + UUID.fromString("70000000-0000-4000-8000-000000000007"), + "sha256:" + "b".repeat(64), + false); + } + + private static RuntimeAccountIdentityEvidence accountProof() { + return new RuntimeAccountIdentityEvidence( + 1, "dev", ASSIGNMENT_UUID, ACCOUNT_UUID, 23L, "ACCOUNT_DATABASE_INSERT"); + } + + private static PreseededActorAssignmentOwnerEvidence ownerEvidence() { + return new PreseededActorAssignmentOwnerEvidence( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + stagingEvidence().observedAt(), + stagingEvidence().membershipAuthorityGeneration(), + stagingEvidence().eligibilityDecisionDigest(), + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + stagingEvidence().authoritySnapshotDigest(), + "4".repeat(64), + "release-bundle/test"); + } + + private static PreseededActorAssignmentOwnerEvidence ownerEvidenceWithAccountSnapshotDigest( + String accountSnapshotDigest) { + PreseededActorAssignmentOwnerEvidence baseline = ownerEvidence(); + return new PreseededActorAssignmentOwnerEvidence( + baseline.assignmentUuid(), + baseline.canonicalAccountUuid(), + baseline.eligibility(), + baseline.eligibilityEvaluatedAt(), + baseline.membershipAuthorityGeneration(), + baseline.eligibilityEvidenceDigest(), + baseline.canonicalTenantUuid(), + baseline.realmUuid(), + baseline.worldSlug(), + baseline.realmSlug(), + baseline.gameInstanceId(), + baseline.catalogRevision(), + baseline.canonicalVersionUuid(), + baseline.frozenPolicyDigest(), + baseline.playableStateNamespaceId(), + baseline.playableStateScope(), + baseline.entryPolicy(), + baseline.accountPurpose(), + baseline.accountCurrentness(), + accountSnapshotDigest, + baseline.publishedOwnerProofDigest(), + baseline.publishedReleaseBundleRef()); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java new file mode 100644 index 0000000000..e9145597ea --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.entitymanagement.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +class PreseededActorCorePayloadTest { + @Test + void rejectsMissingBlankOverlongOrControlCharacterDisplayNames() { + assertThatThrownBy( + () -> new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, " ")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "x".repeat(101))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Bad\nName")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsUnpairedUtf16Surrogates() { + assertThatThrownBy( + () -> + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Bad\uD800Name")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Bad\uDC00Name")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void acceptsAWellFormedAstralNameAtTheCodePointLimit() { + String displayName = "\uD83D\uDE00" + "x".repeat(99); + + PreseededActorCorePayload payload = + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, displayName); + + org.assertj.core.api.Assertions.assertThat(payload.displayName()).isEqualTo(displayName); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java new file mode 100644 index 0000000000..0edcc33177 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java @@ -0,0 +1,428 @@ +package net.firedevops.firemud.entitymanagement.service; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.time.Instant; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class RunOwnedPreseededActorAssignmentAuthorityAdapterTest { + private static final String RUN_ID = "compose-smoke-9123"; + private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-9123"; + private static final String NAMESPACE = "dev"; + private static final String URI = "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final String TRUST_ROOT_SHA256 = "b".repeat(64); + private static final UUID ASSIGNMENT_UUID = + UUID.fromString("10000000-0000-4000-8000-000000000001"); + private static final UUID ACCOUNT_UUID = UUID.fromString("20000000-0000-4000-8000-000000000002"); + private static final UUID TENANT_UUID = UUID.fromString("30000000-0000-4000-8000-000000000003"); + private static final UUID REALM_UUID = UUID.fromString("40000000-0000-4000-8000-000000000004"); + private static final UUID NAMESPACE_UUID = + UUID.fromString("50000000-0000-4000-8000-000000000005"); + + @BeforeEach + void clearSessionContextBeforeTest() { + SessionContext.clear(); + } + + @AfterEach + void clearSessionContextAfterTest() { + SessionContext.clear(); + } + + @Test + void validatesExactGrantThenRechecksItAgainstIndependentOwnerTarget(@TempDir Path directory) + throws Exception { + Path capabilityFile = writeGrant(directory, request()); + RunOwnedPreseededActorAssignmentAuthorityAdapter authority = + authority(capabilityFile.toString()); + + withGameSessionPeer( + () -> { + assertThatCode( + () -> + authority.requireAuthorized( + request(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .doesNotThrowAnyException(); + assertThatCode( + () -> + authority.requireTargetBoundAuthorized( + request(), + ownerEvidence(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .doesNotThrowAnyException(); + assertThatThrownBy( + () -> + authority.requireTargetBoundAuthorized( + request(), + ownerEvidenceWithNamespace( + UUID.fromString("60000000-0000-4000-8000-000000000006")), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class); + }); + } + + @Test + void changedOrAbsentGrantDeniesBeforeOwnerReadsAndRepositoryMutation(@TempDir Path directory) + throws Exception { + PreseededActorAssignmentRequest request = request(); + PreseededActorAssignmentRequest otherIntent = + new PreseededActorAssignmentRequest( + UUID.fromString("10000000-0000-4000-8000-000000000009"), + ACCOUNT_UUID, + request.corePayload(), + request.expectedTarget()); + Path capabilityFile = writeGrant(directory, otherIntent); + RunOwnedPreseededActorAssignmentAuthorityAdapter authority = + authority(capabilityFile.toString()); + PreseededActorAccountIdentityPort accountIdentityPort = + mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerEvidencePort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + authority, accountIdentityPort, stagingPort(), ownerEvidencePort, characterRepository); + + withGameSessionPeer( + () -> + assertThatThrownBy(() -> service.assign(request)) + .isInstanceOf(AdminAuthorizationException.class)); + verifyNoInteractions(accountIdentityPort, ownerEvidencePort, characterRepository); + + RunOwnedPreseededActorAssignmentAuthorityAdapter missingCapability = authority(""); + withGameSessionPeer( + () -> + assertThatThrownBy( + () -> + missingCapability.requireAuthorized( + request, + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class)); + } + + @Test + void authenticatedUriMustBeExactAndUserContextRemainsDenied(@TempDir Path directory) + throws Exception { + Path capabilityFile = writeGrant(directory, request()); + RunOwnedPreseededActorAssignmentAuthorityAdapter authority = + authority(capabilityFile.toString()); + + assertThatThrownBy( + () -> + authority.requireAuthorized( + request(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", + "other", + "game-session-service")) + .run( + () -> + assertThatThrownBy( + () -> + authority.requireAuthorized( + request(), + RunOwnedPreseededAssignmentAuthority.Action + .PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class)); + + SessionContext.setContext(ACCOUNT_UUID.toString(), List.of(), java.util.Map.of()); + try { + withGameSessionPeer( + () -> + assertThatThrownBy( + () -> + authority.requireAuthorized( + request(), + RunOwnedPreseededAssignmentAuthority.Action + .PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class)); + } finally { + SessionContext.clear(); + } + } + + @Test + void grantReplacementBetweenOwnerReadsAndPersistenceFailsClosed(@TempDir Path directory) + throws Exception { + PreseededActorAssignmentRequest request = request(); + Path capabilityFile = writeGrant(directory, request); + RunOwnedPreseededActorAssignmentAuthorityAdapter authority = + authority(capabilityFile.toString()); + RuntimeAccountIdentityEvidence accountProof = + new RuntimeAccountIdentityEvidence( + 1, "dev", ASSIGNMENT_UUID, ACCOUNT_UUID, 23L, "ACCOUNT_DATABASE_INSERT"); + PreseededActorAccountIdentityPort accountIdentityPort = + mock(PreseededActorAccountIdentityPort.class); + PreseededActorAssignmentOwnerEvidencePort ownerEvidencePort = + mock(PreseededActorAssignmentOwnerEvidencePort.class); + CharacterRepository characterRepository = mock(CharacterRepository.class); + PreseededActorAssignmentService service = + new PreseededActorAssignmentService( + authority, accountIdentityPort, stagingPort(), ownerEvidencePort, characterRepository); + when(accountIdentityPort.resolveRuntimeAccountIdentity( + ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) + .thenAnswer( + invocation -> { + PreseededActorAssignmentRequest replacement = + new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Changed Actor"), + request.expectedTarget()); + replaceGrant(capabilityFile, replacement); + return accountProof; + }); + when(ownerEvidencePort.resolveCurrentEligibleTarget(request, accountProof, stagingEvidence())) + .thenReturn(ownerEvidence()); + + withGameSessionPeer( + () -> + assertThatThrownBy(() -> service.assign(request)) + .isInstanceOf(AdminAuthorizationException.class)); + + verifyNoInteractions(characterRepository); + } + + @Test + void activeServerTrustRootPinIsReevaluatedAtTheOwnerBoundBoundary(@TempDir Path directory) + throws Exception { + Path capabilityFile = writeGrant(directory, request()); + AtomicReference activeTrustRoot = new AtomicReference<>(TRUST_ROOT_SHA256); + RunOwnedPreseededActorAssignmentAuthorityAdapter authority = + new RunOwnedPreseededActorAssignmentAuthorityAdapter( + capabilityFile.toString(), RUN_ID, PROJECT_NAME, NAMESPACE, activeTrustRoot::get); + + withGameSessionPeer( + () -> { + authority.requireAuthorized( + request(), RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + activeTrustRoot.set("c".repeat(64)); + assertThatThrownBy( + () -> + authority.requireTargetBoundAuthorized( + request(), + ownerEvidence(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class); + }); + } + + private static RunOwnedPreseededActorAssignmentAuthorityAdapter authority(String path) { + return new RunOwnedPreseededActorAssignmentAuthorityAdapter( + path, RUN_ID, PROJECT_NAME, NAMESPACE, () -> TRUST_ROOT_SHA256); + } + + private static void withGameSessionPeer(Runnable action) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity(URI, NAMESPACE, "game-session-service")) + .run(action); + } + + private static Path writeGrant(Path directory, PreseededActorAssignmentRequest request) + throws Exception { + Files.setPosixFilePermissions( + directory, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE)); + Path file = directory.resolve("run-owned-assignment-grant.json"); + Files.writeString(file, capabilityJson(request), StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + file, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + return file; + } + + private static void replaceGrant(Path file, PreseededActorAssignmentRequest request) + throws Exception { + Files.setPosixFilePermissions( + file, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); + Files.writeString(file, capabilityJson(request), StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + file, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + } + + private static String capabilityJson(PreseededActorAssignmentRequest request) { + PreseededActorAssignmentExpectedTarget target = request.expectedTarget(); + return String.join( + "%n", + "{", + " \"schema\": \"%s\",", + " \"runId\": \"%s\",", + " \"composeProjectName\": \"%s\",", + " \"action\": \"%s\",", + " \"trustedGameSessionUriSan\": \"%s\",", + " \"trustedGameSessionNamespace\": \"%s\",", + " \"assignmentUuid\": \"%s\",", + " \"canonicalAccountUuid\": \"%s\",", + " \"expectedTarget\": {", + " \"canonicalTenantUuid\": \"%s\",", + " \"realmUuid\": \"%s\",", + " \"worldSlug\": \"%s\",", + " \"realmSlug\": \"%s\",", + " \"gameInstanceId\": \"%s\",", + " \"catalogRevision\": %d,", + " \"canonicalVersionUuid\": \"%s\",", + " \"frozenPolicyDigest\": \"%s\",", + " \"playableStateNamespaceUuid\": \"%s\",", + " \"publishedReleaseBundleRef\": \"%s\",", + " \"playableStateScope\": \"%s\"", + " },", + " \"corePayload\": {", + " \"actorKind\": \"%s\",", + " \"displayName\": \"%s\"", + " },", + " \"intentDigest\": \"%s\",", + " \"entityServerTrustRootSha256\": \"%s\"", + "}") + .formatted( + RunOwnedPreseededActorAssignmentCapability.CAPABILITY_SCHEMA, + RUN_ID, + PROJECT_NAME, + RunOwnedPreseededActorAssignmentCapability.ACTION, + URI, + NAMESPACE, + request.assignmentUuid(), + request.canonicalAccountUuid(), + target.canonicalTenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceId(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.frozenPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope().name(), + request.corePayload().actorKind().name(), + request.corePayload().displayName(), + PreseededActorAssignmentGrantIntentDigest.compute(request), + TRUST_ROOT_SHA256); + } + + private static PreseededActorStagingEligibilityPort stagingPort() { + return (accountUuid, tenantUuid, assignmentUuid) -> { + if (!ACCOUNT_UUID.toString().equals(accountUuid) + || !TENANT_UUID.toString().equals(tenantUuid) + || !ASSIGNMENT_UUID.toString().equals(assignmentUuid)) { + throw new IllegalStateException("unexpected Account staging evidence request"); + } + return stagingEvidence(); + }; + } + + private static AccountActorStagingEligibilityEvidence stagingEvidence() { + return AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + ASSIGNMENT_UUID, + ACCOUNT_UUID, + TENANT_UUID, + AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + Instant.parse("2026-10-04T00:00:00Z"), + "ACCOUNT_DATABASE_INSERT", + "ACTIVE", + "ACTIVE", + true, + "EXPLICIT_JOIN", + 17L, + 9L, + "FRESH_GAME_DESIGN", + UUID.fromString("60000000-0000-4000-8000-000000000006"), + "sha256:" + "a".repeat(64), + 23L, + UUID.fromString("70000000-0000-4000-8000-000000000007"), + "sha256:" + "b".repeat(64), + false); + } + + private static PreseededActorAssignmentRequest request() { + return new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Assigned Actor"), + new PreseededActorAssignmentExpectedTarget( + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + "release-bundle/test", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + } + + private static PreseededActorAssignmentOwnerEvidence ownerEvidence() { + return ownerEvidenceWithNamespace(NAMESPACE_UUID); + } + + private static PreseededActorAssignmentOwnerEvidence ownerEvidenceWithNamespace( + UUID namespaceUuid) { + return new PreseededActorAssignmentOwnerEvidence( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + stagingEvidence().observedAt(), + stagingEvidence().membershipAuthorityGeneration(), + stagingEvidence().eligibilityDecisionDigest(), + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + namespaceUuid, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + stagingEvidence().authoritySnapshotDigest(), + "4".repeat(64), + "release-bundle/test"); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java new file mode 100644 index 0000000000..77f822a23f --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java @@ -0,0 +1,390 @@ +package net.firedevops.firemud.entitymanagement.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.security.cert.CertificateExpiredException; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class RunOwnedPreseededActorAssignmentCapabilityTest { + private static final String RUN_ID = "compose-smoke-9123"; + private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-9123"; + private static final String NAMESPACE = "dev"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/dev/sa/game-session-service"; + private static final String ENTITY_TRUST_ROOT_SHA256 = "b".repeat(64); + private static final UUID ASSIGNMENT_UUID = + UUID.fromString("10000000-0000-4000-8000-000000000001"); + private static final UUID ACCOUNT_UUID = UUID.fromString("20000000-0000-4000-8000-000000000002"); + private static final UUID TENANT_UUID = UUID.fromString("30000000-0000-4000-8000-000000000003"); + private static final UUID REALM_UUID = UUID.fromString("40000000-0000-4000-8000-000000000004"); + private static final UUID NAMESPACE_UUID = + UUID.fromString("50000000-0000-4000-8000-000000000005"); + + @Test + void parsesExactGrantAndBindsRunProjectPeerAssignmentTargetPayloadAndTlsTrustRoot() { + RunOwnedPreseededActorAssignmentCapability capability = parse(validJson()); + + assertThat(capability.matchesRequest(request())).isTrue(); + assertThat(capability.matchesOwnerTarget(request(), ownerEvidence())).isTrue(); + } + + @Test + void grantDigestUsesCanonicalShortScopeTextForBothScopes() { + assertThat(PreseededActorAssignmentGrantIntentDigest.compute(request())) + .isEqualTo("59f2041020ab6231ec26fe838bb70b25df509bfd0fa7f4bc78fe85575a1286b8"); + PreseededActorAssignmentRequest isolated = + request("release-bundle/test", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED); + assertThat(PreseededActorAssignmentGrantIntentDigest.compute(isolated)) + .isEqualTo("89b56ed7c981e381017285ef4916928e2e357413f11cf909fb6e07f848f86b5c"); + assertThat(parse(validJson(isolated)).matchesRequest(isolated)).isTrue(); + } + + @Test + void permitsFullReleaseReferenceBoundWithoutRelaxingTargetValidation() { + for (int length : new int[] {257, 1024}) { + PreseededActorAssignmentRequest longReleaseRef = + request("r".repeat(length), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(parse(validJson(longReleaseRef)).matchesRequest(longReleaseRef)).isTrue(); + } + assertThatThrownBy( + () -> request("r".repeat(1025), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isInstanceOf(IllegalArgumentException.class); + assertInvalid( + validJson() + .replace( + "\"publishedReleaseBundleRef\": \"release-bundle/test\"", + "\"publishedReleaseBundleRef\": \"" + "r".repeat(1025) + "\"")); + } + + @Test + void rejectsUnknownDuplicateAndChangedIntentFields() { + assertInvalid( + validJson() + .replace( + RunOwnedPreseededActorAssignmentCapability.CAPABILITY_SCHEMA, + "firemud.run-owned-preseeded-actor-assignment.v2")); + assertInvalid( + validJson() + .replace( + "\"canonicalVersionUuid\": \"" + + request().expectedTarget().canonicalVersionUuid() + + "\"", + "\"publishedVersionId\": 17, \"publishedVersionNumber\": 2")); + assertInvalid(validJson().replace("\"action\":", "\"unexpected\":true,\"action\":")); + assertInvalid( + validJson() + .replace( + "\"action\": \"PRESEEDED_ACTOR_ASSIGNMENT\"", + "\"action\": \"PRESEEDED_ACTOR_ASSIGNMENT\"," + + "\"action\": \"PRESEEDED_ACTOR_ASSIGNMENT\"")); + assertInvalid( + validJson().replace("\"worldSlug\": \"world\"", "\"extra\": 1, \"worldSlug\": \"world\"")); + assertInvalid( + validJson() + .replace("\"actorKind\": \"PLAYER\"", "\"extra\": 1, \"actorKind\": \"PLAYER\"")); + assertInvalid( + validJson() + .replace( + "\"assignmentUuid\": \"" + ASSIGNMENT_UUID, + "\"assignmentUuid\": \"10000000-0000-4000-8000-000000000009")); + assertInvalid( + validJson() + .replace("\"displayName\": \"Assigned Actor\"", "\"displayName\": \"Changed Actor\"")); + assertInvalid(validJson().replace(ENTITY_TRUST_ROOT_SHA256, "c".repeat(64))); + } + + @Test + void rejectsChangedConfiguredRunProjectPeerNamespaceAndTrustRoot() { + byte[] json = validJson().getBytes(StandardCharsets.UTF_8); + + assertInvalid( + json, "different-run", PROJECT_NAME, GAME_SESSION_URI, NAMESPACE, ENTITY_TRUST_ROOT_SHA256); + assertInvalid( + json, RUN_ID, "different-project", GAME_SESSION_URI, NAMESPACE, ENTITY_TRUST_ROOT_SHA256); + assertInvalid( + json, + RUN_ID, + PROJECT_NAME, + "spiffe://firemud/ns/other/sa/game-session-service", + NAMESPACE, + ENTITY_TRUST_ROOT_SHA256); + assertInvalid(json, RUN_ID, PROJECT_NAME, GAME_SESSION_URI, "other", ENTITY_TRUST_ROOT_SHA256); + assertInvalid(json, RUN_ID, PROJECT_NAME, GAME_SESSION_URI, NAMESPACE, "d".repeat(64)); + } + + @Test + void rejectsWritableSymlinkedAndOversizedCapabilityFiles(@TempDir Path directory) + throws Exception { + makePrivateDirectory(directory); + Path writableCapability = writeCapability(directory.resolve("writable.json")); + assertThatThrownBy( + () -> RunOwnedPreseededActorAssignmentCapability.readCapability(writableCapability)) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + + Path readonlyCapability = writeCapability(directory.resolve("readonly.json")); + Files.setPosixFilePermissions(readonlyCapability, readOnlyFilePermissions()); + Path symlink = directory.resolve("symlink.json"); + Files.createSymbolicLink(symlink, readonlyCapability.getFileName()); + assertThatThrownBy(() -> RunOwnedPreseededActorAssignmentCapability.readCapability(symlink)) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + + Path oversized = directory.resolve("oversized.json"); + Files.writeString(oversized, "x".repeat(16 * 1024 + 1)); + Files.setPosixFilePermissions(oversized, readOnlyFilePermissions()); + assertThatThrownBy(() -> RunOwnedPreseededActorAssignmentCapability.readCapability(oversized)) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + } + + @Test + void readsOnlyOwnerBoundNonWritableCapabilityFile(@TempDir Path directory) throws Exception { + makePrivateDirectory(directory); + Path capabilityFile = writeCapability(directory.resolve("capability.json")); + Files.setPosixFilePermissions(capabilityFile, readOnlyFilePermissions()); + + assertThat(RunOwnedPreseededActorAssignmentCapability.readCapability(capabilityFile)) + .isEqualTo(validJson().getBytes(StandardCharsets.UTF_8)); + } + + @Test + void trustRootPinRequiresOneValidCaAndUsesExactLoadedCertificateFingerprint() throws Exception { + X509Certificate trustedRoot = mock(X509Certificate.class); + when(trustedRoot.getBasicConstraints()).thenReturn(1); + when(trustedRoot.getEncoded()).thenReturn(new byte[] {1, 2, 3}); + + assertThat( + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot))) + .isEqualTo( + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(new byte[] {1, 2, 3}))); + + String configuredFingerprint = + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot)); + X509TrustManager loadedTrustManager = mock(X509TrustManager.class); + when(loadedTrustManager.getAcceptedIssuers()).thenReturn(new X509Certificate[] {trustedRoot}); + assertThat( + RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( + new TrustManager[] {loadedTrustManager}, configuredFingerprint)) + .isEqualTo(configuredFingerprint); + assertThatThrownBy( + () -> + RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( + new TrustManager[] {loadedTrustManager}, "c".repeat(64))) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + when(loadedTrustManager.getAcceptedIssuers()) + .thenReturn(new X509Certificate[] {trustedRoot, trustedRoot}); + assertThatThrownBy( + () -> + RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( + new TrustManager[] {loadedTrustManager}, configuredFingerprint)) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + + assertThatThrownBy( + () -> + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot, trustedRoot))) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + + doThrow(new CertificateExpiredException()).when(trustedRoot).checkValidity(); + assertThatThrownBy( + () -> + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot))) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + } + + private static RunOwnedPreseededActorAssignmentCapability parse(String json) { + return parse( + json.getBytes(StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + GAME_SESSION_URI, + NAMESPACE, + ENTITY_TRUST_ROOT_SHA256); + } + + private static RunOwnedPreseededActorAssignmentCapability parse( + byte[] json, + String runId, + String projectName, + String gameSessionUri, + String namespace, + String trustRootSha256) { + return RunOwnedPreseededActorAssignmentCapability.parseAndValidate( + json, runId, projectName, gameSessionUri, namespace, trustRootSha256); + } + + private static void assertInvalid(String json) { + assertInvalid( + json.getBytes(StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + GAME_SESSION_URI, + NAMESPACE, + ENTITY_TRUST_ROOT_SHA256); + } + + private static void assertInvalid( + byte[] json, + String runId, + String projectName, + String gameSessionUri, + String namespace, + String trustRootSha256) { + assertThatThrownBy( + () -> parse(json, runId, projectName, gameSessionUri, namespace, trustRootSha256)) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + } + + private static Path writeCapability(Path path) throws Exception { + return Files.writeString(path, validJson()); + } + + private static void makePrivateDirectory(Path directory) throws Exception { + Files.setPosixFilePermissions( + directory, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE)); + } + + private static Set readOnlyFilePermissions() { + return Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ); + } + + private static PreseededActorAssignmentRequest request() { + return request("release-bundle/test", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + + private static PreseededActorAssignmentRequest request( + String releaseRef, PlayableStateScope scope) { + return new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Assigned Actor"), + new PreseededActorAssignmentExpectedTarget( + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + releaseRef, + scope)); + } + + private static PreseededActorAssignmentOwnerEvidence ownerEvidence() { + return new PreseededActorAssignmentOwnerEvidence( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + Instant.parse("2026-10-04T00:00:00Z"), + 9L, + "1".repeat(64), + TENANT_UUID, + REALM_UUID, + "world", + "realm", + "game-instance", + 4L, + UUID.fromString("17000000-0000-4000-8000-000000000017"), + "2".repeat(64), + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + "3".repeat(64), + "4".repeat(64), + "release-bundle/test"); + } + + private static String validJson() { + return validJson(request()); + } + + private static String validJson(PreseededActorAssignmentRequest request) { + PreseededActorAssignmentExpectedTarget target = request.expectedTarget(); + return String.join( + "%n", + "{", + " \"schema\": \"%s\",", + " \"runId\": \"%s\",", + " \"composeProjectName\": \"%s\",", + " \"action\": \"%s\",", + " \"trustedGameSessionUriSan\": \"%s\",", + " \"trustedGameSessionNamespace\": \"%s\",", + " \"assignmentUuid\": \"%s\",", + " \"canonicalAccountUuid\": \"%s\",", + " \"expectedTarget\": {", + " \"canonicalTenantUuid\": \"%s\",", + " \"realmUuid\": \"%s\",", + " \"worldSlug\": \"%s\",", + " \"realmSlug\": \"%s\",", + " \"gameInstanceId\": \"%s\",", + " \"catalogRevision\": %d,", + " \"canonicalVersionUuid\": \"%s\",", + " \"frozenPolicyDigest\": \"%s\",", + " \"playableStateNamespaceUuid\": \"%s\",", + " \"publishedReleaseBundleRef\": \"%s\",", + " \"playableStateScope\": \"%s\"", + " },", + " \"corePayload\": {", + " \"actorKind\": \"%s\",", + " \"displayName\": \"%s\"", + " },", + " \"intentDigest\": \"%s\",", + " \"entityServerTrustRootSha256\": \"%s\"", + "}") + .formatted( + RunOwnedPreseededActorAssignmentCapability.CAPABILITY_SCHEMA, + RUN_ID, + PROJECT_NAME, + RunOwnedPreseededActorAssignmentCapability.ACTION, + GAME_SESSION_URI, + NAMESPACE, + request.assignmentUuid(), + request.canonicalAccountUuid(), + target.canonicalTenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceId(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.frozenPolicyDigest(), + target.playableStateNamespaceId(), + target.publishedReleaseBundleRef(), + target.playableStateScope().name(), + request.corePayload().actorKind().name(), + request.corePayload().displayName(), + PreseededActorAssignmentGrantIntentDigest.compute(request), + ENTITY_TRUST_ROOT_SHA256); + } +} diff --git a/services/entity-management-service/src/test/resources/application.yml b/services/entity-management-service/src/test/resources/application.yml index ec1671a55b..cd57d6839c 100644 --- a/services/entity-management-service/src/test/resources/application.yml +++ b/services/entity-management-service/src/test/resources/application.yml @@ -1,3 +1,7 @@ FIREMUD_GRPC_CERT_CHAIN_PATH: classpath:certs/dev-cert.pem FIREMUD_GRPC_PRIVATE_KEY_PATH: classpath:certs/dev-key.pem FIREMUD_GRPC_CA_CERT_PATH: classpath:certs/dev-ca.pem +spring: + flyway: + postgresql: + transactional-lock: false