From 8a49b2f1bc1814bb6a02f6ce350e2dca555276f2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:51:26 +1300 Subject: [PATCH 01/61] feat(entity): retain complete passive PRESEEDED assignment roster and receipts --- .../entity-management-service/README.md | 2 +- .../api-contracts.md | 6 +- .../runtime-and-data.md | 6 +- .../gameplay-rules-entities-and-effects.md | 6 +- ...reseededActorStagingEligibilityClient.java | 251 ++++ .../client/AccountRuntimeIdentityClient.java | 163 +++ ...anonicalGameplayRosterOwnerReadClient.java | 137 ++ ...eseededActorAssignmentOwnerReadClient.java | 133 ++ .../CanonicalGameplayRosterConfiguration.java | 94 ++ ...PreseededActorAssignmentConfiguration.java | 248 ++++ .../repository/CharacterRepository.java | 1100 ++++++++++++++++ ...anonicalGameplayRosterPeerInterceptor.java | 66 + .../service/CanonicalGameplayRosterActor.java | 21 + .../CanonicalGameplayRosterEntryPolicy.java | 9 + ...nonicalGameplayRosterExecutionContext.java | 58 + .../CanonicalGameplayRosterOwnerEvidence.java | 19 + ...onicalGameplayRosterOwnerEvidencePort.java | 27 + .../CanonicalGameplayRosterReadRequest.java | 28 + ...ayRosterSelectedAssignmentReadRequest.java | 36 + ...playRosterSelectedAssignmentReference.java | 35 + ...meplayRosterSelectedAssignmentService.java | 117 ++ .../CanonicalGameplayRosterService.java | 54 + .../CanonicalGameplayRosterSnapshot.java | 26 + ...CanonicalGameplayRosterSnapshotDigest.java | 68 + ...onicalGameplayRosterSnapshotReference.java | 19 + .../CanonicalGameplayRosterTarget.java | 84 ++ .../PreseededActorAccountIdentityPort.java | 10 + ...reseededActorAssignmentExpectedTarget.java | 96 ++ ...eededActorAssignmentGrantIntentDigest.java | 56 + .../PreseededActorAssignmentIntentDigest.java | 54 + ...PreseededActorAssignmentOwnerEvidence.java | 129 ++ ...eededActorAssignmentOwnerEvidencePort.java | 35 + .../PreseededActorAssignmentReceipt.java | 92 ++ ...reseededActorAssignmentReceiptRequest.java | 31 + ...reseededActorAssignmentReceiptService.java | 20 + .../PreseededActorAssignmentRequest.java | 34 + .../PreseededActorAssignmentResult.java | 27 + .../PreseededActorAssignmentService.java | 134 ++ .../service/PreseededActorCorePayload.java | 42 + .../PreseededActorStagingEligibilityPort.java | 12 + ...seededActorAssignmentAuthorityAdapter.java | 111 ++ ...nedPreseededActorAssignmentCapability.java | 602 +++++++++ .../RunOwnedPreseededAssignmentAuthority.java | 34 + .../CanonicalGameplayRosterGrpcAdapter.java | 382 ++++++ ...calGameplayRosterOwnerEvidenceAdapter.java | 235 ++++ ...edActorAssignmentOwnerEvidenceAdapter.java | 170 +++ .../src/main/resources/application-prod.yml | 4 +- .../src/main/resources/application.yml | 6 +- .../V5__preseeded_actor_assignment.sql | 208 ++++ ...6__preseeded_assignment_owner_snapshot.sql | 63 + ...7__canonical_gameplay_roster_snapshots.sql | 221 ++++ ...onical_publication_uuid_actor_evidence.sql | 162 +++ .../V9__canonical_roster_owner_counters.sql | 108 ++ ...anonicalGameplayRosterIntegrationTest.java | 417 +++++++ ...eseededActorAssignmentIntegrationTest.java | 1102 +++++++++++++++++ ...ededActorStagingEligibilityClientTest.java | 557 +++++++++ ...icalGameplayRosterOwnerReadClientTest.java | 262 ++++ ...dedActorAssignmentOwnerReadClientTest.java | 130 ++ ...onicalGameplayRosterConfigurationTest.java | 62 + ...eededActorAssignmentConfigurationTest.java | 80 ++ ...icalGameplayRosterPeerInterceptorTest.java | 227 ++++ ...ayRosterSelectedAssignmentServiceTest.java | 481 +++++++ .../CanonicalGameplayRosterServiceTest.java | 318 +++++ .../PreseededActorAssignmentServiceTest.java | 682 ++++++++++ .../PreseededActorCorePayloadTest.java | 51 + ...edActorAssignmentAuthorityAdapterTest.java | 428 +++++++ ...reseededActorAssignmentCapabilityTest.java | 353 ++++++ ...anonicalGameplayRosterGrpcAdapterTest.java | 517 ++++++++ ...ameplayRosterOwnerEvidenceAdapterTest.java | 344 +++++ ...torAssignmentOwnerEvidenceAdapterTest.java | 131 ++ 70 files changed, 12020 insertions(+), 13 deletions(-) create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClient.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfiguration.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterActor.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterEntryPolicy.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterExecutionContext.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidence.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterOwnerEvidencePort.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterReadRequest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReadRequest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentReference.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotDigest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshotReference.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterTarget.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAccountIdentityPort.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentExpectedTarget.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidence.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentOwnerEvidencePort.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceipt.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptRequest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentReceiptService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentRequest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentResult.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayload.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorStagingEligibilityPort.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapter.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapability.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededAssignmentAuthority.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapter.java create mode 100644 services/entity-management-service/src/main/resources/db/migration/V5__preseeded_actor_assignment.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V6__preseeded_assignment_owner_snapshot.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V7__canonical_gameplay_roster_snapshots.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V8__canonical_publication_uuid_actor_evidence.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V9__canonical_roster_owner_counters.sql create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java diff --git a/design/architecture/microservices/entity-management-service/README.md b/design/architecture/microservices/entity-management-service/README.md index 6f3989b11b..768e449aa1 100644 --- a/design/architecture/microservices/entity-management-service/README.md +++ b/design/architecture/microservices/entity-management-service/README.md @@ -6,7 +6,7 @@ Handles player characters, NPCs, runtime actor identity, items, and all inventor ## Implementation Status -Persisted rows and realm-aware listing code exist. V2 gives every persisted character an Entity-owned opaque UUID and retains V1 values unchanged. Legacy rows without the exact Account UUID, owner-resolved tenant UUID, namespace, and immutable scope remain `QUARANTINED`; legacy numeric IDs and `playable_state_key` remain source evidence only. The inherited #2965 Account UUID registration/export output remains implemented. Legacy roster/name lookups return no actors, actor-graph reads bypass stale cache entries and recheck persisted disposition, and repository updates fail closed unless the actor is `OWNER_RESOLVED`. The UUID-qualified lookup is not a gameplay-admission path. Stage 1 has no identity mapping/promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Production scoped inventory, containment, equipment, and actor-state/effect calls remain fail-closed for legacy identities. Unit and fixture proof limits, including the absence of physical PostgreSQL and authenticated Game Session-to-Entity network proof, are tracked under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status). +Persisted rows and realm-aware listing code exist. V2 gives every persisted character an Entity-owned opaque UUID and retains V1 values unchanged. V1 rows and rows created through legacy numeric-ID paths are `QUARANTINED` unless an exact Account UUID plus Game Design-owner-resolved tenant UUID, namespace, and immutable scope are present; the old numeric `account_id`/`tenant_id` and `playable_state_key` remain source evidence only. The inherited #2965 Account UUID registration/export output is implemented, and Entity now contains default-off `PRESEEDED_ONLY` assignment, owner-qualified roster, and selected-receipt source code. Both receiving handlers carry and validate typed `PlayerExecutionContext`; selected reads revalidate the supplied sealed snapshot UUID/digest against the current owner-resolved roster, and failures use canonical non-OK gRPC statuses. This guarded source returns persisted owner evidence only and does not establish gameplay admission or PLAY. Current local verification results and remaining authenticated Game Session-to-Entity mTLS/network, restart, and owner-provenance gaps are tracked under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status). The Game Design tenant UUID/namespace/scope owner producer remains separate. There is no legacy-identity mapping or promotion operation or PLAY activation. Legacy gameplay roster/name lookup paths return no actors, actor graph reads bypass stale cache entries and recheck persisted disposition, and the exact UUID-qualified repository lookup is not wired as a runtime admission path. Production scoped inventory, containment, equipment, and actor-state/effect calls still fail closed for legacy actor identities; conditional service and persistence tests do not establish owner-qualified gameplay admission. Synthetic-ID paths, fixed RPG columns, published entry-policy/descriptor/template resolution, namespace-idempotent auto-provision, and fork-local copy proof remain gaps. 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. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 7f7b6072c0..8af0c6602e 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,7 +6,9 @@ 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. +The canonical `CanonicalGameplayRosterService` proto defines two pre-admission reads restricted to `PRESEEDED_ONLY`; these reads do not admit or activate gameplay. Entity Java handlers implement both methods behind default-off owner-read configuration and the exact same-namespace Game Session mTLS peer allowlist. Their request models and adapter carry and validate typed `PlayerExecutionContext`; selected reads require and revalidate the supplied snapshot UUID/digest against the existing sealed snapshot and current owner-resolved roster, return the original persisted assignment receipt reference, and use canonical non-OK statuses without partial responses. This source does not establish fresh Account eligibility, gameplay admission, PLAY, or production owner provenance. Current PostgreSQL test results and remaining authenticated Game Session-to-Entity mTLS/network, restart, and owner-provenance gaps are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status). + +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. `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 lowercase hexadecimal SHA-256 of Entity's immutable assignment-intent preimage. 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`. UUIDs use canonical `UUID.toString()` form, counters use base-10 decimal text, and scope/policy values use their canonical enum names. 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 is the original persisted operation-intent digest, not a digest of current owner evidence or current Account state. @@ -43,7 +45,7 @@ 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` – 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 caller-provided 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 selected response returns the original persisted assignment receipt reference; it does not mint a receipt or admission proof. Both Java handlers are implemented in guarded source behind default-off owner-read configuration and the exact same-namespace Game Session workload mTLS allowlist. These reads are not actor admission or a session-binding shortcut; no production owner material or activated runtime owner-read path is claimed, and authenticated D-to-Entity runtime/network proof and PLAY activation remain absent. - `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/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 8932fc1501..629e1c9dfc 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -13,11 +13,11 @@ This document defines Entity Management’s runtime model, persistence ownership - The current concurrent first-apply path catches a duplicate-marker `DataIntegrityViolationException` inside the outer replay transaction and then attempts the loser read in that same transaction. PostgreSQL transaction-abort/rollback-only behavior means this is not a reliable replay or conflict result; the target requires a conflict-safe marker insert or a same-transaction savepoint around marker handling, preserving marker/mutation atomicity and never isolating marker insertion in a separate transaction. The [Entity Management Operations implementation status](./operations.md#implementation-status) records this local correction under the canonical [Transaction Strategies](../../system-architecture-transactions.md) participant contract. Real PostgreSQL concurrent first-apply/replay proof remains unavailable, so replay readiness remains blocked. - Character updates are not currently optimistic CAS: `CharacterRepository` increments `version` and requires an exact tenant/row ID match, `OWNER_RESOLVED` status, and one affected row, but does not compare the old version or bind the update to namespace identity. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. - Current `jOOQ + Flyway` adoption and focused persistence proof remain implementation work. -- Entity's standard, production, and test Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V3's out-of-transaction `CREATE INDEX CONCURRENTLY` statements. See [GR-3.1 implementation and proof status](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status) for historical full-source integration evidence and remaining gaps; this Stage 1 split has not been validated. +- Entity's standard, production, and test Flyway profiles set PostgreSQL `transactional-lock=false`. Flyway uses a session-level advisory lock, which still serializes competing migrations and is required for V3's out-of-transaction `CREATE INDEX CONCURRENTLY` statements. See [GR-3.1 implementation and proof status](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status) for the current integration evidence and remaining gaps. - The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for elapsed rows without namespace/instance predicates or a batch bound. Its delete now requires a matching `OWNER_RESOLVED` character, so quarantined actor conditions are excluded and retained; this is a narrow quarantine hold, not complete retention or disposal eligibility proof. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. - Realm-authored actor entry remains partial: legacy creation and actor rows still expose fixed RPG-oriented fields, policy/descriptor/template resolution and auto-provision idempotency are incomplete, and synthetic-ID/fork-copy proof gaps remain. These target rules do not claim runtime convergence. -- Entity V2 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain prior column/value evidence and are quarantined without inferred Account or tenant UUID mapping; legacy row creation remains quarantined. Exact UUID lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows. The inherited #2965 Account UUID registration/export output is implemented; the Game Design tenant UUID/namespace/scope owner producer remains separate. This Stage 1 boundary has no identity-promotion operation, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Current execution and proof status is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status); physical PostgreSQL and authenticated Game Session-to-Entity mTLS/network proof are not claimed. Fixture-created `OWNER_RESOLVED` rows prove SQL isolation only, not owner-backed runtime provenance. -- Legacy character roster/name lookup paths return no actors, numeric-ID graph reads require a fresh persisted `OWNER_RESOLVED` row and bypass the old character graph cache, and scoped gameplay resolution fails closed instead of translating `shared-live` or `instance:`. Consequently, production scoped inventory, containment, equipment, friend, and actor-state/effect calls do not admit legacy actor identities; no canonical owner-qualified gameplay admission path is connected. Resource/condition repositories additionally gate retained rows by actor disposition, and quarantined conditions are excluded from expiry. The original full-source container-location fixture and conditional service tests use explicitly mocked test guards; this Stage 1 split has no integration proof for those downstream paths and does not establish owner provenance or PLAY. This is a nonactivating storage boundary, not an owner-resolution implementation. +- Entity V2 adds `character_uuid`, nullable `account_uuid`, nullable `tenant_uuid`, and namespace/scope provenance on characters, with persisted `OWNER_RESOLVED`/`QUARANTINED` disposition. Existing V1 rows receive independently allocated nonnil character UUIDs but retain prior column/value evidence and are quarantined without inferred Account or tenant UUID mapping; legacy row creation remains quarantined. Exact UUID lookup requires persisted tenant UUID, Account UUID, namespace UUID, scope, and actor UUID and excludes quarantined rows. Entity now has default-off `PRESEEDED_ONLY` assignment, owner-qualified roster, and selected-receipt source code aligned to the C/D typed context, selected snapshot-reference, and gRPC-status contract. Selected reads revalidate the supplied sealed snapshot against the current owner-resolved roster before returning the original persisted receipt; this source returns owner evidence only and does not establish gameplay admission or PLAY. See [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status) for current PostgreSQL test results and remaining authenticated Game Session-to-Entity mTLS/network, restart, and owner-provenance gaps. The inherited #2965 Account UUID registration/export output is implemented; the Game Design tenant UUID/namespace/scope owner producer remains separate. Fixture-created `OWNER_RESOLVED` rows prove SQL isolation only, not owner-backed runtime provenance. +- Legacy character roster/name lookup paths return no actors, numeric-ID graph reads require a fresh persisted `OWNER_RESOLVED` row and bypass the old character graph cache, and scoped gameplay resolution fails closed instead of translating `shared-live` or `instance:`. Consequently, production scoped inventory, containment, equipment, friend, and actor-state/effect calls do not admit legacy actor identities; no canonical owner-qualified gameplay admission path is connected. Resource/condition repositories additionally gate retained rows by actor disposition, and quarantined conditions are excluded from expiry. Conditional service and holder-persistence tests exercise downstream behavior only after an explicitly mocked test guard and do not prove owner provenance or PLAY. This is a nonactivating storage boundary, not an owner-resolution implementation. - Runtime-instance cleanup treats any target `(tenantId, gameInstanceId)` item-instance, container, item-stack, or room-ground row as unclassified evidence and holds cleanup; legacy holder families lack namespace and disposal provenance, so no row is associated with an actor or classified as disposable from a runtime pointer. A transfer audit also holds cleanup when its existing actor link identifies a quarantined actor and its source or destination runtime matches the target. The typed read uses one tenant/runtime target pair and fails closed if its Boolean result is unavailable. An observed empty target returns zero deletion counts and issues no family deletes; this is only an empty-target observation, not trusted quiescence or authority to dispose a nonempty target. Nonempty cleanup remains closed pending owner classification and a fence. This observation-only boundary avoids a check/delete race from deleting rows after the check. - The live Entity schema does not yet represent the target namespace-stable identity for durable S1/S2 state: `characters` and `actor_resource_states` retain legacy `playable_state_key`, while `inventory`, `character_friend`, `character_equipment`, and durable holder/containment rows omit `playableStateNamespaceId` (and some omit `tenant_id` entirely). The current repositories consequently cannot enforce the target `{tenantId, playableStateNamespaceId, domainObjectId}` identity at the SQL boundary. A convergent migration, legacy-row disposition/backfill evidence, namespace-aware repository predicates, and focused isolation proof remain required; until those are complete, legacy `playable_state_key` rows (including `character_friend` associations reached through them) are not namespace-isolated proof and cutover readers must not treat them as namespace-backed survivor state. This does not change the target contract above. - The live `item_stacks` uniqueness constraint includes nullable holder columns, so PostgreSQL can accept duplicate rows for the same tenant/holder/item/fingerprint when another holder column is `NULL`. Inventory and container mutation paths still use find-then-create/save rather than an atomic conflict-safe operation. With no explicit `stackFamilyKey`, source resolution rejects more than one candidate row; with an explicit family key, the current implementation selects the first matching row and does not reject duplicate matches. Target resolution must enforce exactly one matching stack (or fail closed), alongside holder-kind-specific uniqueness or normalized non-null identity, atomic upsert/locking, and concurrent proof. 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 a722fafc45..d27d7330d7 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). Stage 1 adds Entity-owned opaque character identity, quarantine for unresolved legacy provenance, and fail-closed legacy consumers; it does not establish owner provenance, identity promotion, gameplay admission, or PLAY. PRESEEDED_ONLY assignment and owner-qualified roster/receipt source evidence remain in the following stage. 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). Entity now has default-off PRESEEDED_ONLY assignment staging and owner-qualified roster/receipt read sources; these persist or return source evidence only and do not establish gameplay admission or PLAY. 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. 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,8 +28,8 @@ 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` - Entity is the target persistence authority for actor identity. V2 gives persisted characters Entity-owned opaque UUIDs and quarantines unresolved legacy identity while retaining old values as source evidence. Stage 1 preserves owner-resolved-only legacy lookups and updates, fail-closed actor consumers, quarantine retention, and the tenant-wide quarantine blocker used by cutover validation. This stage has no owner-proven identity promotion, PRESEEDED assignment/roster/receipt source, gameplay admission, or PLAY. Policy-aware entry, unified actor runtime, and complete lifecycle remain incomplete. Passive `CHARACTER_CREATE/1` receiving support remains separately documented below as parent-provided local-only codec/projection support, with no authenticated producer, owner protections, Entity terminal composition, or route activation. | `partial` - 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. Historical full-source e3 evidence records a local combined Entity run with 291 passing unit tests and an exact-head [hosted Entity integration-test job](https://github.com/benhook1013/FireMUD/actions/runs/37868666749/job/113621467457); the log records actual `:entity-management-service:integrationTest` execution and `BUILD SUCCESSFUL` in 5m49, with no executed-case count artifact. That full-source run also includes PostgreSQL-backed receiver integration proof, but none of it is exact-head proof for this split postimage. Split-specific compilation/tests, authenticated Game Session-to-Entity mTLS/network proof, and live PLAY proof are unrun. | [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) | [CharacterServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImpl.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [Character.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/Character.java); [CharacterMapper.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/mapper/CharacterMapper.java); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [ActorActiveConditionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepository.java); [ActorResourceStateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepository.java); [CharacterEquipmentRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterEquipmentRepository.java); [CharacterFriendRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepository.java); [QuarantinedActorRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepository.java); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [EntityUpgradeValidationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityUpgradeValidationServiceImpl.java); [RuntimeInstanceCleanupServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImpl.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [V3 UUID/owner-resolved index migration](../../../services/entity-management-service/src/main/resources/db/migration/V3__build_actor_identity_indexes_concurrently.sql); [V4 constraint validation migration](../../../services/entity-management-service/src/main/resources/db/migration/V4__validate_actor_identity_constraints.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); [ActorActiveConditionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorActiveConditionRepositoryTest.java); [ActorResourceStateRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/ActorResourceStateRepositoryTest.java); [CharacterFriendRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/CharacterFriendRepositoryTest.java); [QuarantinedActorRetentionRepositoryTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/repository/QuarantinedActorRetentionRepositoryTest.java); [ScopedCharacterResolverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolverTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [CharacterServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [FriendServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/FriendServiceImplTest.java); [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [RuntimeInstanceCleanupServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/RuntimeInstanceCleanupServiceImplTest.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, policy/descriptor/template resolution, owner-proven PRESEEDED assignment and roster source, namespace-idempotent auto-provision, fork-local copy identity, and unified actor/NPC lifecycle remain open; the passive receiver and fail-closed identity boundary are not gameplay-admission proof. | -| 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` exist, but production actor-scoped inventory, containment, and drop/pickup admission remains fail-closed until trusted owner-qualified resolution is connected. Blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `partial` - Historical full-source e3 proof includes focused inventory, container, stack, transfer, location, and nonblank-effect mutation-replay tests for the bounded holder model. Stage 1's PostgreSQL `ContainerInstanceLocationIntegrationTest` preserves holder-persistence scenarios behind a test-only mocked exact-scope guard for explicitly registered quarantined fixtures; this conditionally proves container content and holder/location persistence, not owner provenance or runtime admission. `RetainedActorIdentityIntegrationTest` exercises the real resolver through `InventoryService.addItem` and asserts persisted item/container/holder counts remain unchanged after denial. This split has not been validated. | [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); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.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 ingress remediation remain open, alongside canonical owner-qualified admission, nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - Entity is the target persisted actor owner and V2 allocates opaque character UUIDs while quarantining unresolved legacy identity. Default-off `PRESEEDED_ONLY` assignment, roster, and selected-receipt source is present: assignment composes Account staging eligibility with current Game Session and Game Design owner evidence to persist an Entity actor association and original receipt; roster/receipt reads return persisted owner evidence only. Both receiver handlers now implement the merged C/D typed-context, selected-snapshot, and canonical-status contract, but they do not establish gameplay admission or PLAY. Policy-aware entry, unified actor runtime, and complete respawn lifecycle remain incomplete. Passive `CHARACTER_CREATE/1` codec and authored-source projection receiving support is present in common-platform-core; this remains passive receiving support without an authenticated producer, owner protections, Entity terminal composition, or route activation. | `proven` - focused character, NPC, and item/inventory tests cover bounded records and lifecycle seams, not PLAYER-01 policy/copy proof. Historical migration, SQL-isolation, and runtime-quarantine evidence remains bounded; fixture-created `OWNER_RESOLVED` rows test SQL predicates only, not owner-backed runtime provenance. On the exact source at `ada9df77752e1c2698e233f1d1395ecb33a1f000` with the 70-file second-stage parcel (106 cumulative files), the local gates passed: 292 unit tests and 26 Testcontainers PostgreSQL integration tests, with zero failures, errors, or skips; `spotlessApply`, `generateJooq`, Entity `check -PfullCheck`, `checkFlywayVersions` (12 migration sets, 265 versioned files), `linkCheck`, and `lintMarkdown` passed. This run does not establish authenticated owner provenance, Game Session-to-Entity mTLS/network behavior, restart recovery, or gameplay activation/PLAY. | [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) | [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); [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [V2 quarantine migration](../../../services/entity-management-service/src/main/resources/db/migration/V2__quarantine_unresolved_actor_identity.sql); [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); [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); [CanonicalGameplayRosterServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java); [CanonicalGameplayRosterSelectedAssignmentServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.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 open; the owner-qualified receiver is not playable/admission proof. | +| 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` exist, but production actor-scoped inventory, containment, and drop/pickup admission remains fail-closed until trusted owner-qualified resolution is connected. Blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `audited` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; `ContainerInstanceLocationIntegrationTest` uses fixture-mocked exact scope guard for quarantined saved characters. This is conditional domain proof, not owner provenance or runtime admission proof; the receiver test execution status is recorded under GR-3.1. | [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 ingress remediation remain open, alongside canonical owner-qualified admission, 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 code exists, but production actor-scoped equipment admission remains fail-closed until trusted owner-qualified resolution is connected; loadouts and lifecycle triggers are not implemented. | `audited` - focused equipment service/controller and item-command tests cover slot compatibility and binding, not production owner-qualified actor admission or PLAY; receiver test execution and proof status are recorded under GR-3.1. | [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. Owner-qualified runtime admission, 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 the self-targeted `APPLY_ACTION_STATE` command path exist, but scoped Entity actor-state/effect access remains fail-closed for legacy identities and canonical owner-qualified runtime admission is absent; general action resolution is incomplete. | `audited` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover bounded component behavior but do not prove owner-qualified Entity actor admission or PLAY; receiver test execution and proof status are recorded under GR-3.1. | [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) | Canonical owner-qualified actor admission, cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | | GR-4.2 Combat and conflict resolution | `not-implemented` - no combat/conflict resolver or authoritative combat loop is present. | `audited` - adjacent action-state/effect tests were inspected, but no focused combat proof exists. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md) | No production anchor: no combat owner is implemented. Adjacent context only: [ActionStateCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandler.java) and [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java) are non-combat seams. | No focused executable proof. [ActionStateCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java) is legacy context for the removed transient action-state handler path, not current combat proof; this does not mean the live durable `BLOCK` gameplay command or its replay-record category was removed. | [GR-3.1](./gameplay-rules-entities-and-effects.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [GR-1.2](./game-session-runtime-and-tick-coordination.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Damage packets, hit/mitigation ordering, combat timing, body-region resolution, and combat-driven defeat/loot/revival/victory behavior remain absent. | diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClient.java new file mode 100644 index 0000000000..40401d106f --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClient.java @@ -0,0 +1,251 @@ +package net.firedevops.firemud.entitymanagement.client; + +import com.google.protobuf.Timestamp; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountActorStagingEligibilityServiceGrpc; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityCurrentness; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityDecision; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityPurpose; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityRequest; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityResponse; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.entitymanagement.service.PreseededActorStagingEligibilityPort; + +/** Read-only Entity Management client for non-admitting Account actor-staging evidence. */ +public final class AccountPreseededActorStagingEligibilityClient + extends AbstractReloadingBlockingGrpcClient< + AccountActorStagingEligibilityServiceGrpc.AccountActorStagingEligibilityServiceBlockingStub> + implements PreseededActorStagingEligibilityPort { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final long MIN_PROTO_TIMESTAMP_SECONDS = -62_135_596_800L; + private static final long MAX_PROTO_TIMESTAMP_SECONDS = 253_402_300_799L; + private static final int MAX_PROTO_TIMESTAMP_NANOS = 999_999_999; + + private final String workloadNamespace; + + public AccountPreseededActorStagingEligibilityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireEntityManagementMtls(tlsProps), + channelFactory, + AccountPreseededActorStagingEligibilityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "Entity Management workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes the client only when an explicit caller owns activation of this handoff. */ + public void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountActorStagingEligibilityServiceGrpc + .AccountActorStagingEligibilityServiceBlockingStub + buildStub(ManagedChannel channel) { + return AccountActorStagingEligibilityServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service")) + .withCompression("gzip"); + } + + /** Reads current Account staging eligibility without granting gameplay admission authority. */ + @Override + public AccountActorStagingEligibilityEvidence resolvePreseededActorStagingEligibility( + String canonicalAccountId, String canonicalTenantId, String requestId) { + UUID accountUuid = parseCanonicalNonNilUuid(canonicalAccountId, "canonical account ID"); + UUID tenantUuid = parseCanonicalNonNilUuid(canonicalTenantId, "canonical tenant ID"); + UUID requestUuid = parseCanonicalNonNilUuid(requestId, "request ID"); + AccountActorStagingEligibilityServiceGrpc.AccountActorStagingEligibilityServiceBlockingStub + currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException( + "Account actor-staging eligibility client is not initialized"); + } + + ResolvePreseededActorStagingEligibilityResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolvePreseededActorStagingEligibility( + ResolvePreseededActorStagingEligibilityRequest.newBuilder() + .setSchemaVersion(AccountActorStagingEligibilityEvidence.SCHEMA_VERSION) + .setTargetNamespace(workloadNamespace) + .setRequestId(requestUuid.toString()) + .setCanonicalAccountId(accountUuid.toString()) + .setCanonicalTenantId(tenantUuid.toString()) + .setPurpose(ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY) + .build()); + if (response == null) { + throw new IllegalStateException("Account actor-staging eligibility response is absent"); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException( + "Account actor-staging eligibility response contains unsupported fields"); + } + if (!response.hasObservedAt()) { + throw new IllegalStateException( + "Account actor-staging eligibility response timestamp is absent"); + } + + AccountActorStagingEligibilityEvidence evidence; + try { + evidence = + new AccountActorStagingEligibilityEvidence( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getRequestId(), "response request ID"), + parseCanonicalNonNilUuid( + response.getCanonicalAccountId(), "response canonical account ID"), + parseCanonicalNonNilUuid( + response.getCanonicalTenantId(), "response canonical tenant ID"), + decodePurpose(response.getPurpose()), + decodeCurrentness(response.getCurrentness()), + parseObservedAt(response.getObservedAt()), + decodeDecision(response.getDecision()), + response.getAccountUuidProvenance(), + response.getAccountLifecycleState(), + response.getMembershipLifecycleState(), + response.getGameplayAdmissionAllowed(), + response.getMembershipAuthorityProvenance(), + response.getMembershipVersion(), + response.getMembershipAuthorityGeneration(), + response.getTenantProvenanceKind(), + parseCanonicalNonNilUuid( + response.getTenantSourceOperationId(), "tenant source operation ID"), + response.getTenantProvenanceDigest(), + response.getMembershipEventSequence(), + parseCanonicalNonNilUuid(response.getMembershipEventId(), "membership event ID"), + response.getMembershipEventDigest(), + response.getLastTransitionInvalidated(), + response.getEligibilityDecisionDigest(), + response.getAuthoritySnapshotDigest()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Account actor-staging eligibility response is invalid", exception); + } + + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !requestUuid.equals(evidence.requestId()) + || !accountUuid.equals(evidence.canonicalAccountId()) + || !tenantUuid.equals(evidence.canonicalTenantId())) { + throw new IllegalStateException( + "Account actor-staging eligibility response does not match the exact request"); + } + return evidence; + } + + private static AccountActorStagingEligibilityEvidence.Purpose decodePurpose( + ActorStagingEligibilityPurpose purpose) { + if (purpose == ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY) { + return AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY; + } + throw new IllegalArgumentException("Unknown Account actor-staging eligibility purpose"); + } + + private static Instant parseObservedAt(Timestamp observedAt) { + if (!observedAt.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Account actor-staging eligibility timestamp contains unsupported fields"); + } + long seconds = observedAt.getSeconds(); + int nanos = observedAt.getNanos(); + if (seconds < MIN_PROTO_TIMESTAMP_SECONDS + || seconds > MAX_PROTO_TIMESTAMP_SECONDS + || nanos < 0 + || nanos > MAX_PROTO_TIMESTAMP_NANOS) { + throw new IllegalArgumentException( + "Account actor-staging eligibility timestamp is outside protobuf bounds"); + } + return Instant.ofEpochSecond(seconds, nanos); + } + + private static AccountActorStagingEligibilityEvidence.Currentness decodeCurrentness( + ActorStagingEligibilityCurrentness currentness) { + if (currentness == ActorStagingEligibilityCurrentness.CURRENT_AT_REVALIDATION) { + return AccountActorStagingEligibilityEvidence.Currentness.CURRENT_AT_REVALIDATION; + } + throw new IllegalArgumentException("Unknown Account actor-staging eligibility currentness"); + } + + private static AccountActorStagingEligibilityEvidence.Decision decodeDecision( + ActorStagingEligibilityDecision decision) { + return switch (decision) { + case STAGING_ELIGIBLE -> AccountActorStagingEligibilityEvidence.Decision.STAGING_ELIGIBLE; + case STAGING_INELIGIBLE -> AccountActorStagingEligibilityEvidence.Decision.STAGING_INELIGIBLE; + default -> throw new IllegalArgumentException("Unknown Account actor-staging decision"); + }; + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static CommonGrpcClientProperties requireEntityManagementMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Entity Management gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Actor-staging eligibility reads require Entity Management workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Actor-staging eligibility reads require Entity Management certificate, key, and CA " + + "files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Actor-staging eligibility reads require file-backed Entity Management workload mTLS"); + } + return tlsProps; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java new file mode 100644 index 0000000000..f9d54c2164 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClient.java @@ -0,0 +1,163 @@ +package net.firedevops.firemud.entitymanagement.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityRequest; +import net.firedevops.firemud.account.v1.ResolveRuntimeAccountIdentityResponse; +import net.firedevops.firemud.account.v1.RuntimeAccountIdentityServiceGrpc; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Unwired Entity Management candidate for exact Account-owned runtime identity reads. */ +public final class AccountRuntimeIdentityClient + extends AbstractReloadingBlockingGrpcClient< + RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + + public AccountRuntimeIdentityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireEntityManagementMtls(tlsProps), + channelFactory, + AccountRuntimeIdentityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "Entity Management workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes the client only when an explicit caller owns activation of this handoff. */ + public void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub buildStub( + ManagedChannel channel) { + return RuntimeAccountIdentityServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service")) + .withCompression("gzip"); + } + + /** Reads Account's exact persisted identity provenance without granting gameplay authority. */ + public RuntimeAccountIdentityEvidence resolveRuntimeAccountIdentity( + String canonicalAccountId, String requestId) { + UUID accountUuid = parseCanonicalNonNilUuid(canonicalAccountId, "canonical account ID"); + UUID requestUuid = parseCanonicalNonNilUuid(requestId, "request ID"); + RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub currentStub = + stub(); + if (currentStub == null) { + throw new IllegalStateException("Account runtime identity client is not initialized"); + } + + ResolveRuntimeAccountIdentityResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveRuntimeAccountIdentity( + ResolveRuntimeAccountIdentityRequest.newBuilder() + .setCanonicalAccountId(accountUuid.toString()) + .setRequestId(requestUuid.toString()) + .build()); + if (response == null) { + throw new IllegalStateException("Account runtime identity response is absent"); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException( + "Account runtime identity response contains unsupported fields"); + } + + RuntimeAccountIdentityEvidence evidence; + try { + evidence = + new RuntimeAccountIdentityEvidence( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getRequestId(), "response request ID"), + parseCanonicalNonNilUuid( + response.getCanonicalAccountId(), "response canonical account ID"), + response.getSourceAccountRowId(), + response.getAccountUuidProvenance()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Account runtime identity response is invalid", exception); + } + + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !requestUuid.equals(evidence.requestId()) + || !accountUuid.equals(evidence.canonicalAccountId())) { + throw new IllegalStateException( + "Account runtime identity response does not match the exact request"); + } + return evidence; + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static CommonGrpcClientProperties requireEntityManagementMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Entity Management gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Runtime account identity reads require Entity Management workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Runtime account identity reads require Entity Management certificate, key, and CA files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Runtime account identity reads require file-backed Entity Management workload mTLS"); + } + return tlsProps; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java new file mode 100644 index 0000000000..0f2f10ad9a --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java @@ -0,0 +1,137 @@ +package net.firedevops.firemud.entitymanagement.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; + +/** Entity client for closed, non-admitting Game Session roster-owner source evidence. */ +public final class GameSessionCanonicalGameplayRosterOwnerReadClient + extends AbstractReloadingBlockingGrpcClient< + CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private final GrpcServerPeerIdentityClientInterceptor serverPeerIdentityInterceptor; + + public GameSessionCanonicalGameplayRosterOwnerReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireEntityManagementMtls(tlsProps), + channelFactory, + GameSessionCanonicalGameplayRosterOwnerReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "Entity Management workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.serverPeerIdentityInterceptor = + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"); + } + + /** Initializes file-backed mTLS only when the explicit owner-read switch is enabled. */ + public void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceBlockingStub + buildStub(ManagedChannel channel) { + return CanonicalGameplayRosterOwnerReadServiceGrpc.newBlockingStub(channel) + .withInterceptors(serverPeerIdentityInterceptor) + .withCompression("gzip"); + } + + /** + * Reads complete request-bound owner source evidence. It is not Account authority, actor + * ownership by itself, or gameplay admission. + */ + public CanonicalGameplayRosterOwnerReadEvidence getCanonicalGameplayRosterOwnerRead( + CanonicalGameplayRosterOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Gameplay roster owner read target namespace does not match Entity Management"); + } + + CanonicalGameplayRosterOwnerReadServiceGrpc.CanonicalGameplayRosterOwnerReadServiceBlockingStub + currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException( + "Game Session canonical gameplay roster owner read client is not initialized"); + } + + GetCanonicalGameplayRosterOwnerReadResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCanonicalGameplayRosterOwnerRead( + CanonicalGameplayRosterOwnerReadGrpcCodec.toRequest(request)); + if (response == null) { + throw new IllegalStateException( + "Game Session canonical gameplay roster owner read response is absent"); + } + + try { + return CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Session canonical gameplay roster owner read response is invalid", exception); + } + } + + private static CommonGrpcClientProperties requireEntityManagementMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Entity Management gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Gameplay roster owner reads require Entity Management workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Gameplay roster owner reads require Entity Management certificate, key, and CA files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Gameplay roster owner reads require file-backed Entity Management workload mTLS"); + } + return tlsProps; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java new file mode 100644 index 0000000000..b4c352bc88 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.entitymanagement.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadGrpcCodec; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadResponse; + +/** Entity client for the selector-only, non-admitting Game Session assignment source read. */ +public final class GameSessionPreseededActorAssignmentOwnerReadClient + extends AbstractReloadingBlockingGrpcClient< + CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private final GrpcServerPeerIdentityClientInterceptor serverPeerIdentityInterceptor; + + public GameSessionPreseededActorAssignmentOwnerReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireEntityManagementMtls(tlsProps), + channelFactory, + GameSessionPreseededActorAssignmentOwnerReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "Entity Management workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.serverPeerIdentityInterceptor = + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"); + } + + /** Initializes file-backed workload mTLS only when run-owned assignment is enabled. */ + public void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceBlockingStub + buildStub(ManagedChannel channel) { + return CanonicalGameplayRosterOwnerReadServiceGrpc.newBlockingStub(channel) + .withInterceptors(serverPeerIdentityInterceptor) + .withCompression("gzip"); + } + + /** + * Reads complete, request-bound source evidence. The request intentionally has no pointer or + * active-epoch counters; Game Session derives those from its current owner rows. + */ + public PreseededActorAssignmentOwnerReadEvidence getPreseededActorAssignmentOwnerRead( + PreseededActorAssignmentOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Actor assignment owner read target namespace does not match Entity Management"); + } + + var currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException( + "Game Session actor assignment owner read client is not initialized"); + } + GetPreseededActorAssignmentOwnerReadResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getPreseededActorAssignmentOwnerRead( + PreseededActorAssignmentOwnerReadGrpcCodec.toRequest(request)); + if (response == null) { + throw new IllegalStateException("Game Session actor assignment owner response is absent"); + } + try { + return PreseededActorAssignmentOwnerReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Session actor assignment owner response is invalid", exception); + } + } + + private static CommonGrpcClientProperties requireEntityManagementMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Entity Management gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Actor assignment owner reads require Entity Management workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Actor assignment owner reads require Entity certificate, key, and CA files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Actor assignment owner reads require file-backed Entity workload mTLS"); + } + return tlsProps; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfiguration.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfiguration.java new file mode 100644 index 0000000000..0ab7e890c9 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfiguration.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.entitymanagement.config; + +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.security.CanonicalGameplayRosterPeerInterceptor; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSelectedAssignmentService; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterService; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.grpc.server.GlobalServerInterceptor; + +/** Wires guarded roster discovery with default-off mTLS Game Session owner evidence. */ +@Configuration +public class CanonicalGameplayRosterConfiguration { + @Bean + @ConditionalOnProperty( + prefix = "firemud.canonical-gameplay-roster-owner-read", + name = "enabled", + havingValue = "false", + matchIfMissing = true) + @ConditionalOnMissingBean(CanonicalGameplayRosterOwnerEvidencePort.class) + public CanonicalGameplayRosterOwnerEvidencePort + unavailableCanonicalGameplayRosterOwnerEvidence() { + return request -> { + throw new CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException(); + }; + } + + @Bean(initMethod = "init", destroyMethod = "close") + @ConditionalOnProperty( + prefix = "firemud.canonical-gameplay-roster-owner-read", + name = "enabled", + havingValue = "true") + @ConditionalOnMissingBean({ + CanonicalGameplayRosterOwnerEvidencePort.class, + GameSessionCanonicalGameplayRosterOwnerReadClient.class + }) + public GameSessionCanonicalGameplayRosterOwnerReadClient + gameSessionCanonicalGameplayRosterOwnerReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new GameSessionCanonicalGameplayRosterOwnerReadClient( + endpoints, tlsProperties, channelFactory, workloadNamespace); + } + + @Bean + @ConditionalOnProperty( + prefix = "firemud.canonical-gameplay-roster-owner-read", + name = "enabled", + havingValue = "true") + @ConditionalOnMissingBean(CanonicalGameplayRosterOwnerEvidencePort.class) + public CanonicalGameplayRosterOwnerEvidencePort + gameSessionCanonicalGameplayRosterOwnerEvidencePort( + GameSessionCanonicalGameplayRosterOwnerReadClient ownerReadClient, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter( + ownerReadClient, workloadNamespace); + } + + @Bean + @ConditionalOnMissingBean + public CanonicalGameplayRosterService canonicalGameplayRosterService( + CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort, + CharacterRepository characterRepository) { + return new CanonicalGameplayRosterService(ownerEvidencePort, characterRepository); + } + + @Bean + @ConditionalOnMissingBean + public CanonicalGameplayRosterSelectedAssignmentService + canonicalGameplayRosterSelectedAssignmentService( + CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort, + CharacterRepository characterRepository) { + return new CanonicalGameplayRosterSelectedAssignmentService( + ownerEvidencePort, characterRepository); + } + + @Bean + @GlobalServerInterceptor + public CanonicalGameplayRosterPeerInterceptor canonicalGameplayRosterPeerInterceptor( + @Value("${firemud.grpc.workload-namespace:}") String trustedNamespace) { + return new CanonicalGameplayRosterPeerInterceptor(trustedNamespace); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java new file mode 100644 index 0000000000..04bace5558 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java @@ -0,0 +1,248 @@ +package net.firedevops.firemud.entitymanagement.config; + +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.entitymanagement.client.AccountPreseededActorStagingEligibilityClient; +import net.firedevops.firemud.entitymanagement.client.AccountRuntimeIdentityClient; +import net.firedevops.firemud.entitymanagement.client.GameSessionPreseededActorAssignmentOwnerReadClient; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAccountIdentityPort; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceiptService; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentService; +import net.firedevops.firemud.entitymanagement.service.PreseededActorStagingEligibilityPort; +import net.firedevops.firemud.entitymanagement.service.RunOwnedPreseededActorAssignmentAuthorityAdapter; +import net.firedevops.firemud.entitymanagement.service.RunOwnedPreseededAssignmentAuthority; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionPreseededActorAssignmentOwnerEvidenceAdapter; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Wires the bounded Entity writer while leaving Account/owner evidence and run authorization denied + * unless their explicitly enabled producers are present. + */ +@Configuration +public class PreseededActorAssignmentConfiguration { + @Bean + @ConditionalOnProperty( + prefix = "firemud.run-owned-preseeded-actor-assignment", + name = "enabled", + havingValue = "false", + matchIfMissing = true) + @ConditionalOnMissingBean(PreseededActorAccountIdentityPort.class) + public PreseededActorAccountIdentityPort disabledPreseededActorAccountIdentityPort() { + return (accountUuid, assignmentUuid) -> { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_IDENTITY_UNAVAILABLE"); + }; + } + + @Bean(initMethod = "init", destroyMethod = "close") + @ConditionalOnProperty( + prefix = "firemud.run-owned-preseeded-actor-assignment", + name = "enabled", + havingValue = "true") + @ConditionalOnMissingBean({ + PreseededActorAccountIdentityPort.class, + AccountRuntimeIdentityClient.class + }) + public AccountRuntimeIdentityClient preseededActorAccountIdentityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @org.springframework.beans.factory.annotation.Value("${firemud.grpc.workload-namespace:}") + String workloadNamespace) { + return new AccountRuntimeIdentityClient( + endpoints, tlsProperties, channelFactory, workloadNamespace); + } + + @Bean + @ConditionalOnProperty( + prefix = "firemud.run-owned-preseeded-actor-assignment", + name = "enabled", + havingValue = "true") + @ConditionalOnMissingBean(PreseededActorAccountIdentityPort.class) + public PreseededActorAccountIdentityPort enabledPreseededActorAccountIdentityPort( + AccountRuntimeIdentityClient accountIdentityClient) { + return accountIdentityClient::resolveRuntimeAccountIdentity; + } + + @Bean + @ConditionalOnProperty( + prefix = "firemud.run-owned-preseeded-actor-assignment", + name = "enabled", + havingValue = "false", + matchIfMissing = true) + @ConditionalOnMissingBean(PreseededActorStagingEligibilityPort.class) + public PreseededActorStagingEligibilityPort disabledPreseededActorStagingEligibilityPort() { + return (accountUuid, tenantUuid, assignmentUuid) -> { + throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_STAGING_EVIDENCE_UNAVAILABLE"); + }; + } + + @Bean(initMethod = "init", destroyMethod = "close") + @ConditionalOnProperty( + prefix = "firemud.run-owned-preseeded-actor-assignment", + name = "enabled", + havingValue = "true") + @ConditionalOnMissingBean({ + PreseededActorStagingEligibilityPort.class, + AccountPreseededActorStagingEligibilityClient.class + }) + public AccountPreseededActorStagingEligibilityClient preseededActorStagingEligibilityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @org.springframework.beans.factory.annotation.Value("${firemud.grpc.workload-namespace:}") + String workloadNamespace) { + return new AccountPreseededActorStagingEligibilityClient( + endpoints, tlsProperties, channelFactory, workloadNamespace); + } + + @Bean(initMethod = "init", destroyMethod = "close") + @ConditionalOnProperty( + prefix = "firemud.run-owned-preseeded-actor-assignment", + name = "enabled", + havingValue = "true") + @ConditionalOnMissingBean({ + PreseededActorAssignmentOwnerEvidencePort.class, + GameSessionPreseededActorAssignmentOwnerReadClient.class + }) + public GameSessionPreseededActorAssignmentOwnerReadClient preseededActorAssignmentOwnerReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @org.springframework.beans.factory.annotation.Value("${firemud.grpc.workload-namespace:}") + String workloadNamespace) { + return new GameSessionPreseededActorAssignmentOwnerReadClient( + endpoints, tlsProperties, channelFactory, workloadNamespace); + } + + @Bean + @ConditionalOnProperty( + prefix = "firemud.run-owned-preseeded-actor-assignment", + name = "enabled", + havingValue = "true") + @ConditionalOnMissingBean(PreseededActorAssignmentOwnerEvidencePort.class) + public PreseededActorAssignmentOwnerEvidencePort preseededActorAssignmentOwnerEvidencePort( + GameSessionPreseededActorAssignmentOwnerReadClient gameSessionClient, + @org.springframework.beans.factory.annotation.Value("${firemud.grpc.workload-namespace:}") + String workloadNamespace) { + return new GameSessionPreseededActorAssignmentOwnerEvidenceAdapter( + gameSessionClient, workloadNamespace); + } + + @Bean + @ConditionalOnProperty( + prefix = "firemud.run-owned-preseeded-actor-assignment", + name = "enabled", + havingValue = "false", + matchIfMissing = true) + @ConditionalOnMissingBean(RunOwnedPreseededAssignmentAuthority.class) + public RunOwnedPreseededAssignmentAuthority disabledRunOwnedPreseededAssignmentAuthority() { + return new RunOwnedPreseededAssignmentAuthority() { + @Override + public void requireAuthorized(PreseededActorAssignmentRequest request, Action action) { + throw new AdminAuthorizationException( + "PRESEEDED_ASSIGNMENT_RUN_OWNED_ACTION_GRANT_UNAVAILABLE"); + } + + @Override + public void requireTargetBoundAuthorized( + PreseededActorAssignmentRequest request, + PreseededActorAssignmentOwnerEvidence target, + Action action) { + throw new AdminAuthorizationException( + "PRESEEDED_ASSIGNMENT_RUN_OWNED_ACTION_GRANT_UNAVAILABLE"); + } + }; + } + + @Bean + @ConditionalOnProperty( + prefix = "firemud.run-owned-preseeded-actor-assignment", + name = "enabled", + havingValue = "true") + @ConditionalOnMissingBean(RunOwnedPreseededAssignmentAuthority.class) + public RunOwnedPreseededAssignmentAuthority runOwnedPreseededAssignmentAuthorityFromCapability( + @org.springframework.beans.factory.annotation.Value( + "${firemud.run-owned-preseeded-actor-assignment.capability-path:}") + String capabilityPath, + @org.springframework.beans.factory.annotation.Value( + "${firemud.run-owned-preseeded-actor-assignment.run-id:}") + String runId, + @org.springframework.beans.factory.annotation.Value( + "${firemud.run-owned-preseeded-actor-assignment.compose-project-name:}") + String composeProjectName, + @org.springframework.beans.factory.annotation.Value("${firemud.grpc.workload-namespace:}") + String workloadNamespace, + @org.springframework.beans.factory.annotation.Value( + "${spring.ssl.bundle.pem.firemud-grpc.truststore.certificate:}") + String entityServerTrustRoot, + @org.springframework.beans.factory.annotation.Value("${spring.grpc.server.ssl.bundle:}") + String activeServerTlsBundleName, + SslBundles sslBundles) { + return RunOwnedPreseededActorAssignmentAuthorityAdapter.forActiveServerTrustBundle( + capabilityPath, + runId, + composeProjectName, + workloadNamespace, + sslBundles, + activeServerTlsBundleName, + entityServerTrustRoot); + } + + /** + * The enabled source adapter combines one current Account staging snapshot with exact current + * Game Session/Game Design selectors. Account status is a point-in-time observation, not a held + * JOIN authorization, PLAY grant, or gameplay admission decision; persisted assignments do not + * authorize runtime admission or activation. + */ + @Bean + @ConditionalOnProperty( + prefix = "firemud.run-owned-preseeded-actor-assignment", + name = "enabled", + havingValue = "false", + matchIfMissing = true) + @ConditionalOnMissingBean(PreseededActorAssignmentOwnerEvidencePort.class) + public PreseededActorAssignmentOwnerEvidencePort + unavailablePreseededActorAssignmentOwnerEvidencePort() { + return (PreseededActorAssignmentRequest request, + RuntimeAccountIdentityEvidence accountIdentityEvidence, + AccountActorStagingEligibilityEvidence stagingEligibilityEvidence) -> { + throw new PreseededActorAssignmentOwnerEvidencePort.OwnerEvidenceUnavailableException(); + }; + } + + @Bean + @ConditionalOnMissingBean + public PreseededActorAssignmentService preseededActorAssignmentService( + RunOwnedPreseededAssignmentAuthority runAuthority, + PreseededActorAccountIdentityPort accountIdentityPort, + PreseededActorStagingEligibilityPort stagingEligibilityPort, + PreseededActorAssignmentOwnerEvidencePort ownerEvidencePort, + CharacterRepository characterRepository) { + return new PreseededActorAssignmentService( + runAuthority, + accountIdentityPort, + stagingEligibilityPort, + ownerEvidencePort, + characterRepository); + } + + /** Receipt reads are read-only and remain available when assignment creation is disabled. */ + @Bean + @ConditionalOnMissingBean + public PreseededActorAssignmentReceiptService preseededActorAssignmentReceiptService( + CharacterRepository characterRepository) { + return new PreseededActorAssignmentReceiptService(characterRepository); + } +} 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 8a219fcebf..4957f06336 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,29 +2,146 @@ 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.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) { @@ -146,6 +263,989 @@ public long countQuarantinedByTenantId(Long tenantId) { CHARACTERS.TENANT_ID.eq(tenantId).and(CHARACTERS.ACTOR_IDENTITY_STATUS.eq("QUARANTINED"))); } + /** + * 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)) + || !"OWNER_RESOLVED".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 + 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) { + dsl.insertInto(TENANT_IDENTITIES) + .set(CANONICAL_TENANT_UUID, tenantUuid) + .onConflict(CANONICAL_TENANT_UUID) + .doNothing() + .execute(); + 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 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); + requireEntityTenantRow(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(); + + 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()))) + .forUpdate() + .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("OWNER_RESOLVED")) + .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(); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java new file mode 100644 index 0000000000..19e5d350c3 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.entitymanagement.security; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Certificate-only guard for canonical roster reads; unrelated RPCs pass through unchanged. */ +public final class CanonicalGameplayRosterPeerInterceptor implements ServerInterceptor { + public static final String METHOD_NAME = + "entity_management.v1.CanonicalGameplayRosterService/ListPreseededRoster"; + public static final String SELECTED_ASSIGNMENT_METHOD_NAME = + "entity_management.v1.CanonicalGameplayRosterService/ReadSelectedPreseededAssignment"; + private static final Context.Key VERIFIED_GAME_SESSION_PEER = + Context.key("firemud-canonical-gameplay-roster-peer"); + + private final String trustedNamespace; + + public CanonicalGameplayRosterPeerInterceptor(String trustedNamespace) { + this.trustedNamespace = + GrpcPeerIdentity.isValidNamespace(trustedNamespace) ? trustedNamespace : ""; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + String methodName = call.getMethodDescriptor().getFullMethodName(); + if (!METHOD_NAME.equals(methodName) && !SELECTED_ASSIGNMENT_METHOD_NAME.equals(methodName)) { + return next.startCall(call, headers); + } + + GrpcPeerIdentity peer = + GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) + .orElse(null); + if (!isTrustedGameSessionPeer(peer, trustedNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + call.close( + Status.PERMISSION_DENIED.withDescription("Trusted Game Session peer required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + + Context context = + Context.current() + .withValue(VERIFIED_GAME_SESSION_PEER, peer) + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + return Contexts.interceptCall(context, call, headers, next); + } + + public static boolean isTrustedGameSessionPeer(GrpcPeerIdentity peer, String expectedNamespace) { + return peer != null + && GrpcPeerIdentity.isValidNamespace(expectedNamespace) + && peer.isService("game-session-service") + && peer.isInNamespace(expectedNamespace); + } + + public static GrpcPeerIdentity currentVerifiedPeer() { + return VERIFIED_GAME_SESSION_PEER.get(); + } +} 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..e93400cf4f --- /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.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..b31dc3e8a6 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentService.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.entitymanagement.service; + +import java.util.Objects; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +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 + || target.playableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) { + 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..baba148e4b --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentGrantIntentDigest.java @@ -0,0 +1,56 @@ +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; + +/** Computes the assignment digest from the caller target before any owner reads are performed. */ +final class PreseededActorAssignmentGrantIntentDigest { + private static final String DOMAIN = "firemud.entity.preseeded-actor-assignment.v4"; + + private PreseededActorAssignmentGrantIntentDigest() {} + + static String compute(PreseededActorAssignmentRequest request) { + var target = request.expectedTarget(); + 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, target.canonicalTenantUuid().toString()); + write(output, target.realmUuid().toString()); + write(output, target.worldSlug()); + write(output, target.realmSlug()); + write(output, target.gameInstanceId()); + write(output, Long.toString(target.catalogRevision())); + write(output, target.canonicalVersionUuid().toString()); + write(output, target.frozenPolicyDigest()); + write(output, target.playableStateNamespaceId().toString()); + write(output, target.publishedReleaseBundleRef()); + write(output, target.playableStateScope().name()); + write( + output, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY.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 grant intent", 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/PreseededActorAssignmentIntentDigest.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java new file mode 100644 index 0000000000..1b5752cf03 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentIntentDigest.java @@ -0,0 +1,54 @@ +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; + +/** 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 compute( + PreseededActorAssignmentRequest request, PreseededActorAssignmentOwnerEvidence evidence) { + 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, evidence.canonicalTenantUuid().toString()); + write(output, evidence.realmUuid().toString()); + write(output, evidence.worldSlug()); + write(output, evidence.realmSlug()); + write(output, evidence.gameInstanceId()); + write(output, Long.toString(evidence.catalogRevision())); + write(output, evidence.canonicalVersionUuid().toString()); + write(output, evidence.frozenPolicyDigest()); + write(output, evidence.playableStateNamespaceId().toString()); + write(output, evidence.publishedReleaseBundleRef()); + write(output, evidence.playableStateScope().name()); + write(output, evidence.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 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..ae90c2ebcd --- /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() > 256 + || !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/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java new file mode 100644 index 0000000000..f571593630 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java @@ -0,0 +1,382 @@ +package net.firedevops.firemud.entitymanagement.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.annotation.Timed; +import io.micrometer.core.instrument.MeterRegistry; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.security.CanonicalGameplayRosterPeerInterceptor; +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.CanonicalGameplayRosterOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSelectedAssignmentReadRequest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSelectedAssignmentReference; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSelectedAssignmentService; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterService; +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.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget.Builder; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.jooq.exception.DataAccessException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.grpc.server.service.GrpcService; + +/** Dedicated certificate-guarded non-admitting canonical roster gRPC boundary. */ +@GrpcService +public final class CanonicalGameplayRosterGrpcAdapter + extends CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceImplBase { + private static final Logger LOGGER = + LoggerFactory.getLogger(CanonicalGameplayRosterGrpcAdapter.class); + private static final String OPERATION = "CanonicalGameplayRoster.ListPreseededRoster"; + private static final String SELECTED_ASSIGNMENT_OPERATION = + "CanonicalGameplayRoster.ReadSelectedPreseededAssignment"; + + private final CanonicalGameplayRosterService rosterService; + private final CanonicalGameplayRosterSelectedAssignmentService selectedAssignmentService; + private final MeterRegistry meterRegistry; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected services and meter registry remain internal to the gRPC adapter.") + public CanonicalGameplayRosterGrpcAdapter( + CanonicalGameplayRosterService rosterService, + CanonicalGameplayRosterSelectedAssignmentService selectedAssignmentService, + MeterRegistry meterRegistry) { + this.rosterService = rosterService; + this.selectedAssignmentService = selectedAssignmentService; + this.meterRegistry = meterRegistry; + } + + @Override + @Timed(value = "entityGrpc.canonicalGameplayRoster.listPreseeded") + public void listPreseededRoster( + CanonicalGameplayRosterRequest request, + StreamObserver responseObserver) { + CanonicalGameplayRosterResponse response; + try { + requireTrustedPeer(); + CanonicalGameplayRosterReadRequest parsed = parseRequest(request); + CanonicalGameplayRosterSnapshot snapshot = rosterService.read(parsed); + response = toResponse(snapshot); + } catch (Exception failure) { + responseObserver.onError(toStatus(failure, OPERATION)); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + @Override + @Timed(value = "entityGrpc.canonicalGameplayRoster.readSelectedPreseededAssignment") + public void readSelectedPreseededAssignment( + CanonicalGameplayRosterSelectedAssignmentRequest request, + StreamObserver responseObserver) { + CanonicalGameplayRosterSelectedAssignmentResponse response; + try { + requireTrustedPeer(); + CanonicalGameplayRosterSelectedAssignmentReadRequest parsed = + parseSelectedAssignmentRequest(request); + CanonicalGameplayRosterSelectedAssignmentReference reference = + selectedAssignmentService.read(parsed); + response = toSelectedAssignmentResponse(reference); + } catch (Exception failure) { + responseObserver.onError(toStatus(failure, SELECTED_ASSIGNMENT_OPERATION)); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + static CanonicalGameplayRosterSelectedAssignmentReadRequest parseSelectedAssignmentRequest( + CanonicalGameplayRosterSelectedAssignmentRequest request) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Request is absent or contains unknown fields"); + } + if (!request.hasExpectedTarget()) { + throw new IllegalArgumentException("Complete expected target is required"); + } + if (!request.hasExpectedSnapshot() + || !request.getExpectedSnapshot().getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Exact expected_snapshot is required"); + } + UUID selectedCharacterUuid = + parseCanonicalUuid(request.getSelectedCharacterUuid(), "selected_character_uuid"); + CanonicalGameplayRosterReadRequest parsedTarget = + parseRequest( + CanonicalGameplayRosterRequest.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setExpectedTarget(request.getExpectedTarget()) + .setPlayerExecutionContext(request.getPlayerExecutionContext()) + .build(), + true); + return new CanonicalGameplayRosterSelectedAssignmentReadRequest( + parsedTarget.requestUuid(), + parsedTarget.canonicalAccountUuid(), + selectedCharacterUuid, + parsedTarget.expectedTarget(), + parseSnapshotReference(request.getExpectedSnapshot()), + parsedTarget.playerExecutionContext()); + } + + static CanonicalGameplayRosterReadRequest parseRequest(CanonicalGameplayRosterRequest request) { + return parseRequest(request, false); + } + + private static CanonicalGameplayRosterReadRequest parseRequest( + CanonicalGameplayRosterRequest request, boolean selectedAssignment) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Request is absent or contains unknown fields"); + } + if (!request.hasExpectedTarget() + || !request.getExpectedTarget().getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Complete expected target is required"); + } + var target = request.getExpectedTarget(); + UUID requestUuid = parseCanonicalUuid(request.getRequestUuid(), "request_uuid"); + UUID accountUuid = + parseCanonicalUuid(request.getCanonicalAccountUuid(), "canonical_account_uuid"); + if (!request.hasPlayerExecutionContext()) { + throw new IllegalArgumentException("player_execution_context is required"); + } + CanonicalGameplayRosterExecutionContext executionContext = + parseExecutionContext(request.getPlayerExecutionContext()); + if (!selectedAssignment && executionContext.characterUuid() != null) { + throw new IllegalArgumentException("character_id must be unset for roster discovery"); + } + PlayableStateScope scope = target.getPlayableStateScope(); + if (scope == PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED + || scope == PlayableStateScope.UNRECOGNIZED) { + throw new IllegalArgumentException("playable_state_scope is required"); + } + CanonicalGameplayRosterEntryPolicy entryPolicy = + switch (target.getEntryPolicy()) { + case CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED -> + CanonicalGameplayRosterEntryPolicy.PLAYER_CREATED; + case CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY -> + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY; + case CANONICAL_ROSTER_ENTRY_POLICY_AUTO_PROVISIONED -> + CanonicalGameplayRosterEntryPolicy.AUTO_PROVISIONED; + case CANONICAL_ROSTER_ENTRY_POLICY_UNSPECIFIED, UNRECOGNIZED -> + CanonicalGameplayRosterEntryPolicy.UNSPECIFIED; + }; + CanonicalGameplayRosterTarget expectedTarget = + new CanonicalGameplayRosterTarget( + parseCanonicalUuid(target.getTenantUuid(), "tenant_uuid"), + parseCanonicalUuid(target.getRealmUuid(), "realm_uuid"), + target.getWorldSlug(), + target.getRealmSlug(), + parseCanonicalUuid(target.getGameInstanceUuid(), "game_instance_uuid"), + target.getCatalogRevision(), + target.getPointerVersion(), + target.getActiveWorldEpoch(), + parseCanonicalUuid(target.getCanonicalVersionUuid(), "canonical_version_uuid"), + target.getPublishedPolicyDigest(), + target.getPublishedReleaseBundleRef(), + target.getAdmissionPointerSnapshotDigest(), + target.getPublishedOwnerProofDigest(), + parseCanonicalUuid( + target.getPlayableStateNamespaceUuid(), "playable_state_namespace_uuid"), + scope, + entryPolicy); + executionContext.requireTargetBinding(requestUuid, accountUuid, expectedTarget); + return new CanonicalGameplayRosterReadRequest( + requestUuid, accountUuid, expectedTarget, executionContext); + } + + private static CanonicalGameplayRosterExecutionContext parseExecutionContext( + PlayerExecutionContext context) { + if (context == null || !context.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "player_execution_context is absent or contains unknown fields"); + } + PlayableStateScope scope = + switch (context.getPlayableStateScope()) { + case "SHARED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + case "ISOLATED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; + default -> + throw new IllegalArgumentException( + "player_execution_context.playable_state_scope must be SHARED or ISOLATED"); + }; + UUID characterUuid = + context.getCharacterId().isEmpty() + ? null + : parseCanonicalUuid(context.getCharacterId(), "player_execution_context.character_id"); + return new CanonicalGameplayRosterExecutionContext( + parseCanonicalUuid(context.getAccountId(), "player_execution_context.account_id"), + parseCanonicalUuid(context.getTenantId(), "player_execution_context.tenant_id"), + parseCanonicalUuid( + context.getPlayableStateNamespaceId(), + "player_execution_context.playable_state_namespace_id"), + parseCanonicalUuid( + context.getGameInstanceId(), "player_execution_context.game_instance_id"), + characterUuid, + parseCanonicalUuid(context.getSessionId(), "player_execution_context.session_id"), + parseCanonicalUuid(context.getRealmId(), "player_execution_context.realm_id"), + parseCanonicalUuid(context.getRequestId(), "player_execution_context.request_id"), + scope); + } + + private static CanonicalGameplayRosterSnapshotReference parseSnapshotReference( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference ref) { + return new CanonicalGameplayRosterSnapshotReference( + parseCanonicalUuid(ref.getSnapshotUuid(), "expected_snapshot.snapshot_uuid"), + ref.getSnapshotDigest()); + } + + private static UUID parseCanonicalUuid(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(fieldName + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID", invalid); + } + if (parsed.equals(new UUID(0L, 0L)) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private void requireTrustedPeer() { + if (CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer() == null) { + throw new UnauthenticatedPeerException(); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException("Trusted Game Session certificate peer is required"); + } + } + + private RuntimeException toStatus(Exception failure, String operation) { + if (failure instanceof UnauthenticatedPeerException) { + return Status.UNAUTHENTICATED + .withDescription("Authenticated Game Session peer required") + .asRuntimeException(); + } + if (failure instanceof AdminAuthorizationException) { + return Status.PERMISSION_DENIED + .withDescription("Trusted Game Session caller required") + .asRuntimeException(); + } + if (failure + instanceof CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException + || failure instanceof DataAccessException) { + return Status.UNAVAILABLE + .withDescription("Owner evidence is unavailable") + .asRuntimeException(); + } + if (failure instanceof UnsupportedOperationException) { + return Status.FAILED_PRECONDITION + .withDescription("Target policy or scope is unsupported") + .asRuntimeException(); + } + if (failure instanceof IllegalArgumentException) { + return Status.INVALID_ARGUMENT + .withDescription("Request is malformed or inconsistent") + .asRuntimeException(); + } + if (failure instanceof IllegalStateException) { + return Status.FAILED_PRECONDITION + .withDescription("Request precondition is not satisfied") + .asRuntimeException(); + } + GrpcAppErrors.internal(meterRegistry, LOGGER, operation, failure); + return Status.INTERNAL.withDescription("Internal error").asRuntimeException(); + } + + private CanonicalGameplayRosterResponse toResponse(CanonicalGameplayRosterSnapshot snapshot) { + CanonicalGameplayRosterResponse.Builder response = + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(snapshot.canonicalAccountUuid().toString()) + .setTarget(toProto(snapshot.target())) + .setSnapshotUuid(snapshot.snapshotUuid().toString()) + .setSnapshotDigest(snapshot.snapshotDigest()); + for (CanonicalGameplayRosterActor actor : snapshot.actors()) { + response.addActors( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(actor.characterUuid().toString()) + .setDisplayName(actor.displayName()) + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER)); + } + return response.build(); + } + + static net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget toProto( + CanonicalGameplayRosterTarget target) { + Builder proto = + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(target.tenantUuid().toString()) + .setRealmUuid(target.realmUuid().toString()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceUuid(target.gameInstanceUuid().toString()) + .setCatalogRevision(target.catalogRevision()) + .setCanonicalVersionUuid(target.canonicalVersionUuid().toString()) + .setPointerVersion(target.pointerVersion()) + .setActiveWorldEpoch(target.activeWorldEpoch()) + .setPublishedPolicyDigest(target.publishedPolicyDigest()) + .setPublishedReleaseBundleRef(target.publishedReleaseBundleRef()) + .setAdmissionPointerSnapshotDigest(target.admissionPointerSnapshotDigest()) + .setPublishedOwnerProofDigest(target.publishedOwnerProofDigest()) + .setPlayableStateNamespaceUuid(target.playableStateNamespaceId().toString()) + .setPlayableStateScope(target.playableStateScope()); + switch (target.entryPolicy()) { + case PRESEEDED_ONLY -> + proto.setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY); + case PLAYER_CREATED -> + proto.setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED); + case AUTO_PROVISIONED -> + proto.setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_AUTO_PROVISIONED); + case UNSPECIFIED -> + proto.setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_UNSPECIFIED); + } + return proto.build(); + } + + static CanonicalGameplayRosterSelectedAssignmentResponse toSelectedAssignmentResponse( + CanonicalGameplayRosterSelectedAssignmentReference reference) { + return CanonicalGameplayRosterSelectedAssignmentResponse.newBuilder() + .setRequestUuid(reference.requestUuid().toString()) + .setCanonicalAccountUuid(reference.canonicalAccountUuid().toString()) + .setSelectedCharacterUuid(reference.selectedCharacterUuid().toString()) + .setTarget(toProto(reference.target())) + .setAssignmentUuid(reference.assignmentUuid().toString()) + .setIntentDigest(reference.intentDigest()) + .setSnapshot( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference + .newBuilder() + .setSnapshotUuid(reference.snapshot().snapshotUuid().toString()) + .setSnapshotDigest(reference.snapshot().snapshotDigest()) + .build()) + .build(); + } + + private static final class UnauthenticatedPeerException extends RuntimeException { + private static final long serialVersionUID = 1L; + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java new file mode 100644 index 0000000000..d8957a7c90 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java @@ -0,0 +1,235 @@ +package net.firedevops.firemud.entitymanagement.service.impl; + +import java.time.Instant; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** + * Maps exact authenticated Game Session and sealed Game Design source evidence to Entity's roster + * target. + */ +public final class GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter + implements CanonicalGameplayRosterOwnerEvidencePort { + private static final Pattern RAW_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + private final GameSessionCanonicalGameplayRosterOwnerReadClient gameSessionClient; + private final String workloadNamespace; + + public GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter( + GameSessionCanonicalGameplayRosterOwnerReadClient gameSessionClient, + String workloadNamespace) { + this.gameSessionClient = Objects.requireNonNull(gameSessionClient, "gameSessionClient"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "Entity Management workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public CanonicalGameplayRosterOwnerEvidence resolveCurrentTarget( + CanonicalGameplayRosterReadRequest request) { + Objects.requireNonNull(request, "request"); + CanonicalGameplayRosterTarget expected = request.expectedTarget(); + if (expected.playableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || expected.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY) { + throw new IllegalArgumentException( + "Canonical gameplay roster owner read requires SHARED PRESEEDED_ONLY target"); + } + + CanonicalGameplayRosterOwnerReadEvidence.Request ownerReadRequest = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + request.requestUuid(), + request.canonicalAccountUuid(), + workloadNamespace, + expected.tenantUuid(), + expected.worldSlug(), + expected.realmUuid(), + expected.realmSlug(), + expected.playableStateNamespaceId(), + "SHARED", + expected.gameInstanceUuid(), + expected.canonicalVersionUuid(), + expected.catalogRevision(), + expected.pointerVersion(), + expected.activeWorldEpoch()); + + CanonicalGameplayRosterOwnerReadEvidence evidence; + try { + evidence = gameSessionClient.getCanonicalGameplayRosterOwnerRead(ownerReadRequest); + } catch (RuntimeException unavailable) { + throw new OwnerEvidenceUnavailableException(unavailable); + } + if (evidence == null || !ownerReadRequest.equals(evidence.request())) { + throw new OwnerEvidenceUnavailableException(); + } + + try { + return mapCompleteEvidence(request, ownerReadRequest, evidence); + } catch (RuntimeException invalid) { + if (invalid instanceof OwnerEvidenceUnavailableException unavailable) { + throw unavailable; + } + throw new OwnerEvidenceUnavailableException(invalid); + } + } + + private CanonicalGameplayRosterOwnerEvidence mapCompleteEvidence( + CanonicalGameplayRosterReadRequest request, + CanonicalGameplayRosterOwnerReadEvidence.Request ownerReadRequest, + CanonicalGameplayRosterOwnerReadEvidence evidence) { + if (!request.requestUuid().equals(evidence.request().requestUuid()) + || !request.canonicalAccountUuid().equals(evidence.request().canonicalAccountUuid())) { + throw new IllegalArgumentException("Game Session evidence changed request/account binding"); + } + GameSessionCanonicalInitialAdmissionOwnerProof proof = evidence.gameSessionOwnerProof(); + if (proof == null + || proof.outcome() != GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED + || proof.committedPointerVersion() == null + || proof.committedPointerVersion() <= 0L + || proof.auditEventId() == null + || proof.auditEventId() <= 0L + || proof.positiveDurableAbort() + || proof.terminalAt() == null) { + throw new IllegalArgumentException("Complete terminal COMMITTED Game Session proof required"); + } + + WorldCanonicalInitialAdmissionHold.Request holdRequest = proof.holdIdentity().request(); + requireOwnerProofMatches(ownerReadRequest, holdRequest, proof); + + PublishedRealmEntryPolicySetEvidence policySet = evidence.publishedPolicySetEvidence(); + if (policySet != null) { + // Reverify the complete set; its sealed release digest stays bound here, not in a caller + // echo. + policySet = policySet.requireValidDigest(); + } + if (policySet == null + || policySet.policyCount() < 1 + || policySet.policyCount() != policySet.policies().size() + || !policySet.target().canonicalTenantId().equals(holdRequest.canonicalTenantId()) + || !policySet.target().canonicalVersionId().equals(holdRequest.canonicalVersionId()) + || policySet.versionNumber() <= 0 + || policySet.publicationVersionStateEpoch() <= 0L + || !hasPrefixedDigest(policySet.publishedReleaseBundleDigest()) + || !hasPrefixedDigest(policySet.policySetDigest())) { + throw new IllegalArgumentException( + "Complete sealed Game Design publication evidence required"); + } + + List exactPolicies = + policySet.policies().stream() + .filter( + candidate -> + candidate.policy().worldSlug().equals(holdRequest.worldSlug()) + && candidate.policy().realmSlug().equals(ownerReadRequest.realmSlug())) + .toList(); + if (exactPolicies.size() != 1) { + throw new IllegalArgumentException( + "Exactly one sealed policy for the exact realm is required"); + } + PublishedRealmEntryPolicyEvidence selectedPolicy = exactPolicies.getFirst(); + if (!selectedPolicy.equals(evidence.selectedPolicyEvidence()) + || !selectedPolicy.hasValidDigest(policySet)) { + throw new IllegalArgumentException("Selected sealed realm policy digest is invalid"); + } + RealmEntryPolicy policy = selectedPolicy.policy(); + if (!policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || !policy.worldSlug().equals(holdRequest.worldSlug()) + || !policy.realmSlug().equals(ownerReadRequest.realmSlug())) { + throw new IllegalArgumentException( + "Sealed Game Design route is not visible public-production SHARED PRESEEDED_ONLY"); + } + + // This is the Game Session owner's independently validated current pointer projection digest. + String pointerSnapshotDigest = evidence.admissionPointerSnapshotDigest(); + if (!isRawDigest(pointerSnapshotDigest)) { + throw new IllegalArgumentException( + "Source-owned admission pointer snapshot digest is invalid"); + } + // Entity stores the exact terminal proof digest as raw hex; the proof itself is prefixed. + String ownerProofDigest = rawHexDigest(proof.proofDigest()); + String policyDigest = rawHexDigest(selectedPolicy.policyDigest()); + + CanonicalGameplayRosterTarget resolvedTarget = + new CanonicalGameplayRosterTarget( + holdRequest.canonicalTenantId(), + holdRequest.realmId(), + holdRequest.worldSlug(), + policy.realmSlug(), + holdRequest.canonicalGameInstanceId(), + holdRequest.expectedCatalogRevision(), + proof.committedPointerVersion(), + holdRequest.activeLifecycleEpoch(), + holdRequest.canonicalVersionId(), + policyDigest, + policySet.publishedReleaseBundleRef(), + pointerSnapshotDigest, + ownerProofDigest, + holdRequest.playableStateNamespaceId(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + + return new CanonicalGameplayRosterOwnerEvidence( + evidence.request().requestUuid(), + evidence.request().canonicalAccountUuid(), + resolvedTarget, + Instant.now()); + } + + private static void requireOwnerProofMatches( + CanonicalGameplayRosterOwnerReadEvidence.Request request, + WorldCanonicalInitialAdmissionHold.Request hold, + GameSessionCanonicalInitialAdmissionOwnerProof proof) { + if (!request.targetNamespace().equals(hold.targetNamespace()) + || !request.canonicalTenantUuid().equals(hold.canonicalTenantId()) + || !request.worldSlug().equals(hold.worldSlug()) + || !request.realmUuid().equals(hold.realmId()) + || !request.playableStateNamespaceUuid().equals(hold.playableStateNamespaceId()) + || !request.playableStateScope().equals(hold.playableStateScope()) + || !request.canonicalGameInstanceUuid().equals(hold.canonicalGameInstanceId()) + || !request.canonicalVersionUuid().equals(hold.canonicalVersionId()) + || request.expectedCatalogRevision() != hold.expectedCatalogRevision() + || request.expectedPointerVersion() != proof.committedPointerVersion() + || request.expectedActiveWorldEpoch() != hold.activeLifecycleEpoch()) { + throw new IllegalArgumentException( + "Game Session proof changed the exact route tuple or counters"); + } + } + + private static String rawHexDigest(String digest) { + if (digest != null && PREFIXED_SHA256.matcher(digest).matches()) { + return digest.substring("sha256:".length()); + } + if (isRawDigest(digest)) { + return digest; + } + throw new IllegalArgumentException("Canonical SHA-256 digest is required"); + } + + private static boolean hasPrefixedDigest(String digest) { + return digest != null && PREFIXED_SHA256.matcher(digest).matches(); + } + + private static boolean isRawDigest(String digest) { + return digest != null && RAW_SHA256.matcher(digest).matches(); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapter.java new file mode 100644 index 0000000000..6c54579b4e --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapter.java @@ -0,0 +1,170 @@ +package net.firedevops.firemud.entitymanagement.service.impl; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +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.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.entitymanagement.client.GameSessionPreseededActorAssignmentOwnerReadClient; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; + +/** Maps the exact Game Session source proof and one Account staging snapshot for Entity. */ +public final class GameSessionPreseededActorAssignmentOwnerEvidenceAdapter + implements PreseededActorAssignmentOwnerEvidencePort { + private static final Pattern RAW_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + private final GameSessionPreseededActorAssignmentOwnerReadClient gameSessionClient; + private final String workloadNamespace; + + public GameSessionPreseededActorAssignmentOwnerEvidenceAdapter( + GameSessionPreseededActorAssignmentOwnerReadClient gameSessionClient, + String workloadNamespace) { + this.gameSessionClient = Objects.requireNonNull(gameSessionClient, "gameSessionClient"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "Entity Management workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public PreseededActorAssignmentOwnerEvidence resolveCurrentEligibleTarget( + PreseededActorAssignmentRequest request, + RuntimeAccountIdentityEvidence accountIdentityEvidence, + AccountActorStagingEligibilityEvidence stagingEligibilityEvidence) { + Objects.requireNonNull(request, "request"); + requireExactAccountSnapshots(request, accountIdentityEvidence, stagingEligibilityEvidence); + + var expected = request.expectedTarget(); + if (expected.playableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) { + throw new OwnerEvidenceUnavailableException(); + } + var ownerReadRequest = + new PreseededActorAssignmentOwnerReadEvidence.Request( + request.assignmentUuid(), + request.canonicalAccountUuid(), + workloadNamespace, + expected.canonicalTenantUuid(), + expected.worldSlug(), + expected.realmUuid(), + expected.realmSlug(), + expected.playableStateNamespaceId(), + "SHARED", + canonicalUuid(expected.gameInstanceId(), "gameInstanceId"), + expected.canonicalVersionUuid(), + expected.catalogRevision(), + expected.frozenPolicyDigest(), + expected.publishedReleaseBundleRef()); + + PreseededActorAssignmentOwnerReadEvidence source; + try { + source = gameSessionClient.getPreseededActorAssignmentOwnerRead(ownerReadRequest); + } catch (RuntimeException unavailable) { + throw new OwnerEvidenceUnavailableException(unavailable); + } + if (source == null || !ownerReadRequest.equals(source.request())) { + throw new OwnerEvidenceUnavailableException(); + } + try { + return mapSourceAndAccountSnapshot(request, stagingEligibilityEvidence, source); + } catch (RuntimeException invalid) { + if (invalid instanceof OwnerEvidenceUnavailableException unavailable) { + throw unavailable; + } + throw new OwnerEvidenceUnavailableException(invalid); + } + } + + private PreseededActorAssignmentOwnerEvidence mapSourceAndAccountSnapshot( + PreseededActorAssignmentRequest request, + AccountActorStagingEligibilityEvidence staging, + PreseededActorAssignmentOwnerReadEvidence source) { + var proof = source.sourceEvidence().gameSessionOwnerProof(); + WorldCanonicalInitialAdmissionHold.Request hold = proof.holdIdentity().request(); + PublishedRealmEntryPolicySetEvidence policySet = + source.sourceEvidence().publishedPolicySetEvidence(); + PublishedRealmEntryPolicyEvidence selected = source.sourceEvidence().selectedPolicyEvidence(); + String policyDigest = rawHexDigest(selected.policyDigest()); + String ownerProofDigest = rawHexDigest(proof.proofDigest()); + + return new PreseededActorAssignmentOwnerEvidence( + request.assignmentUuid(), + request.canonicalAccountUuid(), + PreseededActorAssignmentOwnerEvidence.Eligibility.ELIGIBLE, + staging.observedAt(), + staging.membershipAuthorityGeneration(), + staging.eligibilityDecisionDigest(), + hold.canonicalTenantId(), + hold.realmId(), + hold.worldSlug(), + selected.policy().realmSlug(), + hold.canonicalGameInstanceId().toString(), + hold.expectedCatalogRevision(), + hold.canonicalVersionId(), + policyDigest, + hold.playableStateNamespaceId(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + PreseededActorAssignmentOwnerEvidence.PublishedEntryPolicy.PRESEEDED_ONLY, + PreseededActorAssignmentOwnerEvidence.AccountPurpose.PRESEEDED_ACTOR_STAGING, + PreseededActorAssignmentOwnerEvidence.AccountCurrentness.CURRENT_AT_REVALIDATION, + staging.authoritySnapshotDigest(), + ownerProofDigest, + policySet.publishedReleaseBundleRef()); + } + + private void requireExactAccountSnapshots( + PreseededActorAssignmentRequest request, + RuntimeAccountIdentityEvidence identity, + AccountActorStagingEligibilityEvidence staging) { + if (identity == null + || !request.assignmentUuid().equals(identity.requestId()) + || !request.canonicalAccountUuid().equals(identity.canonicalAccountId()) + || !workloadNamespace.equals(identity.targetNamespace())) { + throw new OwnerEvidenceUnavailableException(); + } + if (staging == null + || !request.assignmentUuid().equals(staging.requestId()) + || !request.canonicalAccountUuid().equals(staging.canonicalAccountId()) + || !request.expectedTarget().canonicalTenantUuid().equals(staging.canonicalTenantId()) + || !workloadNamespace.equals(staging.targetNamespace()) + || !identity.accountUuidProvenance().equals(staging.accountUuidProvenance()) + || staging.purpose() + != AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY + || staging.currentness() + != AccountActorStagingEligibilityEvidence.Currentness.CURRENT_AT_REVALIDATION + || staging.decision() != AccountActorStagingEligibilityEvidence.Decision.STAGING_ELIGIBLE) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static UUID canonicalUuid(String value, String name) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, name)); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID", invalid); + } + } + + private static String rawHexDigest(String digest) { + if (digest != null && PREFIXED_SHA256.matcher(digest).matches()) { + return digest.substring("sha256:".length()); + } + if (digest != null && RAW_SHA256.matcher(digest).matches()) { + return digest; + } + throw new IllegalArgumentException("Canonical SHA-256 digest is required"); + } +} 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 3e6052e2ea..5bd8518afb 100644 --- a/services/entity-management-service/src/main/resources/application-prod.yml +++ b/services/entity-management-service/src/main/resources/application-prod.yml @@ -4,11 +4,11 @@ spring: name: entity-management-service flyway: enabled: true + postgresql: + transactional-lock: false 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 6770b26bf7..ae92704625 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -3,12 +3,12 @@ spring: name: entity-management-service flyway: enabled: true + postgresql: + transactional-lock: false schemas: ${SERVICE_SCHEMA:public} 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: @@ -75,6 +75,8 @@ firemud: grpc: public-methods: - entity_management.v1.EntityManagementService/Ping + - entity_management.v1.CanonicalGameplayRosterService/ListPreseededRoster + - entity_management.v1.CanonicalGameplayRosterService/ReadSelectedPreseededAssignment grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/entity-management-service/src/main/resources/db/migration/V5__preseeded_actor_assignment.sql b/services/entity-management-service/src/main/resources/db/migration/V5__preseeded_actor_assignment.sql new file mode 100644 index 0000000000..99008404ac --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V5__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/V6__preseeded_assignment_owner_snapshot.sql b/services/entity-management-service/src/main/resources/db/migration/V6__preseeded_assignment_owner_snapshot.sql new file mode 100644 index 0000000000..807b3f9698 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V6__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/V7__canonical_gameplay_roster_snapshots.sql b/services/entity-management-service/src/main/resources/db/migration/V7__canonical_gameplay_roster_snapshots.sql new file mode 100644 index 0000000000..13dcdddbb9 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V7__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/V8__canonical_publication_uuid_actor_evidence.sql b/services/entity-management-service/src/main/resources/db/migration/V8__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/V8__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/V9__canonical_roster_owner_counters.sql b/services/entity-management-service/src/main/resources/db/migration/V9__canonical_roster_owner_counters.sql new file mode 100644 index 0000000000..1fa8a05f38 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V9__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..e69828c081 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java @@ -0,0 +1,417 @@ +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 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.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<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").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; + @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 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(); + } + } + + 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/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java new file mode 100644 index 0000000000..99fff8bbb2 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -0,0 +1,1102 @@ +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.List; +import java.util.Map; +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.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidence; +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 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.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 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<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").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; + + @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 postgresMigrationInstallsAndEnforcesDeferredAssignmentForeignKeys() { + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "a"); + + 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 = "entity_publication_history_" + 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("7")).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("8")).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 = "entity_preseeded_assignment_" + UUID.randomUUID().toString().replace("-", ""); + UUID retainedAccountUuid = UUID.randomUUID(); + UUID retainedTenantUuid = UUID.randomUUID(); + UUID retainedNamespaceUuid = UUID.randomUUID(); + + migrationFlyway(schema).target(MigrationVersion.fromVersion("4")).load().migrate(); + 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(); + + 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", + "a"); + PreseededActorAssignmentResult retry = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "a"); + PreseededActorAssignmentResult changedIntent = + assign( + assignmentUuid, + accountUuid, + 5L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "b"); + + 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", + "a"); + 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 selectedAssignmentReadRequiresExactOwnerTargetAndCurrentActorProvenance() { + PreseededActorAssignmentResult assigned = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Selected Actor", + "a"); + 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", + "a"); + PreseededActorAssignmentResult changedAccount = + assign( + assignmentUuid, + secondAccountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "b"); + PreseededActorAssignmentResult changedScope = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, + "Assigned Actor", + "c"); + PreseededActorAssignmentResult changedPayload = + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Renamed Actor", + "d"); + + 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", + "a"); + PreseededActorAssignmentResult second = + assign( + secondAssignmentUuid, + secondAccountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor", + "b"); + + 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", + "a"); + }); + 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", + "b"); + }); + + 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", + "retry")) + .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", + "a")) + .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", + "a"); + + 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", + "a")) + .isEqualTo(assigned); + } + + private PreseededActorAssignmentResult assign( + UUID operationUuid, + UUID actorAccountUuid, + long catalogRevision, + PlayableStateScope scope, + String displayName, + String digestFirstHexDigit) { + 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) { + FluentConfiguration configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", schema)); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + return configuration; + } + + 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/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java new file mode 100644 index 0000000000..e219ef3acd --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java @@ -0,0 +1,557 @@ +package unit.net.firedevops.firemud.entitymanagement.client; + +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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.Timestamp; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountActorStagingEligibilityServiceGrpc; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityCurrentness; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityDecision; +import net.firedevops.firemud.account.v1.ActorStagingEligibilityPurpose; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityRequest; +import net.firedevops.firemud.account.v1.ResolvePreseededActorStagingEligibilityResponse; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Decision; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.entitymanagement.client.AccountPreseededActorStagingEligibilityClient; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; + +class AccountPreseededActorStagingEligibilityClientTest { + private static final String NAMESPACE = "test"; + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID TENANT_SOURCE_OPERATION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID MEMBERSHIP_EVENT_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final Instant OBSERVED_AT = Instant.parse("2026-09-01T12:34:56.123456789Z"); + private static final String SOURCE_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void forwardsExactClosedRequestAndReturnsTypedCurrentAccountEvidence() throws Exception { + AccountActorStagingEligibilityServiceGrpc.AccountActorStagingEligibilityServiceBlockingStub + stub = mockStub(); + when(stub.resolvePreseededActorStagingEligibility(any())).thenReturn(validResponse()); + AccountPreseededActorStagingEligibilityClient client = newClient(stub); + + AccountActorStagingEligibilityEvidence evidence = + client.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString()); + + assertThat(evidence.schemaVersion()).isEqualTo(1); + assertThat(evidence.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(evidence.requestId()).isEqualTo(REQUEST_ID); + assertThat(evidence.canonicalAccountId()).isEqualTo(ACCOUNT_ID); + assertThat(evidence.canonicalTenantId()).isEqualTo(TENANT_ID); + assertThat(evidence.currentness()) + .isEqualTo(AccountActorStagingEligibilityEvidence.Currentness.CURRENT_AT_REVALIDATION); + assertThat(evidence.decision()).isEqualTo(Decision.STAGING_ELIGIBLE); + assertThat(evidence.observedAt()).isEqualTo(OBSERVED_AT); + assertThat(evidence.membershipVersion()).isEqualTo(17L); + assertThat(evidence.membershipAuthorityGeneration()).isEqualTo(19L); + assertThat(evidence.membershipEventSequence()).isEqualTo(23L); + assertThat(evidence.gameplayAdmissionAllowed()).isTrue(); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(ResolvePreseededActorStagingEligibilityRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).resolvePreseededActorStagingEligibility(requestCaptor.capture()); + ResolvePreseededActorStagingEligibilityRequest request = requestCaptor.getValue(); + assertThat(request.getSchemaVersion()).isEqualTo(1); + assertThat(request.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.getRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(request.getCanonicalAccountId()).isEqualTo(ACCOUNT_ID.toString()); + assertThat(request.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(request.getPurpose()) + .isEqualTo(ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY); + assertThat(request.getUnknownFields().asMap()).isEmpty(); + } + + @Test + void returnsStagingIneligibleAsTypedObservation() throws Exception { + AccountActorStagingEligibilityServiceGrpc.AccountActorStagingEligibilityServiceBlockingStub + stub = mockStub(); + when(stub.resolvePreseededActorStagingEligibility(any())) + .thenReturn(validResponse(false, "DEACTIVATED_PENDING_DELETE", "INACTIVE")); + AccountPreseededActorStagingEligibilityClient client = newClient(stub); + + AccountActorStagingEligibilityEvidence evidence = + client.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString()); + + assertThat(evidence.decision()).isEqualTo(Decision.STAGING_INELIGIBLE); + assertThat(evidence.gameplayAdmissionAllowed()).isFalse(); + } + + @Test + void rejectsMalformedInputsBeforeStubOrChannelUse() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountPreseededActorStagingEligibilityClient client = newClientWithoutStub(channelFactory); + List invalidRequests = + List.of( + new String[] {null, TENANT_ID.toString(), REQUEST_ID.toString()}, + new String[] {"", TENANT_ID.toString(), REQUEST_ID.toString()}, + new String[] { + "AB426BB3-A733-43F0-9C8E-2E379CBDF7EC", TENANT_ID.toString(), REQUEST_ID.toString() + }, + new String[] { + ACCOUNT_ID.toString(), "22222222-2222-4222-8222-22222222222", REQUEST_ID.toString() + }, + new String[] { + ACCOUNT_ID.toString(), "00000000-0000-0000-0000-000000000000", REQUEST_ID.toString() + }, + new String[] {ACCOUNT_ID.toString(), TENANT_ID.toString(), null}, + new String[] {ACCOUNT_ID.toString(), TENANT_ID.toString(), ""}, + new String[] { + ACCOUNT_ID.toString(), TENANT_ID.toString(), "33333333-3333-4333-8333-33333333333" + }, + new String[] { + ACCOUNT_ID.toString(), TENANT_ID.toString(), "00000000-0000-0000-0000-000000000000" + }); + + for (String[] invalid : invalidRequests) { + assertThatThrownBy( + () -> + client.resolvePreseededActorStagingEligibility( + invalid[0], invalid[1], invalid[2])) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsUninitializedClientAndAbsentResponseWithoutActivation() throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AccountPreseededActorStagingEligibilityClient uninitialized = + newClientWithoutStub(channelFactory); + assertThatThrownBy( + () -> + uninitialized.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + + AccountActorStagingEligibilityServiceGrpc.AccountActorStagingEligibilityServiceBlockingStub + stub = mockStub(); + when(stub.resolvePreseededActorStagingEligibility(any())).thenReturn(null); + AccountPreseededActorStagingEligibilityClient client = newClient(stub); + assertThatThrownBy( + () -> + client.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("absent"); + } + + @Test + void rejectsResponseRequestMismatchUnknownFieldsAndUnknownEnums() throws Exception { + ResolvePreseededActorStagingEligibilityResponse valid = validResponse(); + assertRejected(valid.toBuilder().setSchemaVersion(2).build()); + assertRejected(valid.toBuilder().setTargetNamespace("other").build()); + assertRejected( + valid.toBuilder().setCanonicalAccountId("66666666-6666-4666-8666-666666666666").build()); + assertRejected( + valid.toBuilder().setCanonicalTenantId("66666666-6666-4666-8666-666666666666").build()); + assertRejected(valid.toBuilder().setRequestId("66666666-6666-4666-8666-666666666666").build()); + assertRejected(valid.toBuilder().setRequestId("33333333-3333-4333-8333-33333333333").build()); + assertRejected( + valid.toBuilder().setCanonicalAccountId("00000000-0000-0000-0000-000000000000").build()); + assertRejected(valid.toBuilder().setCanonicalTenantId("not-a-uuid").build()); + assertRejected(valid.toBuilder().setPurposeValue(99).build()); + assertRejected(valid.toBuilder().setCurrentnessValue(99).build()); + assertRejected(valid.toBuilder().setDecisionValue(99).build()); + assertRejected( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()); + } + + @Test + void rejectsChangedAuthorityFieldsAndChangedDigests() throws Exception { + ResolvePreseededActorStagingEligibilityResponse valid = validResponse(); + assertRejected(valid.toBuilder().setMembershipVersion(18L).build()); + assertRejected(valid.toBuilder().setGameplayAdmissionAllowed(false).build()); + assertRejected(valid.toBuilder().setEligibilityDecisionDigest("0".repeat(64)).build()); + assertRejected(valid.toBuilder().setAuthoritySnapshotDigest("0".repeat(64)).build()); + } + + @Test + void rejectsMissingMalformedAndOutOfRangeTimestamps() throws Exception { + ResolvePreseededActorStagingEligibilityResponse valid = validResponse(); + assertRejected(valid.toBuilder().clearObservedAt().build()); + assertRejected( + valid.toBuilder() + .setObservedAt(Timestamp.newBuilder().setSeconds(0L).setNanos(1_000_000_000).build()) + .build()); + assertRejected( + valid.toBuilder() + .setObservedAt(Timestamp.newBuilder().setSeconds(253_402_300_800L).setNanos(0).build()) + .build()); + assertRejected( + valid.toBuilder() + .setObservedAt(Timestamp.newBuilder().setSeconds(-62_135_596_801L).setNanos(0).build()) + .build()); + assertRejected( + valid.toBuilder() + .setObservedAt(Timestamp.newBuilder().setSeconds(0L).setNanos(-1).build()) + .build()); + assertRejected( + valid.toBuilder() + .setObservedAt( + valid.getObservedAt().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build()); + + Instant minimum = Instant.ofEpochSecond(-62_135_596_800L); + Instant maximum = Instant.ofEpochSecond(253_402_300_799L, 999_999_999); + assertThat(resolve(validResponseAt(minimum)).observedAt()).isEqualTo(minimum); + assertThat(resolve(validResponseAt(maximum)).observedAt()).isEqualTo(maximum); + } + + @Test + void rejectsNonpositiveCountersAndAcceptsLargePositiveCounters() throws Exception { + ResolvePreseededActorStagingEligibilityResponse valid = validResponse(); + assertRejected(valid.toBuilder().setMembershipVersion(0L).build()); + assertRejected(valid.toBuilder().setMembershipVersion(-1L).build()); + assertRejected(valid.toBuilder().setMembershipAuthorityGeneration(0L).build()); + assertRejected(valid.toBuilder().setMembershipAuthorityGeneration(-1L).build()); + assertRejected(valid.toBuilder().setMembershipEventSequence(0L).build()); + assertRejected(valid.toBuilder().setMembershipEventSequence(-1L).build()); + + AccountActorStagingEligibilityEvidence largeCounterEvidence = + resolve(validResponse(true, "ACTIVE", "ACTIVE", Long.MAX_VALUE)); + assertThat(largeCounterEvidence.membershipVersion()).isEqualTo(Long.MAX_VALUE); + assertThat(largeCounterEvidence.membershipAuthorityGeneration()).isEqualTo(Long.MAX_VALUE); + assertThat(largeCounterEvidence.membershipEventSequence()).isEqualTo(Long.MAX_VALUE); + } + + @Test + void propagatesProviderFailuresWithFiniteDeadline() throws Exception { + AccountActorStagingEligibilityServiceGrpc.AccountActorStagingEligibilityServiceBlockingStub + stub = mockStub(); + StatusRuntimeException timeout = + new StatusRuntimeException(Status.DEADLINE_EXCEEDED.withDescription("Account timed out")); + StatusRuntimeException unavailable = + new StatusRuntimeException(Status.UNAVAILABLE.withDescription("Account unavailable")); + when(stub.resolvePreseededActorStagingEligibility(any())) + .thenThrow(timeout) + .thenThrow(unavailable); + AccountPreseededActorStagingEligibilityClient client = newClient(stub); + + assertThatThrownBy( + () -> + client.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) + .isSameAs(timeout); + assertThatThrownBy( + () -> + client.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) + .isSameAs(unavailable); + + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsPlaintextMissingClasspathTlsAndInvalidNamespaceBeforeChannelCreation() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + + assertThatThrownBy( + () -> + new AccountPreseededActorStagingEligibilityClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy( + () -> + new AccountPreseededActorStagingEligibilityClient( + new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("TLS configuration is required"); + + for (CommonGrpcClientProperties incomplete : + List.of( + incompleteMtlsProperties(null, "entity.key", "account-ca.crt"), + incompleteMtlsProperties("entity.crt", null, "account-ca.crt"), + incompleteMtlsProperties("entity.crt", "entity.key", null))) { + assertThatThrownBy( + () -> + new AccountPreseededActorStagingEligibilityClient( + new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("certificate, key, and CA"); + } + + for (CommonGrpcClientProperties classpath : + List.of( + incompleteMtlsProperties("classpath:entity.crt", "entity.key", "account-ca.crt"), + incompleteMtlsProperties("entity.crt", "classpath:entity.key", "account-ca.crt"), + incompleteMtlsProperties("entity.crt", "entity.key", "classpath:account-ca.crt"))) { + assertThatThrownBy( + () -> + new AccountPreseededActorStagingEligibilityClient( + new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + } + + assertThatThrownBy( + () -> + new AccountPreseededActorStagingEligibilityClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one DNS label"); + verifyNoInteractions(channelFactory); + } + + @Test + void initUsesConfiguredAccountTargetAndFileBackedTls(@TempDir Path directory) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + CommonGrpcClientProperties tls = mtlsProperties(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + AccountPreseededActorStagingEligibilityClient client = + new AccountPreseededActorStagingEligibilityClient( + endpoints, tls, channelFactory, NAMESPACE); + + verifyNoInteractions(channelFactory); + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("account.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static void assertRejected(ResolvePreseededActorStagingEligibilityResponse response) + throws Exception { + AccountActorStagingEligibilityServiceGrpc.AccountActorStagingEligibilityServiceBlockingStub + stub = mockStub(); + when(stub.resolvePreseededActorStagingEligibility(any())).thenReturn(response); + AccountPreseededActorStagingEligibilityClient client = newClient(stub); + + assertThatThrownBy( + () -> + client.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) + .isInstanceOf(IllegalStateException.class); + } + + private static AccountActorStagingEligibilityEvidence resolve( + ResolvePreseededActorStagingEligibilityResponse response) throws Exception { + AccountActorStagingEligibilityServiceGrpc.AccountActorStagingEligibilityServiceBlockingStub + stub = mockStub(); + when(stub.resolvePreseededActorStagingEligibility(any())).thenReturn(response); + return newClient(stub) + .resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString()); + } + + private static AccountPreseededActorStagingEligibilityClient newClient( + AccountActorStagingEligibilityServiceGrpc.AccountActorStagingEligibilityServiceBlockingStub + stub) + throws Exception { + AccountPreseededActorStagingEligibilityClient client = + newClientWithoutStub(mock(GrpcChannelFactory.class)); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static AccountPreseededActorStagingEligibilityClient newClientWithoutStub( + GrpcChannelFactory channelFactory) { + return new AccountPreseededActorStagingEligibilityClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, NAMESPACE); + } + + private static AccountActorStagingEligibilityServiceGrpc + .AccountActorStagingEligibilityServiceBlockingStub + mockStub() { + AccountActorStagingEligibilityServiceGrpc.AccountActorStagingEligibilityServiceBlockingStub + stub = + mock( + AccountActorStagingEligibilityServiceGrpc + .AccountActorStagingEligibilityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static ResolvePreseededActorStagingEligibilityResponse validResponse() { + return validResponse(true, "ACTIVE", "ACTIVE"); + } + + private static ResolvePreseededActorStagingEligibilityResponse validResponse( + boolean gameplayAdmissionAllowed, + String accountLifecycleState, + String membershipLifecycleState) { + return validResponse( + gameplayAdmissionAllowed, accountLifecycleState, membershipLifecycleState, 17L, 19L, 23L); + } + + private static ResolvePreseededActorStagingEligibilityResponse validResponse( + boolean gameplayAdmissionAllowed, + String accountLifecycleState, + String membershipLifecycleState, + long largeCounter) { + return validResponse( + gameplayAdmissionAllowed, + accountLifecycleState, + membershipLifecycleState, + largeCounter, + largeCounter, + largeCounter); + } + + private static ResolvePreseededActorStagingEligibilityResponse validResponse( + boolean gameplayAdmissionAllowed, + String accountLifecycleState, + String membershipLifecycleState, + long membershipVersion, + long membershipAuthorityGeneration, + long membershipEventSequence) { + return validResponse( + gameplayAdmissionAllowed, + accountLifecycleState, + membershipLifecycleState, + membershipVersion, + membershipAuthorityGeneration, + membershipEventSequence, + OBSERVED_AT); + } + + private static ResolvePreseededActorStagingEligibilityResponse validResponseAt( + Instant observedAt) { + return validResponse(true, "ACTIVE", "ACTIVE", 17L, 19L, 23L, observedAt); + } + + private static ResolvePreseededActorStagingEligibilityResponse validResponse( + boolean gameplayAdmissionAllowed, + String accountLifecycleState, + String membershipLifecycleState, + long membershipVersion, + long membershipAuthorityGeneration, + long membershipEventSequence, + Instant observedAt) { + AccountActorStagingEligibilityEvidence evidence = + AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + observedAt, + "ACCOUNT_REPOSITORY_INSERT", + accountLifecycleState, + membershipLifecycleState, + gameplayAdmissionAllowed, + "EXPLICIT_JOIN", + membershipVersion, + membershipAuthorityGeneration, + "FRESH_GAME_DESIGN", + TENANT_SOURCE_OPERATION_ID, + SOURCE_DIGEST, + membershipEventSequence, + MEMBERSHIP_EVENT_ID, + SOURCE_DIGEST, + false); + return ResolvePreseededActorStagingEligibilityResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setRequestId(evidence.requestId().toString()) + .setCanonicalAccountId(evidence.canonicalAccountId().toString()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setPurpose(ActorStagingEligibilityPurpose.PUBLIC_PRODUCTION_STAGING_ONLY) + .setCurrentness(ActorStagingEligibilityCurrentness.CURRENT_AT_REVALIDATION) + .setObservedAt( + Timestamp.newBuilder() + .setSeconds(observedAt.getEpochSecond()) + .setNanos(observedAt.getNano()) + .build()) + .setDecision( + evidence.decision() == Decision.STAGING_ELIGIBLE + ? ActorStagingEligibilityDecision.STAGING_ELIGIBLE + : ActorStagingEligibilityDecision.STAGING_INELIGIBLE) + .setAccountUuidProvenance(evidence.accountUuidProvenance()) + .setAccountLifecycleState(evidence.accountLifecycleState()) + .setMembershipLifecycleState(evidence.membershipLifecycleState()) + .setGameplayAdmissionAllowed(evidence.gameplayAdmissionAllowed()) + .setMembershipAuthorityProvenance(evidence.membershipAuthorityProvenance()) + .setMembershipVersion(evidence.membershipVersion()) + .setMembershipAuthorityGeneration(evidence.membershipAuthorityGeneration()) + .setTenantProvenanceKind(evidence.tenantProvenanceKind()) + .setTenantSourceOperationId(evidence.tenantSourceOperationId().toString()) + .setTenantProvenanceDigest(evidence.tenantProvenanceDigest()) + .setMembershipEventSequence(evidence.membershipEventSequence()) + .setMembershipEventId(evidence.membershipEventId().toString()) + .setMembershipEventDigest(evidence.membershipEventDigest()) + .setLastTransitionInvalidated(evidence.lastTransitionInvalidated()) + .setEligibilityDecisionDigest(evidence.eligibilityDecisionDigest()) + .setAuthoritySnapshotDigest(evidence.authoritySnapshotDigest()) + .build(); + } + + private static CommonGrpcClientProperties mtlsProperties() { + return incompleteMtlsProperties( + "entity-management-client.crt", "entity-management-client.key", "account-ca.crt"); + } + + private static CommonGrpcClientProperties mtlsProperties(Path directory) throws Exception { + return incompleteMtlsProperties( + Files.createFile(directory.resolve("entity-management-client.crt")).toString(), + Files.createFile(directory.resolve("entity-management-client.key")).toString(), + Files.createFile(directory.resolve("account-ca.crt")).toString()); + } + + private static CommonGrpcClientProperties incompleteMtlsProperties( + String certificate, String privateKey, String caCertificate) { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate); + tls.setPrivateKey(privateKey); + tls.setCaCert(caCertificate); + return tls; + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java new file mode 100644 index 0000000000..3bbbd20f61 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java @@ -0,0 +1,262 @@ +package unit.net.firedevops.firemud.entitymanagement.client; + +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +class GameSessionCanonicalGameplayRosterOwnerReadClientTest { + private static final String NAMESPACE = "test"; + private static final UUID REQUEST_UUID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_UUID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_UUID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REALM_UUID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID NAMESPACE_UUID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID INSTANCE_UUID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID VERSION_UUID = uuid("77777777-7777-4777-8777-777777777777"); + + @Test + void forwardsExactRequestAndReturnsOnlyCodecValidatedEvidence() throws Exception { + var request = request(NAMESPACE); + var response = + GetCanonicalGameplayRosterOwnerReadResponse.newBuilder() + .setRequest(CanonicalGameplayRosterOwnerReadGrpcCodec.toRequest(request)) + .setGameSessionOwnerProof(ByteString.copyFrom(new byte[] {1})) + .setPublishedPolicySetEvidence(ByteString.copyFrom(new byte[] {2})) + .setAdmissionPointerSnapshotDigest("a".repeat(64)) + .build(); + var evidence = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + var stub = mockStub(); + when(stub.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(response); + var client = newClient(stub); + + try (MockedStatic codec = + Mockito.mockStatic(CanonicalGameplayRosterOwnerReadGrpcCodec.class)) { + codec + .when(() -> CanonicalGameplayRosterOwnerReadGrpcCodec.toRequest(request)) + .thenCallRealMethod(); + codec + .when(() -> CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse(request, response)) + .thenReturn(evidence); + + assertThat(client.getCanonicalGameplayRosterOwnerRead(request)).isSameAs(evidence); + + ArgumentCaptor captor = + ArgumentCaptor.forClass(GetCanonicalGameplayRosterOwnerReadRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).getCanonicalGameplayRosterOwnerRead(captor.capture()); + var wire = captor.getValue(); + assertThat(wire.getSchemaVersion()).isEqualTo(1); + assertThat(wire.getRequestUuid()).isEqualTo(REQUEST_UUID.toString()); + assertThat(wire.getCanonicalAccountUuid()).isEqualTo(ACCOUNT_UUID.toString()); + assertThat(wire.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(wire.getCanonicalTenantUuid()).isEqualTo(TENANT_UUID.toString()); + assertThat(wire.getWorldSlug()).isEqualTo("earth"); + assertThat(wire.getRealmUuid()).isEqualTo(REALM_UUID.toString()); + assertThat(wire.getRealmSlug()).isEqualTo("main"); + assertThat(wire.getPlayableStateNamespaceUuid()).isEqualTo(NAMESPACE_UUID.toString()); + assertThat(wire.getPlayableStateScope()).isEqualTo("SHARED"); + assertThat(wire.getCanonicalGameInstanceUuid()).isEqualTo(INSTANCE_UUID.toString()); + assertThat(wire.getCanonicalVersionUuid()).isEqualTo(VERSION_UUID.toString()); + assertThat(wire.getExpectedCatalogRevision()).isEqualTo(71L); + assertThat(wire.getExpectedPointerVersion()).isEqualTo(73L); + assertThat(wire.getExpectedActiveWorldEpoch()).isEqualTo(82L); + assertThat(wire.getUnknownFields().asMap()).isEmpty(); + assertThat(response.getAdmissionPointerSnapshotDigest()).isEqualTo("a".repeat(64)); + codec.verify(() -> CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse(request, response)); + } + } + + @Test + void rejectsWrongNamespaceAndUninitializedClientWithoutFallbackOrChannelUse() throws Exception { + var channelFactory = mock(GrpcChannelFactory.class); + var uninitialized = newClientWithoutStub(channelFactory); + assertThatThrownBy(() -> uninitialized.getCanonicalGameplayRosterOwnerRead(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("target namespace"); + assertThatThrownBy(() -> uninitialized.getCanonicalGameplayRosterOwnerRead(request(NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsAbsentResponseAndCodecRejectedTupleOrOwnerEvidence() throws Exception { + var request = request(NAMESPACE); + var absentStub = mockStub(); + when(absentStub.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(null); + assertThatThrownBy(() -> newClient(absentStub).getCanonicalGameplayRosterOwnerRead(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("response is absent"); + + var response = + GetCanonicalGameplayRosterOwnerReadResponse.newBuilder() + .setRequest(CanonicalGameplayRosterOwnerReadGrpcCodec.toRequest(request)) + .setGameSessionOwnerProof(ByteString.copyFrom(new byte[] {1})) + .setPublishedPolicySetEvidence(ByteString.copyFrom(new byte[] {2})) + .setAdmissionPointerSnapshotDigest("a".repeat(64)) + .build(); + var stub = mockStub(); + when(stub.getCanonicalGameplayRosterOwnerRead(any())).thenReturn(response); + try (MockedStatic codec = + Mockito.mockStatic(CanonicalGameplayRosterOwnerReadGrpcCodec.class)) { + codec + .when(() -> CanonicalGameplayRosterOwnerReadGrpcCodec.toRequest(request)) + .thenCallRealMethod(); + codec + .when(() -> CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse(request, response)) + .thenThrow(new IllegalArgumentException("changed tuple, counters, policy, or release")); + + assertThatThrownBy(() -> newClient(stub).getCanonicalGameplayRosterOwnerRead(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("response is invalid") + .hasCauseInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void requiresFileBackedMtlsAndPinsExactSameNamespaceGameSessionPeer(@TempDir Path directory) + throws Exception { + var channelFactory = mock(GrpcChannelFactory.class); + var invalidTls = mtlsProperties(); + invalidTls.setPlaintext(true); + assertThatThrownBy( + () -> + new GameSessionCanonicalGameplayRosterOwnerReadClient( + new ServiceEndpointsProperties(), invalidTls, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var tls = mtlsProperties(directory); + var channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-session-service:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + var client = + new GameSessionCanonicalGameplayRosterOwnerReadClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + assertThat(installedServerPeerUri(client)) + .isEqualTo("spiffe://firemud/ns/test/sa/game-session-service"); + verifyNoInteractions(channelFactory); + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-session-service:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static GameSessionCanonicalGameplayRosterOwnerReadClient newClient( + CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceBlockingStub + stub) + throws Exception { + var client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + return client; + } + + private static GameSessionCanonicalGameplayRosterOwnerReadClient newClientWithoutStub( + GrpcChannelFactory channelFactory) { + return new GameSessionCanonicalGameplayRosterOwnerReadClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, NAMESPACE); + } + + private static CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceBlockingStub + mockStub() { + var stub = + mock( + CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static CanonicalGameplayRosterOwnerReadEvidence.Request request(String targetNamespace) { + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + REQUEST_UUID, + ACCOUNT_UUID, + targetNamespace, + TENANT_UUID, + "earth", + REALM_UUID, + "main", + NAMESPACE_UUID, + "SHARED", + INSTANCE_UUID, + VERSION_UUID, + 71L, + 73L, + 82L); + } + + private static String installedServerPeerUri( + GameSessionCanonicalGameplayRosterOwnerReadClient client) throws Exception { + Field field = client.getClass().getDeclaredField("serverPeerIdentityInterceptor"); + field.setAccessible(true); + var interceptor = (GrpcServerPeerIdentityClientInterceptor) field.get(client); + Field peerField = + GrpcServerPeerIdentityClientInterceptor.class.getDeclaredField("expectedPeerUri"); + peerField.setAccessible(true); + return (String) peerField.get(interceptor); + } + + private static CommonGrpcClientProperties mtlsProperties() { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain("entity-management-client.crt"); + tls.setPrivateKey("entity-management-client.key"); + tls.setCaCert("game-session-ca.crt"); + return tls; + } + + private static CommonGrpcClientProperties mtlsProperties(Path directory) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.createFile(directory.resolve("entity.crt")).toString()); + tls.setPrivateKey(Files.createFile(directory.resolve("entity.key")).toString()); + tls.setCaCert(Files.createFile(directory.resolve("game-session-ca.crt")).toString()); + return tls; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java new file mode 100644 index 0000000000..be7af91ec1 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java @@ -0,0 +1,130 @@ +package unit.net.firedevops.firemud.entitymanagement.client; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; +import net.firedevops.firemud.entitymanagement.client.GameSessionPreseededActorAssignmentOwnerReadClient; +import org.junit.jupiter.api.Test; + +class GameSessionPreseededActorAssignmentOwnerReadClientTest { + private static final String NAMESPACE = "gameplay"; + private static final UUID ASSIGNMENT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID ACCOUNT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REALM = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID PLAYABLE_NAMESPACE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID INSTANCE = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID VERSION = uuid("66666666-6666-4666-8666-666666666666"); + + @Test + void requiresStrictFileBackedMtlsAndValidWorkloadNamespace() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + + assertThatThrownBy( + () -> + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy( + () -> + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("TLS configuration is required"); + + for (CommonGrpcClientProperties incomplete : + List.of( + incompleteMtlsProperties(null, "entity.key", "gs-ca.crt"), + incompleteMtlsProperties("entity.crt", null, "gs-ca.crt"), + incompleteMtlsProperties("entity.crt", "entity.key", null))) { + assertThatThrownBy( + () -> + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("certificate, key, and CA"); + } + + for (CommonGrpcClientProperties classpath : + List.of( + incompleteMtlsProperties("classpath:entity.crt", "entity.key", "gs-ca.crt"), + incompleteMtlsProperties("entity.crt", "classpath:entity.key", "gs-ca.crt"), + incompleteMtlsProperties("entity.crt", "entity.key", "classpath:gs-ca.crt"))) { + assertThatThrownBy( + () -> + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + } + + assertThatThrownBy( + () -> + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one DNS label"); + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsCrossNamespaceSelectorsBeforeStubInitialization() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + var client = + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, NAMESPACE); + + assertThatThrownBy(() -> client.getPreseededActorAssignmentOwnerRead(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match Entity Management"); + assertThatThrownBy(() -> client.getPreseededActorAssignmentOwnerRead(request(NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + } + + private static PreseededActorAssignmentOwnerReadEvidence.Request request(String namespace) { + return new PreseededActorAssignmentOwnerReadEvidence.Request( + ASSIGNMENT, + ACCOUNT, + namespace, + TENANT, + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 71L, + "a".repeat(64), + "release:exact"); + } + + private static CommonGrpcClientProperties mtlsProperties() { + return incompleteMtlsProperties("entity-client.crt", "entity-client.key", "gs-ca.crt"); + } + + private static CommonGrpcClientProperties incompleteMtlsProperties( + String certificate, String privateKey, String caCertificate) { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate); + tls.setPrivateKey(privateKey); + tls.setCaCert(caCertificate); + return tls; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java new file mode 100644 index 0000000000..55d59e8b95 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java @@ -0,0 +1,62 @@ +package unit.net.firedevops.firemud.entitymanagement.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.config.CanonicalGameplayRosterConfiguration; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSelectedAssignmentService; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class CanonicalGameplayRosterConfigurationTest { + @Test + void defaultConfigurationKeepsGameSessionOwnerReadDisabledAndDenied() { + runner() + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + assertThat(context).hasSingleBean(CanonicalGameplayRosterOwnerEvidencePort.class); + assertThat(context) + .hasSingleBean(CanonicalGameplayRosterSelectedAssignmentService.class); + assertThat(context.getBean(CanonicalGameplayRosterOwnerEvidencePort.class)) + .isNotInstanceOf(GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.class); + assertThatThrownBy( + () -> + context + .getBean(CanonicalGameplayRosterOwnerEvidencePort.class) + .resolveCurrentTarget(null)) + .isInstanceOf( + CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException + .class); + }); + } + + @Test + void explicitEnablementComposesTheEntityAdapterAroundThePinnedGameSessionClient() { + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + runner() + .withPropertyValues("firemud.canonical-gameplay-roster-owner-read.enabled=true") + .withBean(GameSessionCanonicalGameplayRosterOwnerReadClient.class, () -> client) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .getBean(CanonicalGameplayRosterOwnerEvidencePort.class) + .isInstanceOf(GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.class); + }); + } + + private static ApplicationContextRunner runner() { + return new ApplicationContextRunner() + .withUserConfiguration(CanonicalGameplayRosterConfiguration.class) + .withPropertyValues("firemud.grpc.workload-namespace=test") + .withBean(CharacterRepository.class, () -> mock(CharacterRepository.class)); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java new file mode 100644 index 0000000000..5092100f54 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java @@ -0,0 +1,80 @@ +package unit.net.firedevops.firemud.entitymanagement.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.entitymanagement.client.GameSessionPreseededActorAssignmentOwnerReadClient; +import net.firedevops.firemud.entitymanagement.config.PreseededActorAssignmentConfiguration; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAccountIdentityPort; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.PreseededActorStagingEligibilityPort; +import net.firedevops.firemud.entitymanagement.service.RunOwnedPreseededAssignmentAuthority; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionPreseededActorAssignmentOwnerEvidenceAdapter; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class PreseededActorAssignmentConfigurationTest { + @Test + void defaultConfigurationLeavesOwnerEvidenceUnavailableAndDoesNotCreateGsClient() { + runner() + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(GameSessionPreseededActorAssignmentOwnerReadClient.class); + assertThat(context).hasSingleBean(PreseededActorAssignmentOwnerEvidencePort.class); + assertThat(context.getBean(PreseededActorAssignmentOwnerEvidencePort.class)) + .isNotInstanceOf(GameSessionPreseededActorAssignmentOwnerEvidenceAdapter.class); + assertThatThrownBy( + () -> + context + .getBean(PreseededActorAssignmentOwnerEvidencePort.class) + .resolveCurrentEligibleTarget(null, null, null)) + .isInstanceOf( + PreseededActorAssignmentOwnerEvidencePort.OwnerEvidenceUnavailableException + .class); + }); + } + + @Test + void explicitRunOwnedEnablementComposesTheGsAssignmentOwnerAdapter() { + var gsClient = client(); + runner() + .withPropertyValues("firemud.run-owned-preseeded-actor-assignment.enabled=true") + .withBean(PreseededActorAccountIdentityPort.class, () -> (account, assignment) -> null) + .withBean( + PreseededActorStagingEligibilityPort.class, () -> (account, tenant, assignment) -> null) + .withBean( + RunOwnedPreseededAssignmentAuthority.class, + () -> mock(RunOwnedPreseededAssignmentAuthority.class)) + .withBean(GameSessionPreseededActorAssignmentOwnerReadClient.class, () -> gsClient) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .getBean(PreseededActorAssignmentOwnerEvidencePort.class) + .isInstanceOf(GameSessionPreseededActorAssignmentOwnerEvidenceAdapter.class); + }); + } + + private static ApplicationContextRunner runner() { + return new ApplicationContextRunner() + .withUserConfiguration(PreseededActorAssignmentConfiguration.class) + .withPropertyValues("firemud.grpc.workload-namespace=gameplay") + .withBean(CharacterRepository.class, () -> mock(CharacterRepository.class)); + } + + private static GameSessionPreseededActorAssignmentOwnerReadClient client() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("entity-client.crt"); + tls.setPrivateKey("entity-client.key"); + tls.setCaCert("game-session-ca.crt"); + return new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "gameplay"); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java new file mode 100644 index 0000000000..d01f2c511e --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java @@ -0,0 +1,227 @@ +package net.firedevops.firemud.entitymanagement.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Properties; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.core.io.FileSystemResource; + +class CanonicalGameplayRosterPeerInterceptorTest { + private static final String WORKLOAD_NAMESPACE = "gameplay"; + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void acceptsOnlyExactSameNamespaceGameSessionCertificate() { + CanonicalGameplayRosterPeerInterceptor interceptor = + new CanonicalGameplayRosterPeerInterceptor(WORKLOAD_NAMESPACE); + ServerCall call = + callFor( + CanonicalGameplayRosterPeerInterceptor.METHOD_NAME, + peerSession("spiffe://firemud/ns/gameplay/sa/game-session-service")); + ServerCallHandler next = mock(ServerCallHandler.class); + ServerCall.Listener listener = new ServerCall.Listener<>() {}; + when(next.startCall(any(), any())) + .thenAnswer( + invocation -> { + assertThat(CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer()) + .isNotNull() + .satisfies( + peer -> { + assertThat(peer.isService("game-session-service")).isTrue(); + assertThat(peer.isInNamespace(WORKLOAD_NAMESPACE)).isTrue(); + }); + return listener; + }); + + interceptor.interceptCall(call, new Metadata(), next); + + verify(next).startCall(any(), any()); + } + + @Test + void selectedAssignmentMethodUsesTheSameNamespaceAndEndUserContextGuard() { + CanonicalGameplayRosterPeerInterceptor interceptor = + new CanonicalGameplayRosterPeerInterceptor(WORKLOAD_NAMESPACE); + ServerCall trustedCall = + callFor( + CanonicalGameplayRosterPeerInterceptor.SELECTED_ASSIGNMENT_METHOD_NAME, + peerSession("spiffe://firemud/ns/gameplay/sa/game-session-service")); + ServerCallHandler trustedNext = mock(ServerCallHandler.class); + when(trustedNext.startCall(any(), any())) + .thenAnswer( + invocation -> { + assertThat(CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer()).isNotNull(); + return new ServerCall.Listener<>() {}; + }); + + interceptor.interceptCall(trustedCall, new Metadata(), trustedNext); + + verify(trustedNext).startCall(any(), any()); + + ServerCall wrongNamespaceCall = + callFor( + CanonicalGameplayRosterPeerInterceptor.SELECTED_ASSIGNMENT_METHOD_NAME, + peerSession("spiffe://firemud/ns/other/sa/game-session-service")); + ServerCallHandler wrongNamespaceNext = mock(ServerCallHandler.class); + interceptor.interceptCall(wrongNamespaceCall, new Metadata(), wrongNamespaceNext); + verify(wrongNamespaceCall) + .close( + org.mockito.ArgumentMatchers.argThat( + status -> status.getCode() == Status.Code.PERMISSION_DENIED), + any(Metadata.class)); + verify(wrongNamespaceNext, never()).startCall(any(), any()); + + ServerCall endUserCall = + callFor( + CanonicalGameplayRosterPeerInterceptor.SELECTED_ASSIGNMENT_METHOD_NAME, + peerSession("spiffe://firemud/ns/gameplay/sa/game-session-service")); + ServerCallHandler endUserNext = mock(ServerCallHandler.class); + SessionContext.setContext("player-claim", List.of(), java.util.Map.of()); + interceptor.interceptCall(endUserCall, new Metadata(), endUserNext); + verify(endUserCall) + .close( + org.mockito.ArgumentMatchers.argThat( + status -> status.getCode() == Status.Code.PERMISSION_DENIED), + any(Metadata.class)); + verify(endUserNext, never()).startCall(any(), any()); + } + + @Test + void applicationYamlBypassesJwtForOnlyTheTwoExactRosterMethods() { + var yaml = new YamlPropertiesFactoryBean(); + yaml.setResources(new FileSystemResource("src/main/resources/application.yml")); + Properties properties = yaml.getObject(); + assertThat(properties).isNotNull(); + List publicMethods = + properties.stringPropertyNames().stream() + .filter(name -> name.startsWith("firemud.auth.grpc.public-methods[")) + .map(name -> name.substring(name.indexOf('[') + 1, name.indexOf(']'))) + .map(Integer::parseInt) + .sorted(Comparator.naturalOrder()) + .map(index -> properties.getProperty("firemud.auth.grpc.public-methods[" + index + "]")) + .toList(); + + assertThat( + publicMethods.stream() + .filter( + method -> + method.startsWith("entity_management.v1.CanonicalGameplayRosterService/"))) + .containsExactly( + CanonicalGameplayRosterPeerInterceptor.METHOD_NAME, + CanonicalGameplayRosterPeerInterceptor.SELECTED_ASSIGNMENT_METHOD_NAME); + assertThat(publicMethods).noneMatch(method -> method.contains("*")); + } + + @Test + void rejectsAbsentWrongNamespaceAndNonGameSessionCertificates() { + CanonicalGameplayRosterPeerInterceptor interceptor = + new CanonicalGameplayRosterPeerInterceptor(WORKLOAD_NAMESPACE); + for (SSLSession session : + Arrays.asList( + null, + peerSession("spiffe://firemud/ns/other/sa/game-session-service"), + peerSession("spiffe://firemud/ns/gameplay/sa/account-service"))) { + ServerCall call = + callFor(CanonicalGameplayRosterPeerInterceptor.METHOD_NAME, session); + ServerCallHandler next = mock(ServerCallHandler.class); + + interceptor.interceptCall(call, new Metadata(), next); + + verify(call) + .close( + org.mockito.ArgumentMatchers.argThat( + status -> + status.getCode() == Status.Code.PERMISSION_DENIED + && "Trusted Game Session peer required".equals(status.getDescription())), + any(Metadata.class)); + verify(next, never()).startCall(any(), any()); + } + } + + @Test + void rejectsBearerPlayerContextEvenWhenCertificateIsTrusted() { + CanonicalGameplayRosterPeerInterceptor interceptor = + new CanonicalGameplayRosterPeerInterceptor(WORKLOAD_NAMESPACE); + ServerCall call = + callFor( + CanonicalGameplayRosterPeerInterceptor.METHOD_NAME, + peerSession("spiffe://firemud/ns/gameplay/sa/game-session-service")); + ServerCallHandler next = mock(ServerCallHandler.class); + SessionContext.setContext("player-claim", List.of(), java.util.Map.of()); + + interceptor.interceptCall(call, new Metadata(), next); + + verify(call) + .close( + org.mockito.ArgumentMatchers.argThat( + status -> + status.getCode() == Status.Code.PERMISSION_DENIED + && "Trusted Game Session peer required".equals(status.getDescription())), + any(Metadata.class)); + verify(next, never()).startCall(any(), any()); + } + + @Test + void unrelatedRpcPassesThroughWithoutRosterCertificateGuard() { + CanonicalGameplayRosterPeerInterceptor interceptor = + new CanonicalGameplayRosterPeerInterceptor(WORKLOAD_NAMESPACE); + ServerCall call = + callFor("entity_management.v1.EntityManagementService/Ping", null); + ServerCallHandler next = mock(ServerCallHandler.class); + + interceptor.interceptCall(call, new Metadata(), next); + + verify(next).startCall(any(), any()); + } + + private static ServerCall callFor(String methodName, SSLSession session) { + ServerCall call = mock(ServerCall.class); + MethodDescriptor descriptor = mock(MethodDescriptor.class); + when(descriptor.getFullMethodName()).thenReturn(methodName); + when(call.getMethodDescriptor()).thenReturn(descriptor); + Attributes attributes = + session == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build(); + when(call.getAttributes()).thenReturn(attributes); + return call; + } + + private static SSLSession peerSession(String uri) { + X509Certificate leaf = mock(X509Certificate.class); + try { + when(leaf.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, uri))); + SSLSession session = mock(SSLSession.class); + when(session.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + return session; + } catch (java.security.cert.CertificateParsingException + | javax.net.ssl.SSLPeerUnverifiedException impossible) { + throw new IllegalStateException(impossible); + } + } +} 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..8390971388 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java @@ -0,0 +1,481 @@ +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() { + 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)), + UnsupportedOperationException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_TARGET_UNSUPPORTED"); + assertOwnerMismatchBeforeRepository( + request, + evidence(ownerRequest, withCatalogRevision(request.expectedTarget(), 4L)), + IllegalStateException.class, + "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH"); + } + + @Test + void unsupportedCallerPolicyAndScopeFailBeforeOwnerResolution() { + 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); + assertThatThrownBy( + () -> + service.read( + request(withScope(target(), PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)))) + .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 changedSnapshotOrActorAbsentFromItFailsBeforeReceiptRead() { + 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..f20ed8774e --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentServiceTest.java @@ -0,0 +1,682 @@ +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(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..7e5b8f569c --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java @@ -0,0 +1,353 @@ +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 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); + + doThrow(new CertificateExpiredException()).when(trustedRoot).checkValidity(); + assertThatThrownBy( + () -> + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot))) + .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); + assertThatThrownBy( + () -> + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot, 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 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 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() { + PreseededActorAssignmentRequest request = 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/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java new file mode 100644 index 0000000000..9a10a9b31b --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java @@ -0,0 +1,517 @@ +package net.firedevops.firemud.entitymanagement.service.impl; + +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.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.UUID; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.security.CanonicalGameplayRosterPeerInterceptor; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidence; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSelectedAssignmentReference; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSelectedAssignmentService; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterService; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayRosterGrpcAdapterTest { + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void parsesCanonicalUuidTargetAndPolicyWithoutUsingCallerIdentityFallback() { + var parsed = CanonicalGameplayRosterGrpcAdapter.parseRequest(request(target())); + + assertThat(parsed.requestUuid()).isNotNull(); + assertThat(parsed.canonicalAccountUuid()).isNotNull(); + assertThat(parsed.expectedTarget().entryPolicy()) + .isEqualTo(CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + assertThat(parsed.expectedTarget().playableStateScope()) + .isEqualTo(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(parsed.expectedTarget().pointerVersion()).isEqualTo(17L); + assertThat(parsed.expectedTarget().activeWorldEpoch()).isEqualTo(29L); + } + + @Test + void responseTargetEchoesExactOwnerCounters() { + var expected = + CanonicalGameplayRosterGrpcAdapter.parseRequest(request(target())).expectedTarget(); + + var responseTarget = CanonicalGameplayRosterGrpcAdapter.toProto(expected); + + assertThat(responseTarget.getPointerVersion()).isEqualTo(17L); + assertThat(responseTarget.getActiveWorldEpoch()).isEqualTo(29L); + } + + @Test + void rejectsMalformedIdentityAndUnknownTopLevelFieldsBeforeAnyLookup() { + CanonicalGameplayRosterRequest malformed = + request(target()).toBuilder().setCanonicalAccountUuid("not-a-uuid").build(); + assertThatThrownBy(() -> CanonicalGameplayRosterGrpcAdapter.parseRequest(malformed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical_account_uuid"); + + CanonicalGameplayRosterRequest unknown = + request(target()).toBuilder().setUnknownFields(unknownField()).build(); + assertThatThrownBy(() -> CanonicalGameplayRosterGrpcAdapter.parseRequest(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown fields"); + } + + @Test + void requiresFullyMatchingUnsignedContextAndUnselectedRosterContext() { + CanonicalGameplayRosterRequest exact = request(target()); + CanonicalGameplayRosterRequest wrongTenant = + exact.toBuilder() + .setPlayerExecutionContext( + exact.getPlayerExecutionContext().toBuilder() + .setTenantId(UUID.randomUUID().toString()) + .build()) + .build(); + assertThatThrownBy(() -> CanonicalGameplayRosterGrpcAdapter.parseRequest(wrongTenant)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match exact target"); + + CanonicalGameplayRosterRequest selectedCharacter = + exact.toBuilder() + .setPlayerExecutionContext( + exact.getPlayerExecutionContext().toBuilder() + .setCharacterId(UUID.randomUUID().toString()) + .build()) + .build(); + assertThatThrownBy(() -> CanonicalGameplayRosterGrpcAdapter.parseRequest(selectedCharacter)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("character_id must be unset for roster discovery"); + + CanonicalGameplayRosterRequest numericScope = + exact.toBuilder() + .setPlayerExecutionContext( + exact.getPlayerExecutionContext().toBuilder().setPlayableStateScope("0").build()) + .build(); + assertThatThrownBy(() -> CanonicalGameplayRosterGrpcAdapter.parseRequest(numericScope)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be SHARED or ISOLATED"); + } + + @Test + void rejectsUnknownNestedTargetFieldsAndUnsupportedScopeShape() { + CanonicalGameplayRosterTarget unknownTarget = + target().toBuilder().setUnknownFields(unknownField()).build(); + assertThatThrownBy( + () -> CanonicalGameplayRosterGrpcAdapter.parseRequest(request(unknownTarget))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Complete expected target is required"); + + CanonicalGameplayRosterTarget noScope = + target().toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) + .build(); + assertThatThrownBy(() -> CanonicalGameplayRosterGrpcAdapter.parseRequest(request(noScope))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("playable_state_scope is required"); + + CanonicalGameplayRosterTarget noCanonicalVersion = + target().toBuilder().clearCanonicalVersionUuid().build(); + assertThatThrownBy( + () -> CanonicalGameplayRosterGrpcAdapter.parseRequest(request(noCanonicalVersion))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("canonical_version_uuid is required"); + + CanonicalGameplayRosterTarget noPointerVersion = + target().toBuilder().setPointerVersion(0L).build(); + assertThatThrownBy( + () -> CanonicalGameplayRosterGrpcAdapter.parseRequest(request(noPointerVersion))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("pointerVersion must be positive"); + + CanonicalGameplayRosterTarget negativeWorldEpoch = + target().toBuilder().setActiveWorldEpoch(-1L).build(); + assertThatThrownBy( + () -> CanonicalGameplayRosterGrpcAdapter.parseRequest(request(negativeWorldEpoch))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("activeWorldEpoch must be positive"); + + CanonicalGameplayRosterTarget missingWorldEpoch = + target().toBuilder().setActiveWorldEpoch(0L).build(); + assertThatThrownBy( + () -> CanonicalGameplayRosterGrpcAdapter.parseRequest(request(missingWorldEpoch))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("activeWorldEpoch must be positive"); + } + + @Test + void selectedAssignmentRequestParsesExactAccountActorAndCompleteTarget() { + CanonicalGameplayRosterSelectedAssignmentRequest request = selectedAssignmentRequest(target()); + + var parsed = CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest(request); + + assertThat(parsed.requestUuid()).isEqualTo(UUID.fromString(request.getRequestUuid())); + assertThat(parsed.canonicalAccountUuid()) + .isEqualTo(UUID.fromString(request.getCanonicalAccountUuid())); + assertThat(parsed.selectedCharacterUuid()) + .isEqualTo(UUID.fromString(request.getSelectedCharacterUuid())); + assertThat(parsed.playerExecutionContext().characterUuid()) + .isEqualTo(parsed.selectedCharacterUuid()); + assertThat(parsed.expectedSnapshot().snapshotUuid()) + .isEqualTo(UUID.fromString(request.getExpectedSnapshot().getSnapshotUuid())); + assertThat(parsed.expectedTarget().entryPolicy()) + .isEqualTo(CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + assertThat(parsed.expectedTarget().playableStateScope()) + .isEqualTo(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + UUID assignmentUuid = UUID.randomUUID(); + String intentDigest = "a".repeat(64); + CanonicalGameplayRosterSnapshotReference expectedSnapshot = + new CanonicalGameplayRosterSnapshotReference(UUID.randomUUID(), "b".repeat(64)); + var response = + CanonicalGameplayRosterGrpcAdapter.toSelectedAssignmentResponse( + new CanonicalGameplayRosterSelectedAssignmentReference( + parsed.requestUuid(), + parsed.canonicalAccountUuid(), + parsed.selectedCharacterUuid(), + parsed.expectedTarget(), + expectedSnapshot, + assignmentUuid, + intentDigest)); + + assertThat(response.getRequestUuid()).isEqualTo(request.getRequestUuid()); + assertThat(response.getCanonicalAccountUuid()).isEqualTo(request.getCanonicalAccountUuid()); + assertThat(response.getSelectedCharacterUuid()).isEqualTo(request.getSelectedCharacterUuid()); + assertThat(response.getTarget()).isEqualTo(request.getExpectedTarget()); + assertThat(response.getAssignmentUuid()).isEqualTo(assignmentUuid.toString()); + assertThat(response.getIntentDigest()).isEqualTo(intentDigest); + assertThat(response.getSnapshot().getSnapshotUuid()) + .isEqualTo(expectedSnapshot.snapshotUuid().toString()); + assertThat(response.getSnapshot().getSnapshotDigest()) + .isEqualTo(expectedSnapshot.snapshotDigest()); + } + + @Test + void selectedAssignmentRejectsUnknownFieldsAndMalformedActorIdentityBeforeLookup() { + CanonicalGameplayRosterSelectedAssignmentRequest unknownRequest = + selectedAssignmentRequest(target()).toBuilder().setUnknownFields(unknownField()).build(); + assertThatThrownBy( + () -> CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest(unknownRequest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown fields"); + + CanonicalGameplayRosterTarget unknownTarget = + target().toBuilder().setUnknownFields(unknownField()).build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest( + selectedAssignmentRequest(unknownTarget))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Complete expected target is required"); + + CanonicalGameplayRosterSelectedAssignmentRequest malformedCharacter = + selectedAssignmentRequest(target()).toBuilder() + .setSelectedCharacterUuid("not-a-uuid") + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest( + malformedCharacter)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("selected_character_uuid"); + + CanonicalGameplayRosterSelectedAssignmentRequest noSnapshot = + selectedAssignmentRequest(target()).toBuilder().clearExpectedSnapshot().build(); + assertThatThrownBy( + () -> CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest(noSnapshot)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact expected_snapshot is required"); + + CanonicalGameplayRosterSelectedAssignmentRequest selected = selectedAssignmentRequest(target()); + CanonicalGameplayRosterSelectedAssignmentRequest mismatchedContextActor = + selected.toBuilder() + .setPlayerExecutionContext( + selected.getPlayerExecutionContext().toBuilder() + .setCharacterId(UUID.randomUUID().toString()) + .build()) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest( + mismatchedContextActor)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("playerExecutionContext.character_id must equal selectedCharacterUuid"); + } + + @Test + void rpcErrorsUseCanonicalStatusesWithoutPartialResponses() { + CanonicalGameplayRosterGrpcAdapter unavailableOwnerAdapter = + new CanonicalGameplayRosterGrpcAdapter( + new CanonicalGameplayRosterService( + request -> { + throw new CanonicalGameplayRosterOwnerEvidencePort + .OwnerEvidenceUnavailableException(); + }, + mock(CharacterRepository.class)), + new CanonicalGameplayRosterSelectedAssignmentService( + request -> { + throw new CanonicalGameplayRosterOwnerEvidencePort + .OwnerEvidenceUnavailableException(); + }, + mock(CharacterRepository.class)), + new SimpleMeterRegistry()); + RecordingObserver + unavailableObserver = new RecordingObserver<>(); + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.METHOD_NAME, + () -> unavailableOwnerAdapter.listPreseededRoster(request(target()), unavailableObserver)); + assertOnlyStatus(unavailableObserver, Status.Code.UNAVAILABLE); + + CanonicalGameplayRosterGrpcAdapter malformedAdapter = + new CanonicalGameplayRosterGrpcAdapter( + new CanonicalGameplayRosterService( + request -> { + throw new AssertionError("malformed request must not reach owner read"); + }, + mock(CharacterRepository.class)), + new CanonicalGameplayRosterSelectedAssignmentService( + request -> { + throw new AssertionError("malformed request must not reach owner read"); + }, + mock(CharacterRepository.class)), + new SimpleMeterRegistry()); + RecordingObserver + malformedObserver = new RecordingObserver<>(); + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.METHOD_NAME, + () -> + malformedAdapter.listPreseededRoster( + request(target()).toBuilder().setCanonicalAccountUuid("malformed").build(), + malformedObserver)); + assertOnlyStatus(malformedObserver, Status.Code.INVALID_ARGUMENT); + + CanonicalGameplayRosterSelectedAssignmentRequest selectedRequest = + selectedAssignmentRequest(target()); + CharacterRepository staleRepository = mock(CharacterRepository.class); + when(staleRepository.readCurrentCanonicalGameplayRosterSnapshot(any(), any(), any())) + .thenThrow(new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_STALE")); + CanonicalGameplayRosterGrpcAdapter staleSnapshotAdapter = + new CanonicalGameplayRosterGrpcAdapter( + new CanonicalGameplayRosterService( + request -> { + throw new AssertionError("selected request must use selected service"); + }, + staleRepository), + new CanonicalGameplayRosterSelectedAssignmentService( + request -> + new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + Instant.parse("2026-10-01T00:00:00Z")), + staleRepository), + new SimpleMeterRegistry()); + RecordingObserver< + net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterSelectedAssignmentResponse> + staleSnapshotObserver = new RecordingObserver<>(); + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.SELECTED_ASSIGNMENT_METHOD_NAME, + () -> + staleSnapshotAdapter.readSelectedPreseededAssignment( + selectedRequest, staleSnapshotObserver)); + assertOnlyStatus(staleSnapshotObserver, Status.Code.FAILED_PRECONDITION); + + CanonicalGameplayRosterGrpcAdapter unauthenticatedAdapter = + new CanonicalGameplayRosterGrpcAdapter( + new CanonicalGameplayRosterService( + request -> { + throw new AssertionError("unauthenticated request must not reach owner read"); + }, + mock(CharacterRepository.class)), + new CanonicalGameplayRosterSelectedAssignmentService( + request -> { + throw new AssertionError("unauthenticated request must not reach owner read"); + }, + mock(CharacterRepository.class)), + new SimpleMeterRegistry()); + RecordingObserver + unauthenticatedObserver = new RecordingObserver<>(); + unauthenticatedAdapter.listPreseededRoster(request(target()), unauthenticatedObserver); + assertOnlyStatus(unauthenticatedObserver, Status.Code.UNAUTHENTICATED); + } + + private static void assertOnlyStatus(RecordingObserver observer, Status.Code expectedCode) { + assertThat(observer.values).isEmpty(); + assertThat(observer.errorCount).isEqualTo(1); + assertThat(observer.completed).isFalse(); + assertThat(observer.statusRuntimeFailure).isTrue(); + assertThat(observer.failureCode).isEqualTo(expectedCode); + } + + private static void withTrustedPeer(String methodName, Runnable action) { + ServerCall call = mock(ServerCall.class); + MethodDescriptor descriptor = mock(MethodDescriptor.class); + when(descriptor.getFullMethodName()).thenReturn(methodName); + when(call.getMethodDescriptor()).thenReturn(descriptor); + SSLSession trustedSession = peerSession("spiffe://firemud/ns/gameplay/sa/game-session-service"); + when(call.getAttributes()) + .thenReturn( + Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, trustedSession).build()); + ServerCallHandler next = mock(ServerCallHandler.class); + when(next.startCall(any(), any())) + .thenAnswer( + invocation -> { + action.run(); + return new ServerCall.Listener<>() {}; + }); + + new CanonicalGameplayRosterPeerInterceptor("gameplay") + .interceptCall(call, new Metadata(), next); + verify(next).startCall(any(), any()); + } + + private static SSLSession peerSession(String uri) { + X509Certificate leaf = mock(X509Certificate.class); + try { + when(leaf.getSubjectAlternativeNames()) + .thenReturn(java.util.List.of(java.util.List.of(6, uri))); + SSLSession session = mock(SSLSession.class); + when(session.getPeerCertificates()).thenReturn(new Certificate[] {leaf}); + return session; + } catch (java.security.cert.CertificateParsingException + | javax.net.ssl.SSLPeerUnverifiedException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static final class RecordingObserver implements StreamObserver { + private final java.util.List values = new java.util.ArrayList<>(); + private Status.Code failureCode; + private boolean statusRuntimeFailure; + private int errorCount; + private boolean completed; + + @Override + public void onNext(T value) { + values.add(value); + } + + @Override + public void onError(Throwable throwable) { + errorCount++; + statusRuntimeFailure = throwable instanceof StatusRuntimeException; + failureCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static CanonicalGameplayRosterRequest request(CanonicalGameplayRosterTarget target) { + UUID requestUuid = UUID.randomUUID(); + UUID accountUuid = UUID.randomUUID(); + return CanonicalGameplayRosterRequest.newBuilder() + .setRequestUuid(requestUuid.toString()) + .setCanonicalAccountUuid(accountUuid.toString()) + .setExpectedTarget(target) + .setPlayerExecutionContext(executionContext(target, requestUuid, accountUuid, null)) + .build(); + } + + private static CanonicalGameplayRosterSelectedAssignmentRequest selectedAssignmentRequest( + CanonicalGameplayRosterTarget target) { + UUID requestUuid = UUID.randomUUID(); + UUID accountUuid = UUID.randomUUID(); + UUID selectedUuid = UUID.randomUUID(); + return CanonicalGameplayRosterSelectedAssignmentRequest.newBuilder() + .setRequestUuid(requestUuid.toString()) + .setCanonicalAccountUuid(accountUuid.toString()) + .setSelectedCharacterUuid(selectedUuid.toString()) + .setExpectedTarget(target) + .setExpectedSnapshot( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference + .newBuilder() + .setSnapshotUuid(UUID.randomUUID().toString()) + .setSnapshotDigest("b".repeat(64)) + .build()) + .setPlayerExecutionContext(executionContext(target, requestUuid, accountUuid, selectedUuid)) + .build(); + } + + private static PlayerExecutionContext executionContext( + CanonicalGameplayRosterTarget target, + UUID requestUuid, + UUID accountUuid, + UUID characterUuid) { + return PlayerExecutionContext.newBuilder() + .setAccountId(accountUuid.toString()) + .setTenantId(target.getTenantUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setGameInstanceId(target.getGameInstanceUuid()) + .setCharacterId(characterUuid == null ? "" : characterUuid.toString()) + .setSessionId(UUID.randomUUID().toString()) + .setRealmId(target.getRealmUuid()) + .setRequestId(requestUuid.toString()) + .setPlayableStateScope( + target.getPlayableStateScope() == PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + ? "SHARED" + : "ISOLATED") + .build(); + } + + private static CanonicalGameplayRosterTarget target() { + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(UUID.randomUUID().toString()) + .setRealmUuid(UUID.randomUUID().toString()) + .setWorldSlug("world") + .setRealmSlug("realm") + .setGameInstanceUuid(UUID.randomUUID().toString()) + .setCatalogRevision(3L) + .setCanonicalVersionUuid("17000000-0000-4000-8000-000000000017") + .setPointerVersion(17L) + .setActiveWorldEpoch(29L) + .setPublishedPolicyDigest("1".repeat(64)) + .setPublishedReleaseBundleRef("release/test") + .setAdmissionPointerSnapshotDigest("2".repeat(64)) + .setPublishedOwnerProofDigest("3".repeat(64)) + .setPlayableStateNamespaceUuid(UUID.randomUUID().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .build(); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(999, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java new file mode 100644 index 0000000000..74f81eda4c --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java @@ -0,0 +1,344 @@ +package unit.net.firedevops.firemud.entitymanagement.service.impl; + +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.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +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.CanonicalGameplayRosterOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest { + private static final String NAMESPACE = "gameplay"; + private static final UUID REQUEST_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REALM_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID NAMESPACE_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID INSTANCE_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID VERSION_ID = uuid("77777777-7777-4777-8777-777777777777"); + + @Test + void mapsOnlyCompleteSourceEvidenceAndDoesNotUseCallerDigestFieldsAsAuthority() { + var fixture = fixture(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + when(client.getCanonicalGameplayRosterOwnerRead(fixture.ownerReadRequest())) + .thenReturn(fixture.evidence()); + var adapter = new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter(client, NAMESPACE); + + CanonicalGameplayRosterOwnerEvidence resolved = + adapter.resolveCurrentTarget(fixture.entityRequest()); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(CanonicalGameplayRosterOwnerReadEvidence.Request.class); + verify(client).getCanonicalGameplayRosterOwnerRead(requestCaptor.capture()); + assertThat(requestCaptor.getValue()).isEqualTo(fixture.ownerReadRequest()); + assertThat(resolved.requestUuid()).isEqualTo(REQUEST_ID); + assertThat(resolved.canonicalAccountUuid()).isEqualTo(ACCOUNT_ID); + assertThat(resolved.target()) + .isEqualTo( + new CanonicalGameplayRosterTarget( + TENANT_ID, + REALM_ID, + "earth", + "main", + INSTANCE_ID, + 71L, + 73L, + 82L, + VERSION_ID, + "f".repeat(64), + "release/canonical", + "a".repeat(64), + "b".repeat(64), + NAMESPACE_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY)); + assertThat(resolved.resolvedAt()).isNotNull(); + assertThat(resolved.target().publishedPolicyDigest()) + .isNotEqualTo(fixture.entityRequest().expectedTarget().publishedPolicyDigest()); + assertThat(resolved.target().publishedReleaseBundleRef()) + .isNotEqualTo(fixture.entityRequest().expectedTarget().publishedReleaseBundleRef()); + assertThat(resolved.target().admissionPointerSnapshotDigest()) + .isNotEqualTo(fixture.entityRequest().expectedTarget().admissionPointerSnapshotDigest()); + assertThat(resolved.target().publishedOwnerProofDigest()) + .isNotEqualTo(fixture.entityRequest().expectedTarget().publishedOwnerProofDigest()); + } + + @Test + void rejectsMissingEvidenceAndChangedRequestEchoWithoutProducingTarget() { + var fixture = fixture(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + when(client.getCanonicalGameplayRosterOwnerRead(fixture.ownerReadRequest())).thenReturn(null); + var adapter = new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter(client, NAMESPACE); + + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + + var changedEcho = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(changedEcho.request()).thenReturn(ownerRequest(74L, 82L, "main")); + when(client.getCanonicalGameplayRosterOwnerRead(fixture.ownerReadRequest())) + .thenReturn(changedEcho); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + } + + @Test + void rejectsNonterminalProofAndChangedTupleOrPointerAndEpochCounters() { + var fixture = fixture(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + when(client.getCanonicalGameplayRosterOwnerRead(fixture.ownerReadRequest())) + .thenReturn(fixture.evidence()); + var adapter = new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter(client, NAMESPACE); + + when(fixture.proof().outcome()) + .thenReturn(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + + when(fixture.proof().outcome()) + .thenReturn(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + when(fixture.proof().committedPointerVersion()).thenReturn(74L); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + + when(fixture.proof().committedPointerVersion()).thenReturn(73L); + when(fixture.holdRequest().activeLifecycleEpoch()).thenReturn(83L); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + + when(fixture.holdRequest().activeLifecycleEpoch()).thenReturn(82L); + when(fixture.holdRequest().worldSlug()).thenReturn("other-world"); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + } + + @Test + void rejectsChangedPolicyScopeEntryVisibilityAndReleaseAttestation() { + var fixture = fixture(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + when(client.getCanonicalGameplayRosterOwnerRead(fixture.ownerReadRequest())) + .thenReturn(fixture.evidence()); + var adapter = new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter(client, NAMESPACE); + + when(fixture.realmPolicy().publicProduction()).thenReturn(false); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + + when(fixture.realmPolicy().publicProduction()).thenReturn(true); + when(fixture.realmPolicy().stateScope()).thenReturn(RealmEntryPolicy.StateScope.ISOLATED); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + + when(fixture.realmPolicy().stateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(fixture.realmPolicy().entryPolicy()).thenReturn(null); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + + when(fixture.realmPolicy().entryPolicy()) + .thenReturn(RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); + when(fixture.policySet().publishedReleaseBundleDigest()).thenReturn("not-a-release-digest"); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + + when(fixture.policySet().publishedReleaseBundleDigest()).thenReturn("sha256:" + "e".repeat(64)); + when(fixture.selectedPolicy().hasValidDigest(fixture.policySet())).thenReturn(false); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + + when(fixture.selectedPolicy().hasValidDigest(fixture.policySet())).thenReturn(true); + when(fixture.selectedPolicy().policyDigest()).thenReturn("not-a-policy-digest"); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + } + + @Test + void requiresTheSourcePointerSnapshotDigestInItsCanonicalRawHexForm() { + var fixture = fixture(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + when(client.getCanonicalGameplayRosterOwnerRead(fixture.ownerReadRequest())) + .thenReturn(fixture.evidence()); + var adapter = new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter(client, NAMESPACE); + + when(fixture.evidence().admissionPointerSnapshotDigest()) + .thenReturn("sha256:" + "a".repeat(64)); + assertUnavailable(() -> adapter.resolveCurrentTarget(fixture.entityRequest())); + } + + @Test + void unavailableTransportIsMappedToDefaultDeniedOwnerEvidence() { + var fixture = fixture(); + var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var failure = new IllegalStateException("transport detail"); + when(client.getCanonicalGameplayRosterOwnerRead(any())).thenThrow(failure); + var adapter = new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter(client, NAMESPACE); + + assertThatThrownBy(() -> adapter.resolveCurrentTarget(fixture.entityRequest())) + .isInstanceOf( + CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException.class) + .hasCause(failure); + } + + private static void assertUnavailable(ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf( + CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException.class); + } + + private static Fixture fixture() { + var ownerReadRequest = ownerRequest(73L, 82L, "main"); + var sourceEvidence = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(sourceEvidence.request()).thenReturn(ownerReadRequest); + when(sourceEvidence.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + + var proof = mock(GameSessionCanonicalInitialAdmissionOwnerProof.class); + when(proof.outcome()) + .thenReturn(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + when(proof.committedPointerVersion()).thenReturn(73L); + when(proof.auditEventId()).thenReturn(91L); + when(proof.proofDigest()).thenReturn("sha256:" + "b".repeat(64)); + when(proof.positiveDurableAbort()).thenReturn(false); + when(proof.terminalAt()).thenReturn(Instant.parse("2026-10-08T03:04:05Z")); + var holdIdentity = mock(WorldCanonicalInitialAdmissionHold.HoldIdentity.class); + var holdRequest = mock(WorldCanonicalInitialAdmissionHold.Request.class); + when(proof.holdIdentity()).thenReturn(holdIdentity); + when(holdIdentity.request()).thenReturn(holdRequest); + when(holdRequest.targetNamespace()).thenReturn(NAMESPACE); + when(holdRequest.canonicalTenantId()).thenReturn(TENANT_ID); + when(holdRequest.worldSlug()).thenReturn("earth"); + when(holdRequest.realmId()).thenReturn(REALM_ID); + when(holdRequest.playableStateNamespaceId()).thenReturn(NAMESPACE_ID); + when(holdRequest.playableStateScope()).thenReturn("SHARED"); + when(holdRequest.canonicalGameInstanceId()).thenReturn(INSTANCE_ID); + when(holdRequest.canonicalVersionId()).thenReturn(VERSION_ID); + when(holdRequest.expectedCatalogRevision()).thenReturn(71L); + when(holdRequest.activeLifecycleEpoch()).thenReturn(82L); + when(sourceEvidence.gameSessionOwnerProof()).thenReturn(proof); + + var policySet = mock(PublishedRealmEntryPolicySetEvidence.class); + var routePolicy = realmPolicy(); + var selectedPolicy = selectedPolicy(routePolicy); + var setTarget = mock(TargetProof.class); + when(policySet.target()).thenReturn(setTarget); + when(setTarget.canonicalTenantId()).thenReturn(TENANT_ID); + when(setTarget.canonicalVersionId()).thenReturn(VERSION_ID); + when(policySet.policyCount()).thenReturn(1); + when(policySet.policies()).thenReturn(List.of(selectedPolicy)); + when(policySet.versionNumber()).thenReturn(5); + when(policySet.publicationVersionStateEpoch()).thenReturn(12L); + when(policySet.publishedReleaseBundleRef()).thenReturn("release/canonical"); + when(policySet.publishedReleaseBundleDigest()).thenReturn("sha256:" + "c".repeat(64)); + when(policySet.policySetDigest()).thenReturn("sha256:" + "d".repeat(64)); + when(policySet.requireValidDigest()).thenReturn(policySet); + when(sourceEvidence.publishedPolicySetEvidence()).thenReturn(policySet); + when(sourceEvidence.selectedPolicyEvidence()).thenReturn(selectedPolicy); + return new Fixture( + ownerReadRequest, + sourceEvidence, + proof, + holdRequest, + policySet, + selectedPolicy, + routePolicy); + } + + private static PublishedRealmEntryPolicyEvidence selectedPolicy(RealmEntryPolicy policy) { + var evidence = mock(PublishedRealmEntryPolicyEvidence.class); + when(evidence.policy()).thenReturn(policy); + when(evidence.policyDigest()).thenReturn("sha256:" + "f".repeat(64)); + when(evidence.hasValidDigest(any())).thenReturn(true); + return evidence; + } + + private static RealmEntryPolicy realmPolicy() { + var policy = mock(RealmEntryPolicy.class); + when(policy.visible()).thenReturn(true); + when(policy.publicProduction()).thenReturn(true); + when(policy.stateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(policy.entryPolicy()).thenReturn(RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); + when(policy.worldSlug()).thenReturn("earth"); + when(policy.realmSlug()).thenReturn("main"); + return policy; + } + + private static CanonicalGameplayRosterOwnerReadEvidence.Request ownerRequest( + long pointerVersion, long activeWorldEpoch, String realmSlug) { + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + REQUEST_ID, + ACCOUNT_ID, + NAMESPACE, + TENANT_ID, + "earth", + REALM_ID, + realmSlug, + NAMESPACE_ID, + "SHARED", + INSTANCE_ID, + VERSION_ID, + 71L, + pointerVersion, + activeWorldEpoch); + } + + private static CanonicalGameplayRosterReadRequest entityRequest() { + CanonicalGameplayRosterTarget target = + new CanonicalGameplayRosterTarget( + TENANT_ID, + REALM_ID, + "earth", + "main", + INSTANCE_ID, + 71L, + 73L, + 82L, + VERSION_ID, + "9".repeat(64), + "release/caller-echo-only", + "8".repeat(64), + "7".repeat(64), + NAMESPACE_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + return new CanonicalGameplayRosterReadRequest( + REQUEST_ID, + ACCOUNT_ID, + target, + new CanonicalGameplayRosterExecutionContext( + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + INSTANCE_ID, + null, + UUID.randomUUID(), + REALM_ID, + REQUEST_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + CanonicalGameplayRosterOwnerReadEvidence.Request ownerReadRequest, + CanonicalGameplayRosterOwnerReadEvidence evidence, + GameSessionCanonicalInitialAdmissionOwnerProof proof, + WorldCanonicalInitialAdmissionHold.Request holdRequest, + PublishedRealmEntryPolicySetEvidence policySet, + PublishedRealmEntryPolicyEvidence selectedPolicy, + RealmEntryPolicy realmPolicy) { + CanonicalGameplayRosterReadRequest entityRequest() { + return GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.entityRequest(); + } + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java new file mode 100644 index 0000000000..2d63d4d9bb --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java @@ -0,0 +1,131 @@ +package unit.net.firedevops.firemud.entitymanagement.service.impl; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence; +import net.firedevops.firemud.common.account.AccountActorStagingEligibilityEvidence.Purpose; +import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.entitymanagement.client.GameSessionPreseededActorAssignmentOwnerReadClient; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload.ActorKind; +import net.firedevops.firemud.entitymanagement.service.impl.GameSessionPreseededActorAssignmentOwnerEvidenceAdapter; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; + +class GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest { + private static final String NAMESPACE = "gameplay"; + private static final UUID ASSIGNMENT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID ACCOUNT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID OTHER_TENANT = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID REALM = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID PLAYABLE_NAMESPACE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID INSTANCE = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID VERSION = uuid("66666666-6666-4666-8666-666666666666"); + + @Test + void accountSnapshotMustBindExactAssignmentAccountTenantAndCurrentStagingPurpose() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + var adapter = adapter(channelFactory); + + assertThatThrownBy( + () -> + adapter.resolveCurrentEligibleTarget( + request(INSTANCE.toString()), identity(), staging(OTHER_TENANT))) + .isInstanceOf( + PreseededActorAssignmentOwnerEvidencePort.OwnerEvidenceUnavailableException.class); + + verifyNoInteractions(channelFactory); + } + + @Test + void numericLegacyGameInstanceIdsAreNotConvertedIntoCanonicalUuidSelectors() { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + var adapter = adapter(channelFactory); + + assertThatThrownBy( + () -> adapter.resolveCurrentEligibleTarget(request("73"), identity(), staging(TENANT))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("gameInstanceId must be a canonical non-nil UUID"); + + verifyNoInteractions(channelFactory); + } + + private static GameSessionPreseededActorAssignmentOwnerEvidenceAdapter adapter( + GrpcChannelFactory channelFactory) { + var client = + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), tlsProperties(), channelFactory, NAMESPACE); + return new GameSessionPreseededActorAssignmentOwnerEvidenceAdapter(client, NAMESPACE); + } + + private static PreseededActorAssignmentRequest request(String gameInstanceId) { + return new PreseededActorAssignmentRequest( + ASSIGNMENT, + ACCOUNT, + new PreseededActorCorePayload(ActorKind.PLAYER, "Ari"), + new PreseededActorAssignmentExpectedTarget( + TENANT, + REALM, + "earth", + "main", + gameInstanceId, + 71L, + VERSION, + "a".repeat(64), + PLAYABLE_NAMESPACE, + "release:exact", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + } + + private static RuntimeAccountIdentityEvidence identity() { + return new RuntimeAccountIdentityEvidence( + 1, NAMESPACE, ASSIGNMENT, ACCOUNT, 73L, "ACCOUNT_REPOSITORY_INSERT"); + } + + private static AccountActorStagingEligibilityEvidence staging(UUID tenant) { + return AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + ASSIGNMENT, + ACCOUNT, + tenant, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + Instant.parse("2026-10-08T03:04:05Z"), + "ACCOUNT_REPOSITORY_INSERT", + "ACTIVE", + "ACTIVE", + true, + "EXPLICIT_JOIN", + 17L, + 19L, + "FRESH_GAME_DESIGN", + uuid("77777777-7777-4777-8777-777777777777"), + "sha256:" + "b".repeat(64), + 23L, + uuid("88888888-8888-4888-8888-888888888888"), + "sha256:" + "c".repeat(64), + false); + } + + private static CommonGrpcClientProperties tlsProperties() { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain("entity-client.crt"); + properties.setPrivateKey("entity-client.key"); + properties.setCaCert("game-session-ca.crt"); + return properties; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} From 9526190049a86feef40cd616ec7b5eb931247e8b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:31:12 +1300 Subject: [PATCH 02/61] Preserve accepted Unicode display names through Entity roster and Game Session reads --- .../api-contracts.md | 2 +- .../service/CanonicalGameplayRosterActor.java | 2 +- ...anonicalGameplayRosterIntegrationTest.java | 12 ++++++ .../client/CanonicalGameplayRosterClient.java | 2 +- .../CanonicalGameplayRosterClientTest.java | 40 +++++++++++++++++++ 5 files changed, 55 insertions(+), 3 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index dfd527604b..c07207c35e 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -8,7 +8,7 @@ The authoritative REST schema source lives in [../../../../services/entity-manag The canonical `CanonicalGameplayRosterService` proto defines two pre-admission reads restricted to `PRESEEDED_ONLY`; these reads do not admit or activate gameplay. Entity Java handlers implement both methods behind default-off owner-read configuration and the exact same-namespace Game Session mTLS peer allowlist. Their request models and adapter carry and validate typed `PlayerExecutionContext`; selected reads require and revalidate the supplied snapshot UUID/digest against the existing sealed snapshot and current owner-resolved roster, return the original persisted assignment receipt reference, and use canonical non-OK statuses without partial responses. This source does not establish fresh Account eligibility, gameplay admission, PLAY, or production owner provenance. Current PostgreSQL test results and remaining authenticated Game Session-to-Entity mTLS/network, restart, and owner-provenance gaps are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status). -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. `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 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. 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. 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 index e93400cf4f..f08f38fe00 100644 --- 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 @@ -13,7 +13,7 @@ public record CanonicalGameplayRosterActor(UUID characterUuid, String displayNam if (displayName == null || displayName.isBlank() || !displayName.equals(displayName.trim()) - || displayName.length() > 100 + || 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/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java index e69828c081..d907475961 100644 --- 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 @@ -118,6 +118,18 @@ void returnsOnlyFreshOwnerResolvedActorsForExactAccountTenantAndNamespace() { 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()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java index c6da9e621d..bf981b739f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java @@ -463,7 +463,7 @@ private static boolean isCanonicalDisplayName(String value) { return value != null && !value.isBlank() && value.equals(value.trim()) - && value.length() <= 100 + && value.codePointCount(0, value.length()) <= 100 && value.codePoints().noneMatch(Character::isISOControl); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java index a64ba478a8..4d0826a9b2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java @@ -122,6 +122,31 @@ void sendsExactPublishedTargetWithAccountAndValidatesSourceSnapshot() throws Exc .isEqualTo(route.selectedPolicyEvidence().policyDigest().substring("sha256:".length())); } + @Test + void acceptsOneHundredCodePointDisplayNameAndRejectsOneHundredOne() throws Exception { + String acceptedDisplayName = "\uD83D\uDE00".repeat(100); + var acceptedStub = mockStub(); + when(acceptedStub.listPreseededRoster(any())) + .thenAnswer(invocation -> rosterResponse(invocation.getArgument(0), acceptedDisplayName)); + + var acceptedRoster = + newClient(acceptedStub).listPreseededRoster(publishedRoute(), listContext()); + + assertThat(acceptedRoster.actors()) + .containsExactly( + new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, acceptedDisplayName)); + + String rejectedDisplayName = "\uD83D\uDE00".repeat(101); + var rejectedStub = mockStub(); + when(rejectedStub.listPreseededRoster(any())) + .thenAnswer(invocation -> rosterResponse(invocation.getArgument(0), rejectedDisplayName)); + + assertThatThrownBy( + () -> newClient(rejectedStub).listPreseededRoster(publishedRoute(), listContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("display name is malformed"); + } + @Test void rejectsMissingMalformedAndSubstitutedInitialExecutionContextBeforeRpc() throws Exception { var stub = mockStub(); @@ -873,6 +898,21 @@ private static net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRoste .build(); } + private static CanonicalGameplayRosterResponse rosterResponse( + CanonicalGameplayRosterRequest request, String displayName) throws Exception { + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest( + snapshotDigest( + ACCOUNT_UUID, + request.getExpectedTarget(), + List.of(ACTOR_UUID.toString(), displayName))) + .addActors(actor(ACTOR_UUID, displayName)) + .build(); + } + private static CanonicalGameplayRosterClient.PreseededRosterSnapshot validatedRoster( CanonicalGameplayRosterClient client, CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub stub) { From 94568c1109245598e92ec7481713c937fcc46438 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 02:10:03 +1300 Subject: [PATCH 03/61] Use canonical pinned images for PRESEEDED physical fixtures --- .../CanonicalGameplayRosterIntegrationTest.java | 6 ++++-- .../PreseededActorAssignmentIntegrationTest.java | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) 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 index d907475961..2c848fb966 100644 --- 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 @@ -27,6 +27,7 @@ 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; @@ -50,11 +51,12 @@ properties = "spring.grpc.server.port=0") class CanonicalGameplayRosterIntegrationTest { @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static GenericContainer redis = - new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { 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 index 99fff8bbb2..63fca89642 100644 --- 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 @@ -28,6 +28,7 @@ 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; @@ -64,11 +65,12 @@ class PreseededActorAssignmentIntegrationTest { private UUID namespaceUuid; @Container - static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static GenericContainer redis = - new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { From 512641af1f2523475aaef90b850f5f139b22f0f0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 02:35:07 +1300 Subject: [PATCH 04/61] Prepare byte-preserving PRESEEDED migration tail for qualified parent carry --- .../api-contracts.md | 2 + .../runtime-and-data.md | 1 + .../gameplay-rules-entities-and-effects.md | 2 + ... => V1006__preseeded_actor_assignment.sql} | 0 ...__preseeded_assignment_owner_snapshot.sql} | 0 ...__canonical_gameplay_roster_snapshots.sql} | 0 ...nical_publication_uuid_actor_evidence.sql} | 0 ...1010__canonical_roster_owner_counters.sql} | 0 ...eseededActorAssignmentIntegrationTest.java | 64 +++++++++++++++++-- 9 files changed, 65 insertions(+), 4 deletions(-) rename services/entity-management-service/src/main/resources/db/migration/{V5__preseeded_actor_assignment.sql => V1006__preseeded_actor_assignment.sql} (100%) rename services/entity-management-service/src/main/resources/db/migration/{V6__preseeded_assignment_owner_snapshot.sql => V1007__preseeded_assignment_owner_snapshot.sql} (100%) rename services/entity-management-service/src/main/resources/db/migration/{V7__canonical_gameplay_roster_snapshots.sql => V1008__canonical_gameplay_roster_snapshots.sql} (100%) rename services/entity-management-service/src/main/resources/db/migration/{V8__canonical_publication_uuid_actor_evidence.sql => V1009__canonical_publication_uuid_actor_evidence.sql} (100%) rename services/entity-management-service/src/main/resources/db/migration/{V9__canonical_roster_owner_counters.sql => V1010__canonical_roster_owner_counters.sql} (100%) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index c0dd504944..986a71f973 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,6 +6,8 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status +The local append-only Entity migration repair is provisional pending the parent V1003–V1005 carry and fresh PostgreSQL proof of the combined Entity/Saga upgrade through V1010; earlier test results do not validate this candidate. See [GR-3.1 proof qualification](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). + The canonical `CanonicalGameplayRosterService` proto defines two pre-admission reads restricted to `PRESEEDED_ONLY`; these reads do not admit or activate gameplay. Entity Java handlers implement both methods behind default-off owner-read configuration and the exact same-namespace Game Session mTLS peer allowlist. Their request models and adapter carry and validate typed `PlayerExecutionContext`; selected reads require and revalidate the supplied snapshot UUID/digest against the existing sealed snapshot and current owner-resolved roster, return the original persisted assignment receipt reference, and use canonical non-OK statuses without partial responses. This source does not establish fresh Account eligibility, gameplay admission, PLAY, or production owner provenance. Current PostgreSQL test results and remaining authenticated Game Session-to-Entity mTLS/network, restart, and owner-provenance gaps are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#capability-status). 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. 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 ebd2cef6c6..a06e00cc62 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -4,6 +4,7 @@ This document defines Entity Management’s runtime model, persistence ownership ## Implementation Status +- The local append-only migration candidate assigns the preseeded assignment, owner snapshot, roster snapshot, canonical publication evidence, and owner-counter migrations to V1006–V1010 without changing SQL bytes. The candidate remains provisional until the parent V1003–V1005 carry and fresh combined Entity/Saga upgrade proof; see [GR-3.1 proof qualification](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). - The current crafting REST adapter is runtime-reachable legacy implementation drift, not a supported or advertised boundary: the crafting paths and schemas are omitted from the ping-only authoritative OpenAPI, whose root `security: []` applies only to the health contract, so the adapter remains unsupported/nonconformant. The deployed interceptor requires any `AUTHENTICATED` bearer because this non-public path is not in the public-route list, but neither layer provides tenant binding; there is no controller `SessionContext` tenant guard. `CraftingServiceImpl` trusts the DTO's `tenantId`, `resultItemId`, and ingredient item IDs; `CraftingRecipeRepository.findWithIngredientsById` and the update branch use recipe ID alone, while ingredient loading also uses recipe ID alone. The tenant-qualified list methods first select IDs but then re-enter that unqualified lookup, so they are not evidence of an end-to-end tenant predicate. Existing crafting tests do not establish caller-tenant authorization, cross-tenant recipe isolation, or same-tenant result/ingredient ownership. - World-owned `character_location` and `npc_location` tables plus their authoritative movement, occupancy, and read/write paths are target-only. They are absent from the current schema, migrations, and runtime; `room_instance` is topology rather than actor location, and a Game Session room binding is not World location authority. Entity Management must not add competing location persistence or treat a cache/projection as authoritative. - **Target crafting boundary:** require authenticated caller context and exact tenant authorization before any recipe operation, derive the target tenant rather than treating request `tenantId` as authority, and make recipe read/update and ingredient load/update predicates tenant-qualified. Validate that the result item and every ingredient item belong to the target tenant and the same applicable version/Draft scope before writing. A missing context, tenant mismatch, recipe mismatch, or cross-tenant item reference fails closed before any recipe or ingredient mutation; the target negative proof must exercise each case. 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 d27d7330d7..d37fe0f303 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 @@ -113,6 +113,8 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Validation and Proof +- GR-3.1 append-only migration repair is a local, unvalidated candidate: Entity's former V5–V9 scripts are renamed byte-for-byte to V1006–V1010, following the separately carried parent V1003–V1005 and unchanged V1/common Saga V1000–V1002. `PreseededActorAssignmentIntegrationTest` now uses the default combined Entity/Saga locations, a history table derived from its test `serviceSchema`, and `outOfOrder=false`; the actual-parent upgrade case asserts the exact parent manifest, retained scripts/checksums, and ordered V1006–V1010 tail while retaining actor checks. These assertions have not run. Parent carry, Entity `generateJooq`, `check -PfullCheck`, fresh PostgreSQL and actual-parent upgrade proof, and documentation checks remain required; earlier recorded runs do not validate this candidate. + - 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/services/entity-management-service/src/main/resources/db/migration/V5__preseeded_actor_assignment.sql b/services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql similarity index 100% rename from services/entity-management-service/src/main/resources/db/migration/V5__preseeded_actor_assignment.sql rename to services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql diff --git a/services/entity-management-service/src/main/resources/db/migration/V6__preseeded_assignment_owner_snapshot.sql b/services/entity-management-service/src/main/resources/db/migration/V1007__preseeded_assignment_owner_snapshot.sql similarity index 100% rename from services/entity-management-service/src/main/resources/db/migration/V6__preseeded_assignment_owner_snapshot.sql rename to services/entity-management-service/src/main/resources/db/migration/V1007__preseeded_assignment_owner_snapshot.sql diff --git a/services/entity-management-service/src/main/resources/db/migration/V7__canonical_gameplay_roster_snapshots.sql b/services/entity-management-service/src/main/resources/db/migration/V1008__canonical_gameplay_roster_snapshots.sql similarity index 100% rename from services/entity-management-service/src/main/resources/db/migration/V7__canonical_gameplay_roster_snapshots.sql rename to services/entity-management-service/src/main/resources/db/migration/V1008__canonical_gameplay_roster_snapshots.sql diff --git a/services/entity-management-service/src/main/resources/db/migration/V8__canonical_publication_uuid_actor_evidence.sql b/services/entity-management-service/src/main/resources/db/migration/V1009__canonical_publication_uuid_actor_evidence.sql similarity index 100% rename from services/entity-management-service/src/main/resources/db/migration/V8__canonical_publication_uuid_actor_evidence.sql rename to services/entity-management-service/src/main/resources/db/migration/V1009__canonical_publication_uuid_actor_evidence.sql diff --git a/services/entity-management-service/src/main/resources/db/migration/V9__canonical_roster_owner_counters.sql b/services/entity-management-service/src/main/resources/db/migration/V1010__canonical_roster_owner_counters.sql similarity index 100% rename from services/entity-management-service/src/main/resources/db/migration/V9__canonical_roster_owner_counters.sql rename to services/entity-management-service/src/main/resources/db/migration/V1010__canonical_roster_owner_counters.sql 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 index 63fca89642..4dfc626c45 100644 --- 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 @@ -10,6 +10,7 @@ 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.UUID; @@ -166,7 +167,7 @@ void migrationRetainsOlderRosterEvidenceWithoutBackfillingOwnerCounters() throws UUID historicalNamespace = UUID.randomUUID(); UUID v8CanonicalVersion = UUID.randomUUID(); - migrationFlyway(schema).target(MigrationVersion.fromVersion("7")).load().migrate(); + migrationFlyway(schema).target(MigrationVersion.fromVersion("1008")).load().migrate(); try (Connection connection = connectToSchema(schema)) { try (PreparedStatement tenant = connection.prepareStatement( @@ -210,7 +211,7 @@ void migrationRetainsOlderRosterEvidenceWithoutBackfillingOwnerCounters() throws } } - migrationFlyway(schema).target(MigrationVersion.fromVersion("8")).load().migrate(); + migrationFlyway(schema).target(MigrationVersion.fromVersion("1009")).load().migrate(); try (Connection connection = connectToSchema(schema); PreparedStatement snapshot = connection.prepareStatement( @@ -289,7 +290,22 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( UUID retainedTenantUuid = UUID.randomUUID(); UUID retainedNamespaceUuid = UUID.randomUUID(); - migrationFlyway(schema).target(MigrationVersion.fromVersion("4")).load().migrate(); + migrationFlyway(schema).target(MigrationVersion.fromVersion("1005")).load().migrate(); + List parentHistory = appliedMigrationHistory(schema); + 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( @@ -323,6 +339,24 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( migrationFlyway(schema).load().migrate(); + List upgradedHistory = appliedMigrationHistory(schema); + 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( @@ -1081,7 +1115,9 @@ private FluentConfiguration migrationFlyway(String schema) { .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) .schemas(schema) .defaultSchema(schema) - .locations("classpath:db/migration") + .locations("classpath:db/migration", "classpath:db/migration/saga") + .table("flyway_schema_history_" + schema) + .outOfOrder(false) .placeholders(Map.of("serviceSchema", schema)); configuration .getConfigurationExtension(PostgreSQLConfigurationExtension.class) @@ -1089,6 +1125,26 @@ private FluentConfiguration migrationFlyway(String schema) { 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 version, script, checksum FROM flyway_schema_history_" + + schema + + " WHERE success AND version IS NOT NULL ORDER BY installed_rank")) { + while (rows.next()) { + migrations.add( + new AppliedMigration( + rows.getString(1), rows.getString(2), rows.getObject(3, Integer.class))); + } + } + return migrations; + } + + private record AppliedMigration(String version, String script, Integer checksum) {} + private Connection connectToSchema(String schema) throws SQLException { Connection connection = DriverManager.getConnection( From ce3a9e4c72fb9be2a3640c302cac4efb3145acf3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:31:22 +1300 Subject: [PATCH 05/61] Keep canonical roster and assignment source unregistered --- .../entity-management-service/README.md | 2 +- .../api-contracts.md | 4 +- .../runtime-and-data.md | 2 +- .../gameplay-rules-entities-and-effects.md | 4 +- .../CanonicalGameplayRosterConfiguration.java | 49 +---- ...PreseededActorAssignmentConfiguration.java | 137 +++---------- .../CanonicalGameplayRosterGrpcAdapter.java | 2 - .../src/main/resources/application.yml | 2 - ...onicalGameplayRosterConfigurationTest.java | 192 ++++++++++++++---- ...eededActorAssignmentConfigurationTest.java | 145 ++++++++----- ...icalGameplayRosterPeerInterceptorTest.java | 11 +- 11 files changed, 295 insertions(+), 255 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/README.md b/design/architecture/microservices/entity-management-service/README.md index 446abd5e8e..c1b8221b74 100644 --- a/design/architecture/microservices/entity-management-service/README.md +++ b/design/architecture/microservices/entity-management-service/README.md @@ -6,7 +6,7 @@ Handles player characters, NPCs, runtime actor identity, items, and all inventor ## Implementation Status -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. +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 services, certificate-guarded clients, peer interceptor, and gRPC read adapter remain manually composed source definitions with no automatic Spring or gRPC registration. Their bridge limits and registration prerequisites are recorded in [Entity API Contracts](./api-contracts.md#implementation-status). 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. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 8d5e80bed4..b491064321 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,7 +6,9 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status -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. +Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has manually composed certificate-guarded client, peer-interceptor, and read-adapter source definitions, but no automatic runtime handler, client, or service-bean registration. Default component scanning and legacy activation flags leave this family unregistered; [Runtime and Data](./runtime-and-data.md#implementation-status) owns its registration prerequisites. 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 manually composed Account/Game Session evidence bridge currently supports `SHARED` only; the assignment bridge requires already canonical, non-nil UUID game-instance text under the existing bridge contract. Those bounded adapters supply no owner proof outside their declared scope. They do not narrow the passive assignment core, which supports `SHARED` and `ISOLATED` and hashes exact bounded opaque game-instance text without parsing or normalization. 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. 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 a8c377679e..1fb2ffe636 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -22,7 +22,7 @@ This document defines Entity Management’s runtime model, persistence ownership - `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). +- Entity V1006–V1010 adds committed assignment/receipt and sealed roster-snapshot storage with canonical publication identity and exact owner counters. The services and certificate-guarded client/read-adapter source definitions are manually composed and unregistered; neither default scanning nor an optional flag registers them. No authenticated production 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. 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 7a8b72e22c..ddc01b2603 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 @@ -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` - 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.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 and guarded read-client/adapter definitions 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,8 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Validation and Proof +- The 2026-10-14 current-parent source correction keeps the assignment/roster family unregistered under ordinary component scanning, including when the former activation flags are true, and excludes both roster methods from the JWT public-method allowlist. The initial consolidated gate executed 281 Entity unit cases with one stale allowlist assertion failure, 30 native PostgreSQL cases with no failures, errors or skips, and 17 focused Game Session roster-client cases with no failures, errors or skips. After correcting that assertion, all 11 focused registration, manual-composition and peer-policy cases passed with no failures, errors or skips; affected formatting, static analysis and documentation checks passed. These combined results qualify the bounded source and unchanged retained storage, not production registration, ADR 0163 disposal, genuine authenticated caller completion or a fresh packaged player journey. + - 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. diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfiguration.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfiguration.java index 0ab7e890c9..e7a3f0a940 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfiguration.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfiguration.java @@ -10,23 +10,14 @@ import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSelectedAssignmentService; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterService; import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.grpc.server.GlobalServerInterceptor; -/** Wires guarded roster discovery with default-off mTLS Game Session owner evidence. */ -@Configuration +/** + * Manual factories for the passive canonical gameplay roster source. + * + *

This class is deliberately not a Spring configuration. Production component scanning does not + * register these factories, their services, or their owner-read client. + */ public class CanonicalGameplayRosterConfiguration { - @Bean - @ConditionalOnProperty( - prefix = "firemud.canonical-gameplay-roster-owner-read", - name = "enabled", - havingValue = "false", - matchIfMissing = true) - @ConditionalOnMissingBean(CanonicalGameplayRosterOwnerEvidencePort.class) public CanonicalGameplayRosterOwnerEvidencePort unavailableCanonicalGameplayRosterOwnerEvidence() { return request -> { @@ -34,49 +25,31 @@ public class CanonicalGameplayRosterConfiguration { }; } - @Bean(initMethod = "init", destroyMethod = "close") - @ConditionalOnProperty( - prefix = "firemud.canonical-gameplay-roster-owner-read", - name = "enabled", - havingValue = "true") - @ConditionalOnMissingBean({ - CanonicalGameplayRosterOwnerEvidencePort.class, - GameSessionCanonicalGameplayRosterOwnerReadClient.class - }) + /** Creates an owner-read client for an explicitly controlled composition. */ public GameSessionCanonicalGameplayRosterOwnerReadClient gameSessionCanonicalGameplayRosterOwnerReadClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, - @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + String workloadNamespace) { return new GameSessionCanonicalGameplayRosterOwnerReadClient( endpoints, tlsProperties, channelFactory, workloadNamespace); } - @Bean - @ConditionalOnProperty( - prefix = "firemud.canonical-gameplay-roster-owner-read", - name = "enabled", - havingValue = "true") - @ConditionalOnMissingBean(CanonicalGameplayRosterOwnerEvidencePort.class) public CanonicalGameplayRosterOwnerEvidencePort gameSessionCanonicalGameplayRosterOwnerEvidencePort( GameSessionCanonicalGameplayRosterOwnerReadClient ownerReadClient, - @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + String workloadNamespace) { return new GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter( ownerReadClient, workloadNamespace); } - @Bean - @ConditionalOnMissingBean public CanonicalGameplayRosterService canonicalGameplayRosterService( CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort, CharacterRepository characterRepository) { return new CanonicalGameplayRosterService(ownerEvidencePort, characterRepository); } - @Bean - @ConditionalOnMissingBean public CanonicalGameplayRosterSelectedAssignmentService canonicalGameplayRosterSelectedAssignmentService( CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort, @@ -85,10 +58,8 @@ public CanonicalGameplayRosterService canonicalGameplayRosterService( ownerEvidencePort, characterRepository); } - @Bean - @GlobalServerInterceptor public CanonicalGameplayRosterPeerInterceptor canonicalGameplayRosterPeerInterceptor( - @Value("${firemud.grpc.workload-namespace:}") String trustedNamespace) { + String trustedNamespace) { return new CanonicalGameplayRosterPeerInterceptor(trustedNamespace); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java index 04bace5558..2864a69181 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfiguration.java @@ -20,133 +20,74 @@ import net.firedevops.firemud.entitymanagement.service.RunOwnedPreseededActorAssignmentAuthorityAdapter; import net.firedevops.firemud.entitymanagement.service.RunOwnedPreseededAssignmentAuthority; import net.firedevops.firemud.entitymanagement.service.impl.GameSessionPreseededActorAssignmentOwnerEvidenceAdapter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.ssl.SslBundles; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; /** - * Wires the bounded Entity writer while leaving Account/owner evidence and run authorization denied - * unless their explicitly enabled producers are present. + * Manual factories for passive preseeded-actor assignment source services. + * + *

This class is deliberately not a Spring configuration. Production component scanning does not + * register these factories, their services, or their owner-read clients. */ -@Configuration public class PreseededActorAssignmentConfiguration { - @Bean - @ConditionalOnProperty( - prefix = "firemud.run-owned-preseeded-actor-assignment", - name = "enabled", - havingValue = "false", - matchIfMissing = true) - @ConditionalOnMissingBean(PreseededActorAccountIdentityPort.class) public PreseededActorAccountIdentityPort disabledPreseededActorAccountIdentityPort() { return (accountUuid, assignmentUuid) -> { throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_IDENTITY_UNAVAILABLE"); }; } - @Bean(initMethod = "init", destroyMethod = "close") - @ConditionalOnProperty( - prefix = "firemud.run-owned-preseeded-actor-assignment", - name = "enabled", - havingValue = "true") - @ConditionalOnMissingBean({ - PreseededActorAccountIdentityPort.class, - AccountRuntimeIdentityClient.class - }) + /** Creates an Account identity client for an explicitly controlled composition. */ public AccountRuntimeIdentityClient preseededActorAccountIdentityClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, - @org.springframework.beans.factory.annotation.Value("${firemud.grpc.workload-namespace:}") - String workloadNamespace) { + String workloadNamespace) { return new AccountRuntimeIdentityClient( endpoints, tlsProperties, channelFactory, workloadNamespace); } - @Bean - @ConditionalOnProperty( - prefix = "firemud.run-owned-preseeded-actor-assignment", - name = "enabled", - havingValue = "true") - @ConditionalOnMissingBean(PreseededActorAccountIdentityPort.class) public PreseededActorAccountIdentityPort enabledPreseededActorAccountIdentityPort( AccountRuntimeIdentityClient accountIdentityClient) { return accountIdentityClient::resolveRuntimeAccountIdentity; } - @Bean - @ConditionalOnProperty( - prefix = "firemud.run-owned-preseeded-actor-assignment", - name = "enabled", - havingValue = "false", - matchIfMissing = true) - @ConditionalOnMissingBean(PreseededActorStagingEligibilityPort.class) public PreseededActorStagingEligibilityPort disabledPreseededActorStagingEligibilityPort() { return (accountUuid, tenantUuid, assignmentUuid) -> { throw new IllegalStateException("PRESEEDED_ASSIGNMENT_ACCOUNT_STAGING_EVIDENCE_UNAVAILABLE"); }; } - @Bean(initMethod = "init", destroyMethod = "close") - @ConditionalOnProperty( - prefix = "firemud.run-owned-preseeded-actor-assignment", - name = "enabled", - havingValue = "true") - @ConditionalOnMissingBean({ - PreseededActorStagingEligibilityPort.class, - AccountPreseededActorStagingEligibilityClient.class - }) + /** Creates an Account staging client for an explicitly controlled composition. */ public AccountPreseededActorStagingEligibilityClient preseededActorStagingEligibilityClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, - @org.springframework.beans.factory.annotation.Value("${firemud.grpc.workload-namespace:}") - String workloadNamespace) { + String workloadNamespace) { return new AccountPreseededActorStagingEligibilityClient( endpoints, tlsProperties, channelFactory, workloadNamespace); } - @Bean(initMethod = "init", destroyMethod = "close") - @ConditionalOnProperty( - prefix = "firemud.run-owned-preseeded-actor-assignment", - name = "enabled", - havingValue = "true") - @ConditionalOnMissingBean({ - PreseededActorAssignmentOwnerEvidencePort.class, - GameSessionPreseededActorAssignmentOwnerReadClient.class - }) + public PreseededActorStagingEligibilityPort enabledPreseededActorStagingEligibilityPort( + AccountPreseededActorStagingEligibilityClient stagingEligibilityClient) { + return stagingEligibilityClient::resolvePreseededActorStagingEligibility; + } + + /** Creates a Game Session owner-read client for an explicitly controlled composition. */ public GameSessionPreseededActorAssignmentOwnerReadClient preseededActorAssignmentOwnerReadClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, - @org.springframework.beans.factory.annotation.Value("${firemud.grpc.workload-namespace:}") - String workloadNamespace) { + String workloadNamespace) { return new GameSessionPreseededActorAssignmentOwnerReadClient( endpoints, tlsProperties, channelFactory, workloadNamespace); } - @Bean - @ConditionalOnProperty( - prefix = "firemud.run-owned-preseeded-actor-assignment", - name = "enabled", - havingValue = "true") - @ConditionalOnMissingBean(PreseededActorAssignmentOwnerEvidencePort.class) public PreseededActorAssignmentOwnerEvidencePort preseededActorAssignmentOwnerEvidencePort( GameSessionPreseededActorAssignmentOwnerReadClient gameSessionClient, - @org.springframework.beans.factory.annotation.Value("${firemud.grpc.workload-namespace:}") - String workloadNamespace) { + String workloadNamespace) { return new GameSessionPreseededActorAssignmentOwnerEvidenceAdapter( gameSessionClient, workloadNamespace); } - @Bean - @ConditionalOnProperty( - prefix = "firemud.run-owned-preseeded-actor-assignment", - name = "enabled", - havingValue = "false", - matchIfMissing = true) - @ConditionalOnMissingBean(RunOwnedPreseededAssignmentAuthority.class) public RunOwnedPreseededAssignmentAuthority disabledRunOwnedPreseededAssignmentAuthority() { return new RunOwnedPreseededAssignmentAuthority() { @Override @@ -166,29 +107,14 @@ public void requireTargetBoundAuthorized( }; } - @Bean - @ConditionalOnProperty( - prefix = "firemud.run-owned-preseeded-actor-assignment", - name = "enabled", - havingValue = "true") - @ConditionalOnMissingBean(RunOwnedPreseededAssignmentAuthority.class) + /** Creates run-owned authority from caller-supplied active server trust material. */ public RunOwnedPreseededAssignmentAuthority runOwnedPreseededAssignmentAuthorityFromCapability( - @org.springframework.beans.factory.annotation.Value( - "${firemud.run-owned-preseeded-actor-assignment.capability-path:}") - String capabilityPath, - @org.springframework.beans.factory.annotation.Value( - "${firemud.run-owned-preseeded-actor-assignment.run-id:}") - String runId, - @org.springframework.beans.factory.annotation.Value( - "${firemud.run-owned-preseeded-actor-assignment.compose-project-name:}") - String composeProjectName, - @org.springframework.beans.factory.annotation.Value("${firemud.grpc.workload-namespace:}") - String workloadNamespace, - @org.springframework.beans.factory.annotation.Value( - "${spring.ssl.bundle.pem.firemud-grpc.truststore.certificate:}") - String entityServerTrustRoot, - @org.springframework.beans.factory.annotation.Value("${spring.grpc.server.ssl.bundle:}") - String activeServerTlsBundleName, + String capabilityPath, + String runId, + String composeProjectName, + String workloadNamespace, + String entityServerTrustRoot, + String activeServerTlsBundleName, SslBundles sslBundles) { return RunOwnedPreseededActorAssignmentAuthorityAdapter.forActiveServerTrustBundle( capabilityPath, @@ -201,18 +127,9 @@ public RunOwnedPreseededAssignmentAuthority runOwnedPreseededAssignmentAuthority } /** - * The enabled source adapter combines one current Account staging snapshot with exact current - * Game Session/Game Design selectors. Account status is a point-in-time observation, not a held - * JOIN authorization, PLAY grant, or gameplay admission decision; persisted assignments do not - * authorize runtime admission or activation. + * The manually selected unavailable source adapter fails closed; assignment remains + * non-admitting. */ - @Bean - @ConditionalOnProperty( - prefix = "firemud.run-owned-preseeded-actor-assignment", - name = "enabled", - havingValue = "false", - matchIfMissing = true) - @ConditionalOnMissingBean(PreseededActorAssignmentOwnerEvidencePort.class) public PreseededActorAssignmentOwnerEvidencePort unavailablePreseededActorAssignmentOwnerEvidencePort() { return (PreseededActorAssignmentRequest request, @@ -222,8 +139,6 @@ public RunOwnedPreseededAssignmentAuthority runOwnedPreseededAssignmentAuthority }; } - @Bean - @ConditionalOnMissingBean public PreseededActorAssignmentService preseededActorAssignmentService( RunOwnedPreseededAssignmentAuthority runAuthority, PreseededActorAccountIdentityPort accountIdentityPort, @@ -239,8 +154,6 @@ public PreseededActorAssignmentService preseededActorAssignmentService( } /** Receipt reads are read-only and remain available when assignment creation is disabled. */ - @Bean - @ConditionalOnMissingBean public PreseededActorAssignmentReceiptService preseededActorAssignmentReceiptService( CharacterRepository characterRepository) { return new PreseededActorAssignmentReceiptService(characterRepository); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java index f571593630..2c2decab5e 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java @@ -34,10 +34,8 @@ import org.jooq.exception.DataAccessException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.grpc.server.service.GrpcService; /** Dedicated certificate-guarded non-admitting canonical roster gRPC boundary. */ -@GrpcService public final class CanonicalGameplayRosterGrpcAdapter extends CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceImplBase { private static final Logger LOGGER = diff --git a/services/entity-management-service/src/main/resources/application.yml b/services/entity-management-service/src/main/resources/application.yml index ae92704625..54a96253b4 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -75,8 +75,6 @@ firemud: grpc: public-methods: - entity_management.v1.EntityManagementService/Ping - - entity_management.v1.CanonicalGameplayRosterService/ListPreseededRoster - - entity_management.v1.CanonicalGameplayRosterService/ReadSelectedPreseededAssignment grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java index 55d59e8b95..eda86948f3 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java @@ -3,60 +3,174 @@ 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.verifyNoInteractions; +import java.util.Arrays; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.entitymanagement.client.AccountPreseededActorStagingEligibilityClient; +import net.firedevops.firemud.entitymanagement.client.AccountRuntimeIdentityClient; import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.client.GameSessionPreseededActorAssignmentOwnerReadClient; import net.firedevops.firemud.entitymanagement.config.CanonicalGameplayRosterConfiguration; +import net.firedevops.firemud.entitymanagement.config.PreseededActorAssignmentConfiguration; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.security.CanonicalGameplayRosterPeerInterceptor; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterExecutionContext; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterOwnerEvidencePort; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSelectedAssignmentService; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterService; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentReceiptService; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentService; +import net.firedevops.firemud.entitymanagement.service.impl.CanonicalGameplayRosterGrpcAdapter; import net.firedevops.firemud.entitymanagement.service.impl.GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.MapPropertySource; class CanonicalGameplayRosterConfigurationTest { @Test - void defaultConfigurationKeepsGameSessionOwnerReadDisabledAndDenied() { - runner() - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .doesNotHaveBean(GameSessionCanonicalGameplayRosterOwnerReadClient.class); - assertThat(context).hasSingleBean(CanonicalGameplayRosterOwnerEvidencePort.class); - assertThat(context) - .hasSingleBean(CanonicalGameplayRosterSelectedAssignmentService.class); - assertThat(context.getBean(CanonicalGameplayRosterOwnerEvidencePort.class)) - .isNotInstanceOf(GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.class); - assertThatThrownBy( - () -> - context - .getBean(CanonicalGameplayRosterOwnerEvidencePort.class) - .resolveCurrentTarget(null)) - .isInstanceOf( - CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException - .class); - }); + void applicationComponentScanDoesNotRegisterPassiveSourcesEvenWhenFlagsAreTrue() { + try (var context = new AnnotationConfigApplicationContext()) { + context + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "passive-source-test", + Map.of( + "firemud.canonical-gameplay-roster-owner-read.enabled", + "true", + "firemud.run-owned-preseeded-actor-assignment.enabled", + "true"))); + context.scan("net.firedevops.firemud.entitymanagement"); + + Set registeredClassNames = + Arrays.stream(context.getBeanFactory().getBeanDefinitionNames()) + .map(name -> context.getBeanFactory().getBeanDefinition(name).getBeanClassName()) + .filter(className -> className != null) + .collect(Collectors.toSet()); + + assertThat( + context + .getEnvironment() + .getProperty("firemud.canonical-gameplay-roster-owner-read.enabled")) + .isEqualTo("true"); + assertThat( + context + .getEnvironment() + .getProperty("firemud.run-owned-preseeded-actor-assignment.enabled")) + .isEqualTo("true"); + assertThat(registeredClassNames).contains(CharacterRepository.class.getName()); + assertThat(registeredClassNames) + .doesNotContain( + CanonicalGameplayRosterConfiguration.class.getName(), + PreseededActorAssignmentConfiguration.class.getName(), + CanonicalGameplayRosterService.class.getName(), + CanonicalGameplayRosterSelectedAssignmentService.class.getName(), + PreseededActorAssignmentService.class.getName(), + PreseededActorAssignmentReceiptService.class.getName(), + GameSessionCanonicalGameplayRosterOwnerReadClient.class.getName(), + GameSessionPreseededActorAssignmentOwnerReadClient.class.getName(), + AccountRuntimeIdentityClient.class.getName(), + AccountPreseededActorStagingEligibilityClient.class.getName(), + CanonicalGameplayRosterGrpcAdapter.class.getName(), + CanonicalGameplayRosterPeerInterceptor.class.getName()); + } + } + + @Test + void manualCompositionUsesDefaultDeniedOwnerEvidence() { + var configuration = new CanonicalGameplayRosterConfiguration(); + CharacterRepository repository = mock(CharacterRepository.class); + CanonicalGameplayRosterOwnerEvidencePort ownerEvidencePort = + configuration.unavailableCanonicalGameplayRosterOwnerEvidence(); + CanonicalGameplayRosterService service = + configuration.canonicalGameplayRosterService(ownerEvidencePort, repository); + + assertThatThrownBy(() -> service.read(request(target()))) + .isInstanceOf( + CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException.class) + .hasMessage("CANONICAL_GAMEPLAY_ROSTER_OWNER_EVIDENCE_UNAVAILABLE"); + verifyNoInteractions(repository); } @Test - void explicitEnablementComposesTheEntityAdapterAroundThePinnedGameSessionClient() { - var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); - runner() - .withPropertyValues("firemud.canonical-gameplay-roster-owner-read.enabled=true") - .withBean(GameSessionCanonicalGameplayRosterOwnerReadClient.class, () -> client) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .getBean(CanonicalGameplayRosterOwnerEvidencePort.class) - .isInstanceOf(GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.class); - }); + void explicitlyInvokedFactoriesCreateOnlyTheSuppliedOwnerReadComposition() { + var configuration = new CanonicalGameplayRosterConfiguration(); + var channels = mock(GrpcChannelFactory.class); + var manuallyCreatedClient = + configuration.gameSessionCanonicalGameplayRosterOwnerReadClient( + new ServiceEndpointsProperties(), tlsProperties(), channels, "gameplay"); + var suppliedClient = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var ownerEvidencePort = + configuration.gameSessionCanonicalGameplayRosterOwnerEvidencePort( + suppliedClient, "gameplay"); + var service = + configuration.canonicalGameplayRosterService( + ownerEvidencePort, mock(CharacterRepository.class)); + + assertThat(manuallyCreatedClient) + .isInstanceOf(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + assertThat(ownerEvidencePort) + .isInstanceOf(GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.class); + assertThat(service).isInstanceOf(CanonicalGameplayRosterService.class); + verifyNoInteractions(channels); + } + + 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 CanonicalGameplayRosterTarget target() { + return new CanonicalGameplayRosterTarget( + UUID.randomUUID(), + UUID.randomUUID(), + "world", + "realm", + UUID.randomUUID(), + 3L, + 17L, + 29L, + UUID.randomUUID(), + "1".repeat(64), + "release/test", + "2".repeat(64), + "3".repeat(64), + UUID.randomUUID(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); } - private static ApplicationContextRunner runner() { - return new ApplicationContextRunner() - .withUserConfiguration(CanonicalGameplayRosterConfiguration.class) - .withPropertyValues("firemud.grpc.workload-namespace=test") - .withBean(CharacterRepository.class, () -> mock(CharacterRepository.class)); + private static CommonGrpcClientProperties tlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("entity-client.crt"); + tls.setPrivateKey("entity-client.key"); + tls.setCaCert("game-session-ca.crt"); + return tls; } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java index 5092100f54..c63ec14c7d 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java @@ -3,78 +3,123 @@ 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.verifyNoInteractions; +import java.util.UUID; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.entitymanagement.client.AccountPreseededActorStagingEligibilityClient; +import net.firedevops.firemud.entitymanagement.client.AccountRuntimeIdentityClient; import net.firedevops.firemud.entitymanagement.client.GameSessionPreseededActorAssignmentOwnerReadClient; import net.firedevops.firemud.entitymanagement.config.PreseededActorAssignmentConfiguration; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; -import net.firedevops.firemud.entitymanagement.service.PreseededActorAccountIdentityPort; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentExpectedTarget; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentOwnerEvidencePort; -import net.firedevops.firemud.entitymanagement.service.PreseededActorStagingEligibilityPort; -import net.firedevops.firemud.entitymanagement.service.RunOwnedPreseededAssignmentAuthority; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; +import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentService; +import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; import net.firedevops.firemud.entitymanagement.service.impl.GameSessionPreseededActorAssignmentOwnerEvidenceAdapter; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; class PreseededActorAssignmentConfigurationTest { @Test - void defaultConfigurationLeavesOwnerEvidenceUnavailableAndDoesNotCreateGsClient() { - runner() - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .doesNotHaveBean(GameSessionPreseededActorAssignmentOwnerReadClient.class); - assertThat(context).hasSingleBean(PreseededActorAssignmentOwnerEvidencePort.class); - assertThat(context.getBean(PreseededActorAssignmentOwnerEvidencePort.class)) - .isNotInstanceOf(GameSessionPreseededActorAssignmentOwnerEvidenceAdapter.class); - assertThatThrownBy( - () -> - context - .getBean(PreseededActorAssignmentOwnerEvidencePort.class) - .resolveCurrentEligibleTarget(null, null, null)) - .isInstanceOf( - PreseededActorAssignmentOwnerEvidencePort.OwnerEvidenceUnavailableException - .class); - }); + void manualCompositionDeniesByDefaultBeforeReadsOrPersistence() { + var configuration = new PreseededActorAssignmentConfiguration(); + var request = request(); + var repository = mock(CharacterRepository.class); + var runAuthority = configuration.disabledRunOwnedPreseededAssignmentAuthority(); + var accountIdentityPort = configuration.disabledPreseededActorAccountIdentityPort(); + var stagingEligibilityPort = configuration.disabledPreseededActorStagingEligibilityPort(); + var ownerEvidencePort = configuration.unavailablePreseededActorAssignmentOwnerEvidencePort(); + PreseededActorAssignmentService service = + configuration.preseededActorAssignmentService( + runAuthority, + accountIdentityPort, + stagingEligibilityPort, + ownerEvidencePort, + repository); + + assertThatThrownBy(() -> service.assign(request)) + .isInstanceOf(AdminAuthorizationException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_RUN_OWNED_ACTION_GRANT_UNAVAILABLE"); + assertThatThrownBy( + () -> + accountIdentityPort.resolveRuntimeAccountIdentity( + request.canonicalAccountUuid().toString(), request.assignmentUuid().toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_ACCOUNT_IDENTITY_UNAVAILABLE"); + assertThatThrownBy( + () -> + stagingEligibilityPort.resolvePreseededActorStagingEligibility( + request.canonicalAccountUuid().toString(), + request.expectedTarget().canonicalTenantUuid().toString(), + request.assignmentUuid().toString())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PRESEEDED_ASSIGNMENT_ACCOUNT_STAGING_EVIDENCE_UNAVAILABLE"); + assertThatThrownBy(() -> ownerEvidencePort.resolveCurrentEligibleTarget(request, null, null)) + .isInstanceOf( + PreseededActorAssignmentOwnerEvidencePort.OwnerEvidenceUnavailableException.class); + verifyNoInteractions(repository); } @Test - void explicitRunOwnedEnablementComposesTheGsAssignmentOwnerAdapter() { - var gsClient = client(); - runner() - .withPropertyValues("firemud.run-owned-preseeded-actor-assignment.enabled=true") - .withBean(PreseededActorAccountIdentityPort.class, () -> (account, assignment) -> null) - .withBean( - PreseededActorStagingEligibilityPort.class, () -> (account, tenant, assignment) -> null) - .withBean( - RunOwnedPreseededAssignmentAuthority.class, - () -> mock(RunOwnedPreseededAssignmentAuthority.class)) - .withBean(GameSessionPreseededActorAssignmentOwnerReadClient.class, () -> gsClient) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .getBean(PreseededActorAssignmentOwnerEvidencePort.class) - .isInstanceOf(GameSessionPreseededActorAssignmentOwnerEvidenceAdapter.class); - }); + void explicitlyInvokedFactoriesCreateOnlyTheSuppliedOwnerReadComposition() { + var configuration = new PreseededActorAssignmentConfiguration(); + var channels = mock(GrpcChannelFactory.class); + var endpoints = new ServiceEndpointsProperties(); + var tls = tlsProperties(); + var accountIdentityClient = + configuration.preseededActorAccountIdentityClient(endpoints, tls, channels, "gameplay"); + var stagingEligibilityClient = + configuration.preseededActorStagingEligibilityClient(endpoints, tls, channels, "gameplay"); + var ownerReadClient = + configuration.preseededActorAssignmentOwnerReadClient(endpoints, tls, channels, "gameplay"); + var accountIdentityPort = + configuration.enabledPreseededActorAccountIdentityPort(accountIdentityClient); + var stagingEligibilityPort = + configuration.enabledPreseededActorStagingEligibilityPort(stagingEligibilityClient); + var ownerEvidencePort = + configuration.preseededActorAssignmentOwnerEvidencePort(ownerReadClient, "gameplay"); + + assertThat(accountIdentityClient).isInstanceOf(AccountRuntimeIdentityClient.class); + assertThat(stagingEligibilityClient) + .isInstanceOf(AccountPreseededActorStagingEligibilityClient.class); + assertThat(ownerReadClient) + .isInstanceOf(GameSessionPreseededActorAssignmentOwnerReadClient.class); + assertThat(accountIdentityPort).isNotNull(); + assertThat(stagingEligibilityPort).isNotNull(); + assertThat(ownerEvidencePort) + .isInstanceOf(GameSessionPreseededActorAssignmentOwnerEvidenceAdapter.class); + verifyNoInteractions(channels); } - private static ApplicationContextRunner runner() { - return new ApplicationContextRunner() - .withUserConfiguration(PreseededActorAssignmentConfiguration.class) - .withPropertyValues("firemud.grpc.workload-namespace=gameplay") - .withBean(CharacterRepository.class, () -> mock(CharacterRepository.class)); + private static PreseededActorAssignmentRequest request() { + return new PreseededActorAssignmentRequest( + UUID.randomUUID(), + UUID.randomUUID(), + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Sora"), + new PreseededActorAssignmentExpectedTarget( + UUID.randomUUID(), + UUID.randomUUID(), + "world", + "realm", + UUID.randomUUID().toString(), + 3L, + UUID.randomUUID(), + "1".repeat(64), + UUID.randomUUID(), + "release/test", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); } - private static GameSessionPreseededActorAssignmentOwnerReadClient client() { + private static CommonGrpcClientProperties tlsProperties() { CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); tls.setCertChain("entity-client.crt"); tls.setPrivateKey("entity-client.key"); - tls.setCaCert("game-session-ca.crt"); - return new GameSessionPreseededActorAssignmentOwnerReadClient( - new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "gameplay"); + tls.setCaCert("owner-service-ca.crt"); + return tls; } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java index d01f2c511e..b147981d4f 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java @@ -112,7 +112,7 @@ void selectedAssignmentMethodUsesTheSameNamespaceAndEndUserContextGuard() { } @Test - void applicationYamlBypassesJwtForOnlyTheTwoExactRosterMethods() { + void applicationYamlKeepsRosterMethodsOutsideJwtBypassAllowlist() { var yaml = new YamlPropertiesFactoryBean(); yaml.setResources(new FileSystemResource("src/main/resources/application.yml")); Properties properties = yaml.getObject(); @@ -126,12 +126,9 @@ void applicationYamlBypassesJwtForOnlyTheTwoExactRosterMethods() { .map(index -> properties.getProperty("firemud.auth.grpc.public-methods[" + index + "]")) .toList(); - assertThat( - publicMethods.stream() - .filter( - method -> - method.startsWith("entity_management.v1.CanonicalGameplayRosterService/"))) - .containsExactly( + assertThat(publicMethods) + .containsExactly("entity_management.v1.EntityManagementService/Ping") + .doesNotContain( CanonicalGameplayRosterPeerInterceptor.METHOD_NAME, CanonicalGameplayRosterPeerInterceptor.SELECTED_ASSIGNMENT_METHOD_NAME); assertThat(publicMethods).noneMatch(method -> method.contains("*")); From 9508de4091569e8f48086a95c2273111b398cb67 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:33:58 +1300 Subject: [PATCH 06/61] Prepare unregistered selected publication reservation from exact owner readbacks --- ...ame-authoring-publishing-and-activation.md | 4 + ...ectedDraftPublicationAdmissionService.java | 339 +++++++++ ...dDraftPublicationAdmissionServiceTest.java | 675 ++++++++++++++++++ 3 files changed, 1018 insertions(+) create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index ac6fd0e46f..7a1036699c 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +### Selected publication reservation preparation + +A separate unregistered reservation adapter is being reconciled from the remaining carrier. It independently reads the retained selection, exact Account HELD evidence, World freeze/inventory/selector and original World source/delivery before the existing local reservation transaction. Current client types and binding guards remain authoritative. Focused proof is pending. This preparation does not supply through-commit Account protection, failed-selection recovery, a reachable publication finalizer or a production entrypoint; fresh/PENDING publication and runtime authority remain denied. + ### Selected-full owner publication preparation The source candidate prepares complete selected-owner publication consumption under the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile). It reuses the actual parent World closure producer, adds its full-profile consumer mapping, and composes the selected Game Design digest read/collector with independently retained Entity, Automation and Game Logic receipts. The Game Logic adapter reads the exact retained terminal, selected source and manifest through the existing owner repository and returns both manifest and ability projections; its default Spring composition remains denied. Private selected writer mechanics use the exact canonical selection/request binding and selected gate. Public Game Design fresh/PENDING publication remains denied. Existing Game Design V1020 storage is reused; no Game Design migration is added. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java new file mode 100644 index 0000000000..042d2ccc78 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java @@ -0,0 +1,339 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Game Design admission boundary for one exact selected-Draft publication. Account + * authorization, World freeze and selector capture finish before the local reservation transaction. + */ +public final class SelectedDraftPublicationAdmissionService { + private final AccountPublicationAuthorizationReadClient accountClient; + private final WorldPublishedStartLocationClient worldClient; + private final WorldSelectedDraftPublicationFreezeClient freezeClient; + private final WorldSelectedPublicationArtifactInventoryClient inventoryClient; + private final SelectionReader selectionReader; + private final SelectedDraftPublicationOwner owner; + private final WorldAuthoredSourceIntakeClient worldSourceIntakeClient; + private final GameAuthoredWorldSourceRepository worldSourceRepository; + private final GameAuthoredWorldSourceDeliveryRepository worldSourceDeliveryRepository; + private final TransactionTemplate reservationTransaction; + private final String workloadNamespace; + + public SelectedDraftPublicationAdmissionService( + DSLContext dsl, + PlatformTransactionManager transactionManager, + AccountPublicationAuthorizationReadClient accountClient, + WorldSelectedDraftPublicationFreezeClient freezeClient, + WorldSelectedPublicationArtifactInventoryClient inventoryClient, + WorldPublishedStartLocationClient worldClient, + WorldAuthoredSourceIntakeClient worldSourceIntakeClient, + String workloadNamespace) { + this( + transactionManager, + accountClient, + freezeClient, + inventoryClient, + worldClient, + worldSourceIntakeClient, + new GameAuthoredWorldSourceRepository(Objects.requireNonNull(dsl, "dsl")), + new GameAuthoredWorldSourceDeliveryRepository(dsl), + new SelectedDraftPublicationOwner(Objects.requireNonNull(dsl, "dsl")), + intent -> + new AuthoredDraftPublishSelectionRepository( + dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId()) + .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection), + workloadNamespace); + } + + SelectedDraftPublicationAdmissionService( + PlatformTransactionManager transactionManager, + AccountPublicationAuthorizationReadClient accountClient, + WorldSelectedDraftPublicationFreezeClient freezeClient, + WorldSelectedPublicationArtifactInventoryClient inventoryClient, + WorldPublishedStartLocationClient worldClient, + WorldAuthoredSourceIntakeClient worldSourceIntakeClient, + GameAuthoredWorldSourceRepository worldSourceRepository, + GameAuthoredWorldSourceDeliveryRepository worldSourceDeliveryRepository, + SelectedDraftPublicationOwner owner, + SelectionReader selectionReader, + String workloadNamespace) { + this.accountClient = Objects.requireNonNull(accountClient, "accountClient"); + this.worldClient = Objects.requireNonNull(worldClient, "worldClient"); + this.freezeClient = Objects.requireNonNull(freezeClient, "freezeClient"); + this.inventoryClient = Objects.requireNonNull(inventoryClient, "inventoryClient"); + this.worldSourceIntakeClient = + Objects.requireNonNull(worldSourceIntakeClient, "worldSourceIntakeClient"); + this.worldSourceRepository = + Objects.requireNonNull(worldSourceRepository, "worldSourceRepository"); + this.worldSourceDeliveryRepository = + Objects.requireNonNull(worldSourceDeliveryRepository, "worldSourceDeliveryRepository"); + this.selectionReader = Objects.requireNonNull(selectionReader, "selectionReader"); + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.reservationTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + this.reservationTransaction.setName("selected-draft-publication-reservation"); + this.reservationTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + this.reservationTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.reservationTransaction.setReadOnly(false); + } + + /** + * Verifies the retained selection, authenticates Account HELD, freezes World, and reads the exact + * selector and complete source receipt before reserving locally. All owner reads complete outside + * SQL. + */ + public SelectedDraftPublicationOwner.Reservation admitAndReserve( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding) { + requireNoAmbientTransaction(); + Objects.requireNonNull(intent, "intent"); + Objects.requireNonNull(accountBinding, "accountBinding"); + AuthoredDraftPublishSelection selection = + selectionReader + .read(intent) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")); + requireRequestIdentity(intent, accountBinding, selection); + + AccountPublicationAuthorizationReadEvidence.Request accountReadRequest = + AccountPublicationAuthorizationReadEvidence.Request.create( + workloadNamespace, accountBinding); + AccountPublicationAuthorizationReadEvidence accountEvidence = + accountClient.read(accountReadRequest); + requireExactAccountReadback(accountReadRequest, accountBinding, accountEvidence); + + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + workloadNamespace, + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + selection.digest().substring("sha256:".length()), + accountEvidence.request().binding()); + var freeze = freezeClient.begin(freezeRequest); + if (freeze == null + || !freezeRequest.equals(freeze.request()) + || !freezeRequest.equals(freeze.acknowledgement().request())) { + throw new IllegalStateException( + "World publication freeze readback differs from the exact request"); + } + var acknowledgement = freeze.acknowledgement(); + var inventory = inventoryClient.read(freeze); + if (inventory == null + || !freeze.request().equals(inventory.freezeEvidence().request()) + || !freeze.acknowledgement().equals(inventory.freezeEvidence().acknowledgement())) { + throw new IllegalStateException( + "World inventory readback differs from exact acknowledged freeze"); + } + var worldRequest = + new WorldPublishedStartLocationEvidence.Request( + workloadNamespace, + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + acknowledgement.intakeRequestId(), + acknowledgement.publicationFence(), + intent.publishRequestId(), + freezeRequest.requestDigest(), + acknowledgement.versionStateEpoch(), + PublicationDigestRequestBinding.full( + intent.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity(), + acknowledgement.appliedCommitId(), + acknowledgement.contentDigest(), + acknowledgement.digestSchemaVersion(), + selection + .selectedCommit() + .affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT) + .stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList()); + WorldPublishedStartLocationEvidence worldEvidence = worldClient.read(worldRequest); + requireExactWorldReadback(worldRequest, worldEvidence); + new GameDesignPublicationOperationBinding( + accountEvidence.request().binding(), worldEvidence, inventory); + SelectedDraftTemplateWorldSourceAssociation.SourceRead worldSourceRead = + readAndVerifyWorldSource(worldEvidence, selection.target()); + + return Objects.requireNonNull( + reservationTransaction.execute( + status -> + owner.reserve( + intent, + accountEvidence.request().binding(), + worldEvidence, + inventory, + worldSourceRead)), + "Selected Draft publication reservation returned no result"); + } + + private SelectedDraftTemplateWorldSourceAssociation.SourceRead readAndVerifyWorldSource( + WorldPublishedStartLocationEvidence worldEvidence, + DraftCommitBinding.TargetProof selectedTarget) { + var selected = worldEvidence.request(); + java.util.UUID readRequestId = java.util.UUID.randomUUID(); + while (readRequestId.equals(selected.intakeRequestId())) { + readRequestId = java.util.UUID.randomUUID(); + } + var request = + new ByIdReadRequest( + 1, + selected.targetNamespace(), + readRequestId, + selected.intakeRequestId(), + selected.canonicalTenantId()); + var receipt = worldSourceIntakeClient.readById(request); + var worldRead = new SelectedDraftTemplateWorldSourceAssociation.SourceRead(request, receipt); + var source = + worldSourceRepository + .read( + receipt.sourceOperationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + selected.targetNamespace()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_WORLD_SOURCE_GD_RECORD_UNAVAILABLE")); + var delivery = + worldSourceDeliveryRepository + .read(receipt.sourceOperationId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_WORLD_SOURCE_DELIVERY_UNAVAILABLE")); + var expectedReceipt = + new CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest()); + if (!source.equals(receipt.source()) + || !delivery.source().equals(source) + || !delivery.request().targetNamespace().equals(selected.targetNamespace()) + || !delivery.request().intakeRequestId().equals(selected.intakeRequestId()) + || !delivery.request().canonicalTenantId().equals(selected.canonicalTenantId()) + || !delivery.request().worldSlug().equals(receipt.worldSlug()) + || !delivery.request().sourceOperationId().equals(receipt.sourceOperationId()) + || !delivery.request().expectedSourceEvidenceDigest().equals(receipt.sourceEvidenceDigest()) + || source.sourceGameRowId() != selectedTarget.sourceGameRowId() + || !source.sourceGameTenantKey().equals(selectedTarget.sourceGameTenantKey()) + || !source.provenanceKind().equals(selectedTarget.sourceProvenanceKind()) + || !WorldAuthoredSourceIntakeGrpcCodec.requestDigest(delivery.request()) + .equals(receipt.requestDigest()) + || delivery.acknowledgedReceipt().filter(ack -> !ack.equals(expectedReceipt)).isPresent()) { + throw new IllegalStateException( + "SELECTED_WORLD_SOURCE_OWNER_READBACK_CONFLICT: World, retained source, and original delivery differ"); + } + return worldRead; + } + + private void requireRequestIdentity( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding, + AuthoredDraftPublishSelection selection) { + var intentFromBinding = accountBinding.input().selection().intent(); + var expectedIntent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + if (!expectedIntent.equals(intentFromBinding) + || !intent.equals(selection.intent()) + || !Arrays.equals( + selection.canonicalBytes(), accountBinding.input().selection().canonicalBytes())) { + throw new IllegalArgumentException( + "Account publication binding and retained selection must match the exact selected Draft intent"); + } + } + + @FunctionalInterface + interface SelectionReader { + Optional read( + AuthoredDraftPublishSelection.PublishIntent intent); + } + + private static void requireExactAccountReadback( + AccountPublicationAuthorizationReadEvidence.Request expectedRequest, + AccountPublicationAuthorizationBinding expectedBinding, + AccountPublicationAuthorizationReadEvidence evidence) { + if (evidence == null + || !expectedRequest.equals(evidence.request()) + || !java.util.Arrays.equals( + expectedBinding.canonicalBytes(), evidence.request().binding().canonicalBytes())) { + throw new IllegalStateException( + "Account publication authorization readback differs from the exact request"); + } + } + + private static void requireExactWorldReadback( + WorldPublishedStartLocationEvidence.Request expectedRequest, + WorldPublishedStartLocationEvidence evidence) { + if (evidence == null || !expectedRequest.equals(evidence.request())) { + throw new IllegalStateException( + "World publication selector readback differs from the exact request"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Selected Draft publication owner reads require no ambient transaction"); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java new file mode 100644 index 0000000000..588133d367 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java @@ -0,0 +1,675 @@ +package net.firedevops.firemud.gamedesign.publication; + +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.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.inOrder; +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 io.grpc.Status; +import java.util.Arrays; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unit proof for the admission ordering and exact preflight checks; clients are transport doubles. + */ +class SelectedDraftPublicationAdmissionServiceTest { + private static final String NAMESPACE = "test"; + + @Test + void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = freezeClient(fixture); + var inventory = inventoryClient(fixture); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var sourceFixture = sourceFixture(fixture.worldRequest()); + when(sourceIntake.readById(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return sourceReceipt(invocation.getArgument(0), sourceFixture); + }); + when(sourceRepository.read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(sourceFixture.source())); + when(deliveryRepository.read(sourceFixture.source().operationId())) + .thenReturn( + Optional.of( + new GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim( + sourceFixture.source(), sourceFixture.intakeRequest(), Optional.empty()))); + var owner = mock(SelectedDraftPublicationOwner.class); + var reader = mock(SelectedDraftPublicationAdmissionService.SelectionReader.class); + var transactions = mock(PlatformTransactionManager.class); + var retained = + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest()); + when(reader.read(fixture.intent())).thenReturn(Optional.of(retained)); + when(account.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + when(world.read(fixture.worldRequest())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return fixture.operation().world(); + }); + var reservation = mock(SelectedDraftPublicationOwner.Reservation.class); + // Request.binding() reconstructs the exact Account bytes; its nested selection does not use + // value equality. Match the complete canonical binding rather than decoded object identity. + when(owner.reserve( + eq(fixture.intent()), + argThat( + binding -> + Arrays.equals( + binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), + same(fixture.operation().world()), + same(fixture.operation().inventory()), + any())) + .thenReturn(reservation); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + reader, + NAMESPACE); + + assertThat(service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(reservation); + var order = + inOrder( + reader, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + transactions, + owner); + order.verify(reader).read(fixture.intent()); + order.verify(account).read(any()); + order.verify(freeze).begin(any()); + order.verify(inventory).read(any()); + order.verify(world).read(fixture.worldRequest()); + order + .verify(sourceIntake) + .readById( + argThat( + request -> + request.schemaVersion() == 1 + && request.targetNamespace().equals(NAMESPACE) + && request + .intakeRequestId() + .equals(fixture.worldRequest().intakeRequestId()) + && request + .canonicalTenantId() + .equals(fixture.worldRequest().canonicalTenantId()) + && !request.readRequestId().equals(request.intakeRequestId()))); + order + .verify(sourceRepository) + .read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE); + order.verify(deliveryRepository).read(sourceFixture.source().operationId()); + order.verify(transactions).getTransaction(any()); + order + .verify(owner) + .reserve( + eq(fixture.intent()), + argThat( + binding -> + Arrays.equals( + binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), + same(fixture.operation().world()), + same(fixture.operation().inventory()), + any()); + } + + @Test + void missingRetainedSelectionNeverReadsAccountFreezesWorldOrOpensSql() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> Optional.empty(), + NAMESPACE); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SELECTION_UNAVAILABLE"); + verifyNoInteractions( + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + transactions); + } + + @Test + void mismatchedRetainedDeliveryAcknowledgementDeniesBeforeReservation() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var sourceFixture = sourceFixture(fixture.worldRequest()); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + when(sourceIntake.readById(any())) + .thenAnswer(invocation -> sourceReceipt(invocation.getArgument(0), sourceFixture)); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + when(sourceRepository.read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(sourceFixture.source())); + var receipt = + sourceReceipt( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + NAMESPACE, + UUID.randomUUID(), + fixture.worldRequest().intakeRequestId(), + fixture.worldRequest().canonicalTenantId()), + sourceFixture); + var wrongAcknowledgement = + new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + "sha256:" + "b".repeat(64)); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + when(deliveryRepository.read(sourceFixture.source().operationId())) + .thenReturn( + Optional.of( + new GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim( + sourceFixture.source(), + sourceFixture.intakeRequest(), + Optional.of(wrongAcknowledgement)))); + var world = mock(WorldPublishedStartLocationClient.class); + when(world.read(fixture.worldRequest())).thenReturn(fixture.operation().world()); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freezeClient(fixture), + inventoryClient(fixture), + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest())), + NAMESPACE); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("OWNER_READBACK_CONFLICT"); + verifyNoInteractions(transactions, owner); + } + + @Test + void freezeFailureNeverReadsSelectorOrReserves() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var selection = fixture.operation().account().input().selection(); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + selection.canonicalJson(), selection.digest())), + NAMESPACE); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var failure = Status.UNAVAILABLE.asRuntimeException(); + when(freeze.begin(any())).thenThrow(failure); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(failure); + verifyNoInteractions(inventory, world, owner, transactions); + } + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void missingInventoryAfterAcknowledgedFreezeNeverReadsSelectorOrOpensSql() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var selection = fixture.operation().account().input().selection(); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freezeClient(fixture), + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + selection.canonicalJson(), selection.digest())), + NAMESPACE); + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("inventory readback"); + verify(inventory).read(any()); + verifyNoInteractions( + world, sourceIntake, sourceRepository, deliveryRepository, owner, transactions); + } + + @Test + void rejectsAmbientSqlTransactionBeforeEitherOwnerRead() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void rejectsAmbientSynchronizationBeforeEitherOwnerRead() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void rejectsChangedIntentBeforeOwnerReads() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + var original = fixture.intent(); + var changedIntent = + new AuthoredDraftPublishSelection.PublishIntent( + original.canonicalTenantId(), + original.canonicalVersionId(), + original.publishRequestId(), + original.expectedVersionStateEpoch(), + "changed notes", + original.selectedCommitRequestId(), + original.selectedCommitId(), + original.selectedCommitDigest()); + + assertThatThrownBy(() -> service.admitAndReserve(changedIntent, fixture.operation().account())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected Draft intent"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void accountDenialOrUnavailableReadNeverReadsWorldOrReserves() throws Exception { + for (Status.Code code : + new Status.Code[] {Status.Code.PERMISSION_DENIED, Status.Code.UNAVAILABLE}) { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var service = service(fixture, accountClient, worldClient, owner); + var failure = Status.fromCode(code).asRuntimeException(); + when(accountClient.read(any())).thenThrow(failure); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(failure); + + verify(accountClient).read(any()); + verifyNoInteractions(worldClient, owner); + } + } + + @Test + void worldUnavailableAfterAccountReadNeverOpensReservation() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var service = service(fixture, accountClient, worldClient, owner); + + // The client is a transport double here; the mock evidence is never accepted as proof because + // the World read fails before the reservation boundary. + when(accountClient.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var failure = Status.UNAVAILABLE.asRuntimeException(); + when(worldClient.read(fixture.worldRequest())).thenThrow(failure); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(failure); + + verify(accountClient).read(any()); + verify(worldClient).read(fixture.worldRequest()); + verifyNoInteractions(owner); + } + + private static SelectedDraftPublicationAdmissionService service( + Fixture fixture, + AccountPublicationAuthorizationReadClient accountClient, + WorldPublishedStartLocationClient worldClient, + SelectedDraftPublicationOwner owner) { + return new SelectedDraftPublicationAdmissionService( + mock(PlatformTransactionManager.class), + accountClient, + freezeClient(fixture), + inventoryClient(fixture), + worldClient, + mock(WorldAuthoredSourceIntakeClient.class), + mock(GameAuthoredWorldSourceRepository.class), + mock(GameAuthoredWorldSourceDeliveryRepository.class), + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest())), + NAMESPACE); + } + + private static WorldSelectedPublicationArtifactInventoryClient inventoryClient(Fixture fixture) { + var client = mock(WorldSelectedPublicationArtifactInventoryClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return fixture.operation().inventory(); + }); + return client; + } + + private static WorldSelectedDraftPublicationFreezeClient freezeClient(Fixture fixture) { + var client = mock(WorldSelectedDraftPublicationFreezeClient.class); + when(client.begin(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + WorldSelectedDraftPublicationFreezeEvidence.Request request = + invocation.getArgument(0); + var world = fixture.worldRequest(); + var acknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + request, + world.intakeRequestId(), + world.versionStateEpoch(), + world.publicationFence(), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + world.appliedCommitId(), + world.contentDigest(), + world.digestSchemaVersion()); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + }); + return client; + } + + private static SourceFixture sourceFixture(WorldPublishedStartLocationEvidence.Request selected) { + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "fixture-tenant"; + String worldSlug = "fixture-world"; + String worldDisplayName = "Fixture World"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + selected.targetNamespace(), + registrationRequestId, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + var source = + new AuthoredWorldSourceEvidence( + 1, + selected.targetNamespace(), + registrationRequestId, + sourceOperationId, + requestDigest, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + "tenant-key", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + selected.targetNamespace(), + registrationRequestId, + sourceOperationId, + requestDigest, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + "tenant-key", + "NEW_GAME_ROW")); + var intakeRequest = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + selected.targetNamespace(), + selected.intakeRequestId(), + selected.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + return new SourceFixture(source, intakeRequest); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt sourceReceipt( + WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest request, SourceFixture fixture) { + var source = fixture.source(); + return new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + request.targetNamespace(), + request.intakeRequestId(), + UUID.nameUUIDFromBytes( + "synthetic-world-operation".getBytes(java.nio.charset.StandardCharsets.UTF_8)), + request.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(fixture.intakeRequest()), + "sha256:" + "a".repeat(64), + source); + } + + private static Fixture fixture() throws Exception { + var target = + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + var original = IsolatedPublicationOperationFixtures.fresh(target); + var selectionIntent = original.account().input().selection().intent(); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + selectionIntent.canonicalTenantId(), + selectionIntent.canonicalVersionId(), + selectionIntent.publishRequestId(), + selectionIntent.expectedVersionStateEpoch(), + selectionIntent.notes(), + selectionIntent.selectedCommitRequestId(), + selectionIntent.selectedCommitId(), + selectionIntent.selectedCommitDigest()); + return new Fixture(original, intent, original.world().request()); + } + + private record Fixture( + GameDesignPublicationOperation operation, + AuthoredDraftPublishSelection.PublishIntent intent, + WorldPublishedStartLocationEvidence.Request worldRequest) {} + + private record SourceFixture( + AuthoredWorldSourceEvidence source, + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest intakeRequest) {} +} From af89e4e1363d5f95f25aa69545e2cda15f0c5454 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:43:14 +1300 Subject: [PATCH 07/61] Prepare actual Account selected-publication producer and terminal owner closure --- ...ame-authoring-publishing-and-activation.md | 2 +- .../player-access-and-session.md | 5 + .../selected_publication_order_service.proto | 30 + ...blicationAuthorizationReadGrpcService.java | 78 + ...ntPublicationAuthorizationReadService.java | 85 ++ ...untPublicationAuthorizationRepository.java | 332 +++++ ...ccountPublicationAuthorizationService.java | 50 + ...ectedDraftPublicationOrderGrpcService.java | 152 ++ ...tSelectedDraftPublicationOrderService.java | 88 ++ ...ctedDraftPublicationSettlementService.java | 138 ++ ...horizationMtlsPostgresIntegrationTest.java | 1055 +++++++++++++ ...nAuthorizationPostgresIntegrationTest.java | 1327 +++++++++++++++++ ...blicationAuthorizationReadServiceTest.java | 246 +++ ...ntPublicationAuthorizationServiceTest.java | 43 + ...ctedDraftPublicationOrderGrpcMtlsTest.java | 578 +++++++ ...dDraftPublicationOrderGrpcServiceTest.java | 305 ++++ ...ectedDraftPublicationOrderServiceTest.java | 292 ++++ ...DraftPublicationSettlementServiceTest.java | 377 +++++ ...AccountSelectedPublicationOrderClient.java | 137 ++ ...ntSelectedPublicationOrderCredentials.java | 113 ++ ...ountSelectedPublicationOrderGrpcCodec.java | 152 ++ ...untSelectedPublicationOrderClientTest.java | 158 ++ ...lectedPublicationOrderCredentialsTest.java | 99 ++ ...SelectedPublicationOrderGrpcCodecTest.java | 112 ++ ...ectedDraftPublicationAdmissionService.java | 2 +- ...dDraftPublicationAdmissionServiceTest.java | 2 +- 26 files changed, 5955 insertions(+), 3 deletions(-) create mode 100644 protos/account/v1/selected_publication_order_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 7a1036699c..e1cb4ad0ef 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ### Selected publication reservation preparation -A separate unregistered reservation adapter is being reconciled from the remaining carrier. It independently reads the retained selection, exact Account HELD evidence, World freeze/inventory/selector and original World source/delivery before the existing local reservation transaction. Current client types and binding guards remain authoritative. Focused proof is pending. This preparation does not supply through-commit Account protection, failed-selection recovery, a reachable publication finalizer or a production entrypoint; fresh/PENDING publication and runtime authority remain denied. +An unregistered reservation adapter independently reads the retained selection, exact Account HELD evidence, World freeze/inventory/selector and original World source/delivery before the existing local reservation transaction. Its ten focused ordering/refusal units and GDS static/format/docs pass; remote inputs remain transport doubles, not physical authenticated admission. The coherent continuation includes the missing Account selected-publication producer, HELD read, typed order transport and exact terminal-settlement owner over existing V93 storage; current-contract reconciliation and their focused/native proof remain pending. No migration or parallel terminal codec is introduced. Current client types and binding guards remain authoritative. This does not supply through-commit Account protection, failed-selection recovery, a reachable publication finalizer or a production entrypoint; fresh/PENDING publication and runtime authority remain denied. ### Selected-full owner publication preparation 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 51c15d655a..43ceb1b2ee 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,11 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Selected publication owner preparation + +The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. Source/currentness, caller, retention and focused physical proof remain pending. These owners remain unregistered and grant no publication finalizer, player admission or runtime authority. + + ### Selected recipient source intake preparation R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. R35 freshly passes the successor disclosure composition at the actual V1008–V1010 repository frontier, including physical source-writer exclusion until exact reservation abort; its static, formatting and documentation checks pass. The earlier V1007-only source proof retains separate R33 attribution. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority. diff --git a/protos/account/v1/selected_publication_order_service.proto b/protos/account/v1/selected_publication_order_service.proto new file mode 100644 index 0000000000..a23b205803 --- /dev/null +++ b/protos/account/v1/selected_publication_order_service.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered Game Design-only producer. No environment authority is caller supplied. +service AccountSelectedPublicationOrderService { + rpc AuthorizeSelectedPublication(AuthorizeSelectedPublicationRequest) + returns (AuthorizeSelectedPublicationResponse); +} + +message AuthorizeSelectedPublicationRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Transport correlation only; the selected publication request owns durable identity. + string request_id = 3; + bytes original_selection = 4; + // The original creator credential travels only in protected per-call metadata. + reserved 5; + reserved "original_creator_credential"; +} + +message AuthorizeSelectedPublicationResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + bytes original_selection = 4; + bytes publication_authorization_binding = 5; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java new file mode 100644 index 0000000000..3bedfb6d7e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountPublicationAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadGrpcCodec; + +/** Standalone endpoint only: peer authentication precedes decoding and persistence lookup. */ +public final class AccountPublicationAuthorizationReadGrpcService + extends AccountPublicationAuthorizationReadServiceGrpc + .AccountPublicationAuthorizationReadServiceImplBase { + private final AccountPublicationAuthorizationReadService owner; + private final String trustedNamespace; + + public AccountPublicationAuthorizationReadGrpcService( + AccountPublicationAuthorizationReadService owner, String trustedNamespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest request, + StreamObserver observer) { + try { + AccountPublicationAuthorizationReadService.requirePeer(trustedNamespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence + .Request + decoded; + try { + decoded = AccountPublicationAuthorizationReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical Account publication read required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Account publication namespace differs from peer") + .asRuntimeException()); + return; + } + final ReadHeldPublicationAuthorizationResponse response; + try { + owner.requireHeld(decoded); + response = AccountPublicationAuthorizationReadGrpcCodec.toHeldResponse(decoded); + } catch (StatusRuntimeException failure) { + observer.onError( + Status.fromCode(Status.fromThrowable(failure).getCode()) + .withDescription("Account publication authorization owner read denied or unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Account publication owner read unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java new file mode 100644 index 0000000000..aabbb848e7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered owner read of a distinct retained publication order; never a terminal result. */ +public final class AccountPublicationAuthorizationReadService { + private final AccountPublicationAuthorizationRepository repository; + private final String trustedNamespace; + private final TransactionTemplate ownerTransaction; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner persistence collaborator.") + public AccountPublicationAuthorizationReadService( + AccountPublicationAuthorizationRepository repository, + PlatformTransactionManager transactions, + String trustedNamespace) { + this.repository = Objects.requireNonNull(repository); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + public void requireHeld(AccountPublicationAuthorizationReadEvidence.Request request) { + requirePeer(trustedNamespace); + Objects.requireNonNull(request); + if (!trustedNamespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("Account publication namespace differs from peer") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent Account publication owner transaction required") + .asRuntimeException(); + } + try { + ownerTransaction.execute( + status -> { + repository.readHeld(request.binding()); + return null; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (IllegalArgumentException inconsistent) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact held Account publication authorization unavailable") + .asRuntimeException(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Account publication owner read unavailable") + .asRuntimeException(); + } + } + + static void requirePeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + String peerUri = peer.uri(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peerUri) + && !("spiffe://firemud/ns/" + namespace + "/sa/world-management-service").equals(peerUri)) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design or World Management workload required") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java new file mode 100644 index 0000000000..ec61455a67 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java @@ -0,0 +1,332 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal owner-transaction storage; remote evidence must first be authenticated by composition. + */ +public final class AccountPublicationAuthorizationRepository { + private final DSLContext dsl; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner persistence collaborator.") + public AccountPublicationAuthorizationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + AccountPublicationAuthorizationBinding authorize( + AccountPublicationAuthorizationBinding.PreallocationInput input, + AccountControlUiActorService.Current current, + Runnable admission) { + requireTransaction(); + Record prior = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations" + + " WHERE tenant_uuid = ? AND publish_request_id = ? FOR UPDATE", + current.stored().tenantId, + input.selection().intent().publishRequestId()); + if (prior != null) { + var original = + AccountPublicationAuthorizationBinding.fromStored(prior.get("binding", byte[].class)); + requireExact(prior, original, input, current); + return original; + } + admission.run(); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, current.source().sources()); + dsl.execute( + "INSERT INTO account_selected_publication_authorizations" + + " (operation_id, fence_id, actor_account_uuid, tenant_uuid, publish_request_id," + + " input_digest, binding, issuance_operation_id, issuance_fence," + + " source_payload, issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + input.actorAccountId(), + binding.tenantId(), + binding.publishRequestId(), + input.digest(), + binding.canonicalBytes(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints())); + for (var source : binding.sources()) { + dsl.execute( + "INSERT INTO account_selected_publication_sources" + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + source.key(), + source.canonicalBytes()); + } + Record retained = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations WHERE operation_id = ? FOR UPDATE", + binding.operationId()); + requireExact(retained, binding, input, current); + return binding; + } + + /** Exact owner read; caller-carried structure alone can never establish HELD. */ + public void readHeld(AccountPublicationAuthorizationBinding requested) { + readOriginal(requested); + if (dsl.fetchOne( + "SELECT 1 FROM account_selected_publication_settlements WHERE operation_id = ?", + requested.operationId()) + != null) { + throw new IllegalArgumentException("Publication authorization is already settled"); + } + } + + /** Historical validation uses the original committed issuance, never current credentials. */ + private void readOriginal(AccountPublicationAuthorizationBinding requested) { + requireTransaction(); + Objects.requireNonNull(requested); + // Sources precede the operation. No transport is permitted in this owner transaction. + for (var source : + requested.sources().stream() + .sorted( + java.util.Comparator.comparing(DraftAuthorizationFenceBinding.SourceEvidence::key)) + .toList()) { + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks" + + " WHERE source_key = ? FOR UPDATE", + source.key()) + == null) { + throw new IllegalArgumentException("Original publication source lock is absent"); + } + } + Record row = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations" + + " WHERE operation_id = ? FOR UPDATE", + requested.operationId()); + if (row == null + || !Arrays.equals(requested.canonicalBytes(), row.get("binding", byte[].class))) { + throw new IllegalArgumentException("Exact held publication authorization is absent"); + } + var retained = + AccountPublicationAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + validateRetainedWorldIfPresent(row, retained); + // Issuance producers acquire this row before source capture. Do not wait backwards while + // holding sources; a concurrent issuer/source writer must cause a retry, never a lock cycle. + Record issuance = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations" + + " WHERE operation_id = ? FOR UPDATE NOWAIT", + row.get("issuance_operation_id", UUID.class)); + if (issuance == null) { + throw new IllegalArgumentException("Original committed issuance is absent"); + } + var originalIssuer = new AccountControlUiIssuanceRepository.Stored(issuance); + var bundle = AccountControlUiIssuanceRepository.object(originalIssuer.bundle); + var sources = AccountControlUiIssuanceRepository.object(originalIssuer.sources); + var rawVector = sources.get("sources"); + if (!"COMMITTED".equals(originalIssuer.status) + || !retained.operationId().equals(row.get("operation_id", UUID.class)) + || !retained.fenceId().equals(row.get("fence_id", UUID.class)) + || !retained.input().actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !retained.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !retained.publishRequestId().equals(row.get("publish_request_id", String.class)) + || !retained.input().digest().equals(row.get("input_digest", String.class)) + || !retained.input().actorAccountId().equals(originalIssuer.accountId) + || !retained.tenantId().equals(originalIssuer.tenantId) + || !originalIssuer.operationId.equals(row.get("issuance_operation_id", UUID.class)) + || !Arrays.equals(originalIssuer.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(originalIssuer.bundle, row.get("issuance_bundle", byte[].class)) + || !(bundle.get("issuanceFence") instanceof Number fence) + || fence.longValue() != row.get("issuance_fence", Long.class) + || !Arrays.equals( + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + bundle.get("outboxCheckpoints")), + row.get("outbox_checkpoints", byte[].class)) + || !originalIssuer.accountId.toString().equals(sources.get("accountId")) + || !originalIssuer.tenantId.toString().equals(sources.get("tenantId")) + || !(rawVector instanceof java.util.List vector) + || vector.size() != retained.sources().size()) { + throw new IllegalArgumentException("Changed original publication issuance evidence"); + } + var participation = + dsl + .fetch( + "SELECT source_key, source_evidence FROM account_selected_publication_sources" + + " WHERE operation_id = ?", + retained.operationId()) + .stream() + .sorted(java.util.Comparator.comparing(r -> r.get("source_key", String.class))) + .toList(); + if (participation.size() != retained.sources().size()) { + throw new IllegalArgumentException("Incomplete original publication source participation"); + } + for (int i = 0; i < retained.sources().size(); i++) { + var source = retained.sources().get(i); + if (!(vector.get(i) instanceof String encoded) + || !Arrays.equals(source.canonicalBytes(), java.util.Base64.getDecoder().decode(encoded)) + || !source.key().equals(participation.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), participation.get(i).get("source_evidence", byte[].class))) { + throw new IllegalArgumentException("Changed original publication source participation"); + } + } + } + + /** + * Persist only after strict authenticated reads from both owners, outside this transaction. + * Structure alone is not owner authentication. World retains the same complete terminal bytes + * with PUBLISHED or ABORTED phase. Transport request IDs deliberately do not enter identity. + */ + public byte[] settle( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence gameDesign, + String worldOutcome, + byte[] worldTerminalEvidence) { + requireTransaction(); + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(gameDesign, "gameDesign"); + var world = GameDesignPublicationTerminalEvidence.fromStored(worldTerminalEvidence); + String expectedPhase = + gameDesign.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + if (!expectedPhase.equals(worldOutcome) + || !Arrays.equals(operation.canonicalBytes(), gameDesign.operationBytes()) + || !Arrays.equals(gameDesign.canonicalBytes(), world.canonicalBytes())) { + throw new IllegalArgumentException("Exact publication owner outcomes disagree"); + } + readOriginal(operation.account()); + byte[] receipt = settlementReceipt(operation, gameDesign, worldOutcome, worldTerminalEvidence); + Record prior = + dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + operation.account().operationId()); + if (prior != null) { + if (!Arrays.equals(receipt, prior.get("receipt", byte[].class))) { + throw new IllegalArgumentException("Changed original publication settlement"); + } + return prior.get("receipt", byte[].class); + } + dsl.execute( + "INSERT INTO account_selected_publication_settlements" + + " (operation_id, fence_id, account_binding, publication_operation," + + " game_design_outcome, game_design_terminal, world_outcome, world_terminal, receipt)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + operation.account().operationId(), + operation.account().fenceId(), + operation.account().canonicalBytes(), + operation.canonicalBytes(), + gameDesign.outcome().name(), + gameDesign.canonicalBytes(), + worldOutcome, + worldTerminalEvidence, + receipt); + Record retained = + dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + operation.account().operationId()); + if (retained == null || !Arrays.equals(receipt, retained.get("receipt", byte[].class))) { + throw new IllegalStateException("Exact publication settlement readback is absent"); + } + return retained.get("receipt", byte[].class); + } + + private static byte[] settlementReceipt( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence gameDesign, + String worldOutcome, + byte[] worldTerminalEvidence) { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, gameDesign.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, worldOutcome); + DraftAuthorizationFenceBinding.frame(out, worldTerminalEvidence); + return out.toByteArray(); + } + + private void requireExact( + Record row, + AccountPublicationAuthorizationBinding binding, + AccountPublicationAuthorizationBinding.PreallocationInput input, + AccountControlUiActorService.Current current) { + validateRetainedWorldIfPresent(row, binding); + if (row == null + || !binding.operationId().equals(row.get("operation_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class)) + || !input.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !binding.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !binding.publishRequestId().equals(row.get("publish_request_id", String.class)) + || !input.digest().equals(row.get("input_digest", String.class)) + || !Arrays.equals(input.canonicalBytes(), binding.input().canonicalBytes()) + || !Arrays.equals(binding.canonicalBytes(), row.get("binding", byte[].class)) + || !current.stored().operationId.equals(row.get("issuance_operation_id", UUID.class)) + || current.source().issuanceFence() != row.get("issuance_fence", Long.class) + || !Arrays.equals(current.stored().sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(current.stored().bundle, row.get("issuance_bundle", byte[].class)) + || !Arrays.equals( + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints()), + row.get("outbox_checkpoints", byte[].class))) { + throw new IllegalArgumentException("Changed immutable selected-publication authorization"); + } + var stored = + dsl + .fetch( + "SELECT source_key, source_evidence FROM account_selected_publication_sources" + + " WHERE operation_id = ?", + binding.operationId()) + .stream() + .sorted(java.util.Comparator.comparing(r -> r.get("source_key", String.class))) + .toList(); + if (stored.size() != binding.sources().size() + || stored.size() != current.source().sources().size()) { + throw new IllegalStateException("Incomplete publication source participation"); + } + for (int i = 0; i < stored.size(); i++) { + var source = binding.sources().get(i); + if (!source.key().equals(stored.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), stored.get(i).get("source_evidence", byte[].class)) + || !Arrays.equals( + source.canonicalBytes(), current.source().sources().get(i).canonicalBytes())) { + throw new IllegalArgumentException("Changed original publication source vector"); + } + } + } + + /** + * Historical pre-freeze World evidence remains immutable and is checked when a row contains it. + */ + private static void validateRetainedWorldIfPresent( + Record row, AccountPublicationAuthorizationBinding binding) { + byte[] worldEvidence = row == null ? null : row.get("world_evidence", byte[].class); + if (worldEvidence != null) { + GameDesignPublicationOperationBinding.requireAccountWorldCorrelation( + binding, WorldPublishedStartLocationEvidence.fromStored(worldEvidence)); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Objects.equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(), + Connection.TRANSACTION_READ_COMMITTED)) { + throw new IllegalStateException("Writable READ_COMMITTED Account owner transaction required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java new file mode 100644 index 0000000000..6e51691691 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Objects; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; + +/** + * Unregistered Account producer for a distinct selected-publication order. Authenticates the + * current initial creator through the real issuance owner and retains the immutable Draft selection + * before World freezes it. World capture and correlation are a separate later boundary. No remote + * calls, terminalization, or activation occur here. + */ +public final class AccountPublicationAuthorizationService { + private final AccountControlUiActorService actors; + private final DraftAuthorizationFenceRepository fences; + private final AccountPublicationAuthorizationRepository publications; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner transaction collaborators.") + public AccountPublicationAuthorizationService( + AccountControlUiActorService actors, + DraftAuthorizationFenceRepository fences, + AccountPublicationAuthorizationRepository publications) { + this.actors = Objects.requireNonNull(actors); + this.fences = Objects.requireNonNull(fences); + this.publications = Objects.requireNonNull(publications); + } + + public AccountPublicationAuthorizationBinding authorize( + String compactJwt, + AuthoredDraftPublishSelectionBinding selection, + CapturedEnvironmentBoundary environment) { + Objects.requireNonNull(selection); + return actors.withCurrent( + compactJwt, + selection.intent().canonicalTenantId(), + environment, + current -> { + fences.lockProducerSourcesNowait(current.source().sources()); + return publications.authorize( + new AccountPublicationAuthorizationBinding.PreallocationInput( + current.stored().accountId, selection), + current, + () -> fences.requirePublicationAdmission(current.source().sources())); + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java new file mode 100644 index 0000000000..3e26220f58 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.BindableService; +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone, unregistered producer; Account obtains environment authority internally. */ +public final class AccountSelectedDraftPublicationOrderGrpcService implements BindableService { + private final AccountSelectedDraftPublicationOrderService owner; + private final AccountHostedTermsService terms; + private final String namespace; + + public AccountSelectedDraftPublicationOrderGrpcService( + AccountSelectedDraftPublicationOrderService owner, + AccountHostedTermsService terms, + String namespace) { + this.owner = Objects.requireNonNull(owner); + this.terms = Objects.requireNonNull(terms); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + /** + * Binding always includes the method-local credential interceptor; peer identity runs outside it. + */ + @Override + public ServerServiceDefinition bindService() { + var handler = + new AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceImplBase() { + @Override + public void authorizeSelectedPublication( + AuthorizeSelectedPublicationRequest request, + StreamObserver observer) { + AccountSelectedDraftPublicationOrderGrpcService.this.authorizeSelectedPublication( + request, observer); + } + }; + return ServerInterceptors.intercept( + handler, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Status denied = peerDenial(); + if (denied != null) { + call.close(sanitized(denied), new Metadata()); + return new ServerCall.Listener<>() {}; + } + final AccountSelectedPublicationOrderCredentials.Credential credential; + try { + credential = AccountSelectedPublicationOrderCredentials.readAuthenticated(headers); + } catch (IllegalArgumentException malformed) { + call.close(sanitized(Status.UNAUTHENTICATED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + var context = + Context.current() + .withValue(AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, credential); + return Contexts.interceptCall(context, call, headers, next); + } + }); + } + + public void authorizeSelectedPublication( + AuthorizeSelectedPublicationRequest wire, + StreamObserver observer) { + Status denied = peerDenial(); + if (denied != null) { + deny(observer, denied); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + final AccountSelectedPublicationOrderGrpcCodec.Request request; + final String credential; + try { + var protectedCredential = AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get(); + if (protectedCredential == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + credential = protectedCredential.value(); + } catch (IllegalArgumentException malformed) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + try { + request = AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, credential); + } catch (IllegalArgumentException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + final AuthorizeSelectedPublicationResponse response; + try { + var captured = terms.captureCurrentEnvironmentBoundary(); + var binding = + owner.authorize(request.originalCreatorCredential(), request.selection(), captured); + response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + } catch (StatusRuntimeException failure) { + deny(observer, Status.fromCode(failure.getStatus().getCode())); + return; + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError(sanitized(status).asRuntimeException()); + } + + private Status peerDenial() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) return Status.UNAUTHENTICATED; + return ("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri()) + ? null + : Status.PERMISSION_DENIED; + } + + private static Status sanitized(Status status) { + return status.withDescription("Account selected-publication order denied or unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java new file mode 100644 index 0000000000..45180b793b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Standalone, unregistered composition of authenticated Game Design selection read and distinct + * Account publication ordering. SELECTED attests immutable reservation only; Account's existing + * owner primitive remains the authority for the original creator, currentness and source holds. + * World freeze/capture, settlement and runtime admission are separate boundaries. + */ +public final class AccountSelectedDraftPublicationOrderService { + private final AuthoredDraftPublishSelectionReadClient selectionClient; + private final AccountPublicationAuthorizationService owner; + private final String workloadNamespace; + + public AccountSelectedDraftPublicationOrderService( + AuthoredDraftPublishSelectionReadClient selectionClient, + AccountPublicationAuthorizationService owner, + String workloadNamespace) { + this.selectionClient = Objects.requireNonNull(selectionClient, "selectionClient"); + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * The caller's selection is lookup data. Only the exact authenticated Game Design read is passed + * to Account's local producer, with the original creator JWT and environment unchanged. The + * remote read completes before the producer opens its own owner transaction. + */ + public AccountPublicationAuthorizationBinding authorize( + String compactJwt, + AuthoredDraftPublishSelectionBinding lookupSelection, + CapturedEnvironmentBoundary environment) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(lookupSelection, "lookupSelection"); + var request = + AuthoredDraftPublishSelectionReadEvidence.Request.create( + workloadNamespace, lookupSelection); + var evidence = selectionClient.read(request); + if (evidence == null + || !request.equals(evidence.request()) + || !Arrays.equals( + lookupSelection.canonicalBytes(), evidence.request().binding().canonicalBytes()) + || !lookupSelection.digest().equals(evidence.request().binding().digest())) { + throw new IllegalStateException( + "Authenticated Game Design selection differs from the exact publication order request"); + } + requireNoAmbientTransaction(); + return owner.authorize(compactJwt, evidence.request().binding(), environment); + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected publication ordering requires no ambient transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java new file mode 100644 index 0000000000..52729abfb6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java @@ -0,0 +1,138 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered composition of two authenticated owner reads and Account's immutable receipt. + * Historical settlement grants neither creator authority nor runtime admission. + */ +public final class AccountSelectedDraftPublicationSettlementService { + private final AccountPublicationAuthorizationRepository repository; + private final GameDesignPublicationTerminalClient gameDesignClient; + private final WorldPublicationTerminalReadClient worldClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal owner persistence and strict mTLS clients.") + public AccountSelectedDraftPublicationSettlementService( + AccountPublicationAuthorizationRepository repository, + GameDesignPublicationTerminalClient gameDesignClient, + WorldPublicationTerminalReadClient worldClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient); + this.worldClient = Objects.requireNonNull(worldClient); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** Caller bytes identify the original order; only independent authenticated owners settle it. */ + public byte[] settle(byte[] originalOperation) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + var operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); + if (!Arrays.equals(originalOperation, operation.canonicalBytes()) + || !workloadNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException("Exact original publication operation namespace required"); + } + var gameDesignRequest = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create(workloadNamespace, operation.canonicalBytes()); + var gameDesign = gameDesignClient.read(gameDesignRequest); + var terminal = gameDesign == null ? null : gameDesign.terminalEvidence().orElse(null); + if (gameDesign == null || !gameDesignRequest.equals(gameDesign.request()) || terminal == null) { + throw new IllegalStateException("Game Design terminal differs from exact owner read request"); + } + if (!Arrays.equals(operation.canonicalBytes(), terminal.operationBytes())) { + throw new IllegalStateException("Game Design terminal substitutes original operation"); + } + requireNoAmbientTransaction(); + var worldRequest = + WorldPublicationTerminalReadEvidence.Request.create( + workloadNamespace, operation.canonicalBytes(), terminal.canonicalBytes()); + var world = worldClient.read(worldRequest); + var expectedWorldOutcome = + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED + : WorldPublicationTerminalReadEvidence.WorldOutcome.ABORTED; + if (world == null + || !worldRequest.equals(world.request()) + || world.worldOutcome() != expectedWorldOutcome + || world.terminalEvidence() == null + || !Arrays.equals(operation.canonicalBytes(), world.terminalEvidence().operationBytes()) + || !Arrays.equals(terminal.canonicalBytes(), world.terminalEvidence().canonicalBytes()) + || !Arrays.equals(terminal.canonicalBytes(), world.worldTerminalEvidence())) { + throw new IllegalStateException("World terminal differs from exact independent owner read"); + } + requireNoAmbientTransaction(); + byte[] receipt = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository.settle( + operation, + terminal, + world.worldOutcome().name(), + world.worldTerminalEvidence()))); + // A second transaction establishes post-commit historical readback; no new issuer or + // credential capture is involved. Neither SQL phase can contain an owner RPC. + requireNoAmbientTransaction(); + byte[] committed = + ownerTransaction.execute( + ignored -> + repository.settle( + operation, + terminal, + world.worldOutcome().name(), + world.worldTerminalEvidence())); + if (!Arrays.equals(receipt, committed)) { + throw new IllegalStateException("Committed Account settlement readback differs from receipt"); + } + return receipt; + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Publication settlement requires no ambient transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java new file mode 100644 index 0000000000..85bf9e3102 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -0,0 +1,1055 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Genuine Account issuance/current actor, publication producer/storage, loopback mutual TLS and + * production read client. Trust provisioning, legal sources, synchronized Draft and World APPLIED + * descriptors are explicitly stipulated test inputs. No real World handoff, Game Design release, + * deployed workload trust, public wiring, or activation is established by this isolated proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountPublicationAuthorizationMtlsPostgresIntegrationTest { + private static final String NAMESPACE = "test"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("publication-mtls-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "publication-mtls-primary", + "6379"); + + @TempDir Path temporary; + + /** + * Real creator issuance, automatic Account environment capture and publication transaction over + * loopback mTLS. The strict upstream Game Design reader serves a stipulated immutable selection, + * not an actual Game Design reservation/database. Platform/legal/trust inputs remain fixtures. + */ + @Test + void selectedOrderProducerTransportUsesOriginalCreatorAndReplaysOneDurableHeldOrder() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("producer-pki"))); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve("producer-owner")))) { + // Exactly one issuance/OTP consumption; no owner order is fabricated or preseeded. + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var selection = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()) + .selection(); + var issuance = + sources.dsl.fetchSingle( + "SELECT operation_id, token_hash FROM account_control_ui_issuance_operations WHERE status = 'COMMITTED'"); + var reads = new java.util.concurrent.CopyOnWriteArrayList(); + var upstream = + new net.firedevops.firemud.gamedesign.v1.GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceImplBase() { + @Override + public void readSelectedDraftPublication( + net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse> + observer) { + try { + requireAccountClient(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var request = AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest(wire); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.originalSelection()).isEqualTo(selection.canonicalBytes()); + reads.add(wire.getReadRequestId()); + observer.onNext( + AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(request)); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + Server gdServer = terminalServer(pki.gameDesignServer, pki.ca, upstream); + try (var selectionClient = selectionClient(gdServer.getPort(), pki.accountClient, pki.ca)) { + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var owner = + new AccountSelectedDraftPublicationOrderService( + selectionClient, + new AccountPublicationAuthorizationService( + issued.actors(), sources.fences, repository), + NAMESPACE); + var producer = + new AccountSelectedDraftPublicationOrderGrpcService(owner, sources.terms, NAMESPACE); + var held = + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE), + NAMESPACE); + Server accountServer = terminalServer(pki.server, pki.ca, producer, held); + try { + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, issued.compact()); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + assertThat(wire.toString()).doesNotContain(issued.compact()); + var rawKey = + io.grpc.Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + io.grpc.Metadata.BINARY_BYTE_MARSHALLER); + var malformed = new io.grpc.Metadata(); + malformed.put(rawKey, new byte[] {(byte) 128}); + var duplicate = new io.grpc.Metadata(); + duplicate.put(rawKey, issued.compact().getBytes(StandardCharsets.US_ASCII)); + duplicate.put(rawKey, issued.compact().getBytes(StandardCharsets.US_ASCII)); + for (var wrongPeer : List.of(pki.worldManagement, pki.otherNamespace)) { + assertProducerHeaderDenied( + accountServer.getPort(), + wrongPeer, + pki.ca, + wire, + malformed, + Status.Code.PERMISSION_DENIED); + } + for (var headers : List.of(new io.grpc.Metadata(), malformed, duplicate)) { + assertProducerHeaderDenied( + accountServer.getPort(), + pki.gameDesign, + pki.ca, + wire, + headers, + Status.Code.UNAUTHENTICATED); + } + assertThat(reads).isEmpty(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isZero(); + for (var wrongPeer : List.of(pki.worldManagement, pki.otherNamespace)) { + try (var client = producerClient(accountServer.getPort(), wrongPeer, pki.ca)) { + assertCode(Status.Code.PERMISSION_DENIED, () -> client.authorize(request)); + } + assertThat(reads).isEmpty(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isZero(); + } + try (var client = producerClient(accountServer.getPort(), pki.gameDesign, pki.ca)) { + var first = client.authorize(request); + var retry = client.authorize(request); + var fresh = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, issued.compact()); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat(fresh.originalCreatorCredential()) + .isEqualTo(request.originalCreatorCredential()); + var correlatedRetry = client.authorize(fresh); + assertThat(retry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + assertThat(correlatedRetry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + assertThat(first.input().selection().canonicalBytes()) + .isEqualTo(selection.canonicalBytes()); + assertThat(first.input().actorAccountId()).isEqualTo(sources.account.getAccountUuid()); + assertThat(reads).hasSize(3).doesNotHaveDuplicates(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isEqualTo(first.sources().size()); + var stored = + sources.dsl.fetchSingle( + "SELECT binding, issuance_operation_id FROM account_selected_publication_authorizations WHERE operation_id = ?", + first.operationId()); + assertThat(stored.get("binding", byte[].class)).isEqualTo(first.canonicalBytes()); + assertThat(stored.get("issuance_operation_id", UUID.class)) + .isEqualTo(issuance.get("operation_id", UUID.class)); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_control_ui_issuance_operations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchSingle( + "SELECT operation_id, token_hash FROM account_control_ui_issuance_operations WHERE status = 'COMMITTED'")) + .isEqualTo(issuance); + assertPending(sources, repository, first); + try (var reader = client(accountServer.getPort(), pki.worldManagement, pki.ca)) { + var exactHeld = + AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, first); + assertThat(reader.read(exactHeld).request()).isEqualTo(exactHeld); + } + } + } finally { + accountServer.shutdownNow(); + assertThat(accountServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } finally { + gdServer.shutdownNow(); + assertThat(gdServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static AccountSelectedPublicationOrderClient producerClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var client = + new AccountSelectedPublicationOrderClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + /** Negative transport only: deliberately bypasses the production credential emitter. */ + private static void assertProducerHeaderDenied( + int port, + TestIdentity identity, + Path ca, + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest wire, + io.grpc.Metadata headers, + Status.Code expected) + throws Exception { + var channel = + new GrpcChannelFactory() + .buildChannel("127.0.0.1:" + port, 6565, identity.properties(ca), true); + try { + var peer = "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service"; + var stub = + net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc + .newBlockingStub(channel) + .withCallCredentials( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( + peer)) + .withInterceptors( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( + peer), + io.grpc.stub.MetadataUtils.newAttachHeadersInterceptor(headers)) + .withDeadlineAfter(5, TimeUnit.SECONDS); + assertCode(expected, () -> stub.authorizeSelectedPublication(wire)); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static AuthoredDraftPublishSelectionReadClient selectionClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + port); + var client = + new AuthoredDraftPublishSelectionReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + /** + * Real Account storage and two strict loopback mTLS clients. Remote immutable terminals and the + * incoming Game Design request context are stipulated; remote owner databases are not exercised. + */ + @Test + void twoAuthenticatedTerminalOwnersSettleActualAccountOrderAndReadBackAfterCommit() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("settlement-pki"))); + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve(outcome.name())))) { + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var descriptor = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()); + var repository = + org.mockito.Mockito.spy(new AccountPublicationAuthorizationRepository(sources.dsl)); + var order = + new AccountPublicationAuthorizationService(issued.actors(), sources.fences, repository) + .authorize(issued.compact(), descriptor.selection(), issued.environment()); + var operation = + AccountPublicationAuthorizationPostgresIntegrationTest.operation( + order, descriptor.world()); + var terminal = + AccountPublicationAuthorizationPostgresIntegrationTest.terminal(operation, outcome); + var mode = new AtomicReference<>("exact"); + var gdReads = new java.util.concurrent.CopyOnWriteArrayList(); + var worldReads = new java.util.concurrent.CopyOnWriteArrayList(); + var gdEndpoint = + new net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceImplBase() { + @Override + public void readGameDesignPublicationTerminal( + net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse> + observer) { + try { + requireAccountClient(); + var request = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wire); + gdReads.add(request.readRequestId().toString()); + if (mode.get().equals("gd-missing")) throw Status.NOT_FOUND.asRuntimeException(); + if (mode.get().equals("gd-unavailable")) throw Status.UNAVAILABLE.asRuntimeException(); + var result = new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult( + request, + net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status.valueOf(terminal.outcome().name()), + java.util.Optional.of(terminal)); + var response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result).toBuilder(); + if (mode.get().startsWith("gd-") && !mode.get().equals("gd-missing") && !mode.get().equals("gd-unavailable")) { + byte[] echoedRequest = request.canonicalBytes(); + byte[] terminalBytes = terminal.canonicalBytes(); + if (mode.get().equals("gd-correlation")) { + echoedRequest = new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest( + 1, request.targetNamespace(), UUID.randomUUID(), request.operationBytes()).canonicalBytes(); + } else if (mode.get().equals("gd-operation")) { + var invalidRequest = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(invalidRequest, + net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest.SCHEMA); + DraftAuthorizationFenceBinding.frame(invalidRequest, "1"); + DraftAuthorizationFenceBinding.frame(invalidRequest, request.targetNamespace()); + DraftAuthorizationFenceBinding.frame(invalidRequest, request.readRequestId().toString()); + DraftAuthorizationFenceBinding.frame(invalidRequest, new byte[0]); + echoedRequest = invalidRequest.toByteArray(); + } else if (mode.get().equals("gd-unknown")) { + var invalid = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(invalid, GameDesignPublicationTerminalEvidence.SCHEMA); + DraftAuthorizationFenceBinding.frame(invalid, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(invalid, "UNKNOWN"); + terminalBytes = invalid.toByteArray(); + } + var invalidResponse = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(invalidResponse, + net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult.SCHEMA); + DraftAuthorizationFenceBinding.frame(invalidResponse, echoedRequest); + DraftAuthorizationFenceBinding.frame(invalidResponse, terminal.outcome().name()); + DraftAuthorizationFenceBinding.frame(invalidResponse, terminalBytes); + response.setCanonicalResponseBytes(com.google.protobuf.ByteString.copyFrom(invalidResponse.toByteArray())); + } + observer.onNext(response.build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + var worldEndpoint = + new net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadServiceGrpc + .WorldPublicationTerminalReadServiceImplBase() { + @Override + public void readPublicationTerminal( + net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalRequest wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalResponse> + observer) { + try { + requireAccountClient(); + var request = WorldPublicationTerminalReadGrpcCodec.fromRequest(wire); + worldReads.add(wire.getReadRequestId()); + if (mode.get().equals("world-missing")) + throw Status.NOT_FOUND.asRuntimeException(); + if (mode.get().equals("world-unavailable")) + throw Status.UNAVAILABLE.asRuntimeException(); + var response = + WorldPublicationTerminalReadGrpcCodec.toResponse(request, terminal) + .toBuilder(); + if (mode.get().equals("world-correlation")) + response.setReadRequestId(UUID.randomUUID().toString()); + if (mode.get().equals("world-operation")) + response.setOriginalOperation(com.google.protobuf.ByteString.EMPTY); + if (mode.get().equals("world-terminal")) + response.setWorldTerminalEvidence(com.google.protobuf.ByteString.EMPTY); + if (mode.get().equals("world-unknown")) response.setWorldOutcomeValue(99); + if (mode.get().equals("world-phase")) + response.setWorldOutcomeValue( + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED ? 2 : 1); + observer.onNext(response.build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + Server gdServer = terminalServer(pki.gameDesignServer, pki.ca, gdEndpoint); + Server worldServer = terminalServer(pki.worldServer, pki.ca, worldEndpoint); + Server wrongServer = terminalServer(pki.server, pki.ca, gdEndpoint, worldEndpoint); + try (var gdClient = gameDesignClient(gdServer.getPort(), pki.accountClient, pki.ca); + var worldClient = worldClient(worldServer.getPort(), pki.accountClient, pki.ca)) { + var composition = + new AccountSelectedDraftPublicationSettlementService( + repository, gdClient, worldClient, sources.manager, NAMESPACE); + for (String failure : + List.of( + "gd-missing", + "gd-unavailable", + "gd-correlation", + "gd-operation", + "gd-unknown", + "world-missing", + "world-unavailable", + "world-correlation", + "world-operation", + "world-terminal", + "world-unknown", + "world-phase")) { + mode.set(failure); + assertThatThrownBy( + () -> asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + } + mode.set("exact"); + try (var wrongGd = gameDesignClient(wrongServer.getPort(), pki.accountClient, pki.ca); + var wrongWorld = worldClient(wrongServer.getPort(), pki.accountClient, pki.ca)) { + var wrongGdComposition = + new AccountSelectedDraftPublicationSettlementService( + repository, wrongGd, worldClient, sources.manager, NAMESPACE); + var wrongWorldComposition = + new AccountSelectedDraftPublicationSettlementService( + repository, gdClient, wrongWorld, sources.manager, NAMESPACE); + assertThatThrownBy( + () -> asGameDesign(() -> wrongGdComposition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + assertThatThrownBy( + () -> + asGameDesign( + () -> wrongWorldComposition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + } + var invocations = new AtomicInteger(); + var corruptReadback = new java.util.concurrent.atomic.AtomicBoolean(); + String schema = + java.util.Objects.requireNonNull( + sources.dsl.fetchOne("SELECT current_schema() AS schema")) + .get("schema", String.class); + org.mockito.Mockito.doAnswer( + call -> { + int invocation = invocations.incrementAndGet(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_READ_COMMITTED); + if (invocation == 2) { + // Independent connection cannot see the first transaction's uncommitted + // insert. + // Seeing its exact row before the second owner invocation proves prior + // commit. + try (var connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword())) { + connection.setSchema(schema); + try (var statement = + connection.prepareStatement( + "SELECT game_design_terminal FROM account_selected_publication_settlements WHERE operation_id = ?")) { + statement.setObject(1, order.operationId()); + try (var result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getBytes(1)).isEqualTo(terminal.canonicalBytes()); + assertThat(result.next()).isFalse(); + } + } + } + } + byte[] readback = (byte[]) call.callRealMethod(); + return corruptReadback.get() && invocation % 2 == 0 + ? new byte[] {99} + : readback; + }) + .when(repository) + .settle( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + gdReads.clear(); + worldReads.clear(); + byte[] receipt = asGameDesign(() -> composition.settle(operation.canonicalBytes())); + assertThat(asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isEqualTo(receipt); + assertThat(invocations).hasValue(4); + assertThat(gdReads).hasSize(2).doesNotHaveDuplicates(); + assertThat(worldReads).hasSize(2).doesNotHaveDuplicates(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isEqualTo(1); + var heldReader = + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + asGameDesign( + () -> { + heldReader.requireHeld( + AccountPublicationAuthorizationReadEvidence.Request.create( + NAMESPACE, order)); + return null; + })); + assertThat(sources.tx(sources::changeRoleToAdmin).getRole()).isEqualTo("admin"); + corruptReadback.set(true); + assertThatThrownBy( + () -> asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs"); + assertThat( + java.util.Objects.requireNonNull( + sources.dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + order.operationId())) + .get("receipt", byte[].class)) + .isEqualTo(receipt); + } finally { + for (Server server : List.of(gdServer, worldServer, wrongServer)) server.shutdownNow(); + for (Server server : List.of(gdServer, worldServer, wrongServer)) + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + } + + private static void assertPending( + AccountControlUiOwnerSourcesFixture sources, + AccountPublicationAuthorizationRepository repository, + AccountPublicationAuthorizationBinding order) { + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + sources.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy(() -> sources.tx(sources::changeRoleToAdmin)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + } + + private static void requireAccountClient() { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !("spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private static T asGameDesign(Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static Server terminalServer( + TestIdentity identity, Path ca, io.grpc.BindableService... endpoints) throws Exception { + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + for (var endpoint : endpoints) + builder.addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())); + return builder.build().start(); + } + + private static GameDesignPublicationTerminalClient gameDesignClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + port); + var client = + new GameDesignPublicationTerminalClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + private static WorldPublicationTerminalReadClient worldClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + port); + var client = + new WorldPublicationTerminalReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + @Test + void genuineProducerToGameDesignAndWorldMtlsReadersReplaysExactlyAndRejectsSubstitution() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("pki"))); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve("owner")))) { + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var descriptor = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var producer = + new AccountPublicationAuthorizationService(issued.actors(), sources.fences, repository); + var original = + producer.authorize(issued.compact(), descriptor.selection(), issued.environment()); + var request = AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, original); + var endpoint = + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE), + NAMESPACE); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + pki.server.certificate().toFile(), pki.server.key().toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + try { + try (var client = client(server.getPort(), pki.gameDesign, pki.ca)) { + var first = client.read(request); + var retry = client.read(request); + assertThat(first.request()).isEqualTo(request); + assertThat(retry.request()).isEqualTo(first.request()); + assertThat(first.request().originalPublicationAuthorizationBinding()) + .isEqualTo(original.canonicalBytes()); + var freshRead = + AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, original); + assertThat(client.read(freshRead).request()).isEqualTo(freshRead); + var unknown = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), original.fenceId(), original.input(), original.sources()); + var changedFence = + new AccountPublicationAuthorizationBinding( + original.operationId(), UUID.randomUUID(), original.input(), original.sources()); + for (var rejected : List.of(unknown, changedFence)) { + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + client.read( + AccountPublicationAuthorizationReadEvidence.Request.create( + NAMESPACE, rejected))); + } + // A negative read cannot change the exact held owner row or prevent its next read. + assertThat(client.read(request).request()).isEqualTo(request); + } + try (var client = client(server.getPort(), pki.worldManagement, pki.ca)) { + var first = client.read(request); + var retry = client.read(request); + assertThat(first.request()).isEqualTo(request); + assertThat(retry.request()).isEqualTo(first.request()); + assertThat(first.request().originalPublicationAuthorizationBinding()) + .isEqualTo(original.canonicalBytes()); + } + for (var wrongPeer : + List.of(pki.wrongWorkload, pki.otherNamespace, pki.otherWorldNamespace)) { + try (var client = client(server.getPort(), wrongPeer, pki.ca)) { + assertCode(Status.Code.PERMISSION_DENIED, () -> client.read(request)); + } + } + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat( + java.util.Objects.requireNonNull( + sources.dsl.fetchOne( + "SELECT binding FROM account_selected_publication_authorizations WHERE operation_id = ?", + original.operationId()), + "Expected exact retained publication after transport reads") + .get("binding", byte[].class)) + .isEqualTo(original.canonicalBytes()); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static AccountPublicationAuthorizationReadClient client( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var client = + new AccountPublicationAuthorizationReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private record TestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + } + + /** Ephemeral keytool PKI, following Account's existing loopback test; no runtime credentials. */ + private static final class TestPki { + private static final String PASSWORD = "test-only-publication-mtls-password"; + final Path ca; + final TestIdentity server, + accountClient, + gameDesignServer, + worldServer, + gameDesign, + worldManagement, + wrongWorkload, + otherNamespace, + otherWorldNamespace; + + TestPki(Path root) throws Exception { + Path caStore = root.resolve("ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=Account publication test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + ca = root.resolve("ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + ca.toString(), + "-rfc"); + server = issue(root, caStore, "account-server", NAMESPACE, "account-service", true); + accountClient = issue(root, caStore, "account-client", NAMESPACE, "account-service", false); + gameDesignServer = + issue(root, caStore, "game-design-server", NAMESPACE, "game-design-service", true); + worldServer = + issue(root, caStore, "world-server", NAMESPACE, "world-management-service", true); + gameDesign = + issue(root, caStore, "game-design-client", NAMESPACE, "game-design-service", false); + worldManagement = + issue(root, caStore, "world-client", NAMESPACE, "world-management-service", false); + wrongWorkload = + issue(root, caStore, "game-session-client", NAMESPACE, "game-session-service", false); + otherNamespace = + issue( + root, + caStore, + "other-game-design-client", + "other-test", + "game-design-service", + false); + otherWorldNamespace = + issue( + root, caStore, "other-world-client", "other-test", "world-management-service", false); + } + + private static TestIdentity issue( + Path root, Path caStore, String alias, String namespace, String workload, boolean server) + throws Exception { + Path store = root.resolve(alias + ".p12"), + request = root.resolve(alias + ".csr"), + certificate = root.resolve(alias + ".crt"); + String san = + "URI:spiffe://firemud/ns/" + + namespace + + "/sa/" + + workload + + ",DNS:localhost,IP:127.0.0.1"; + String eku = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san); + var keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, PASSWORD.toCharArray()); + } + byte[] privateKey = + java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull( + keyStore.getKey(alias, PASSWORD.toCharArray()), + "Expected ephemeral test private key") + .getEncoded(), + "Expected encoded ephemeral test private key"); + Path key = root.resolve(alias + ".key"); + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(privateKey); + Files.writeString( + key, + "-----BEGIN PRIVATE KEY-----\n" + body + "\n-----END PRIVATE KEY-----\n", + StandardCharsets.US_ASCII); + java.util.Arrays.fill(privateKey, (byte) 0); + return new TestIdentity(certificate, key); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("Ephemeral test certificate generation timed out"); + } + try (var output = process.getInputStream()) { + String details = new String(output.readAllBytes(), StandardCharsets.UTF_8); + if (process.exitValue() != 0) + throw new IllegalStateException("Test keytool failed: " + details); + } + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java new file mode 100644 index 0000000000..6f5208f155 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -0,0 +1,1327 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Account signer/issuance/Redis/current-actor and PostgreSQL ordering. World APPLIED and + * synchronized selection bytes below are explicitly test-only upstream stipulations. This does not + * prove authenticated World transport, publication terminalization or runtime activation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountPublicationAuthorizationPostgresIntegrationTest { + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("publication-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "publication-primary", + "6379"); + + @TempDir Path temporary; + + /** + * Both owner readbacks here are upstream authenticated-owner stipulations, not transport proof. + */ + @Test + void exactTwoOwnerSettlementRollsBackAtomicallyThenReplaysAfterLostAcknowledgement() + throws Exception { + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var order = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var terminal = terminal(operation, outcome); + String phase = + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.settle(operation, terminal, phase, terminal.canonicalBytes()); + throw new IllegalStateException("rollback before owner commit"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy(() -> f.tx(f::changeRoleToAdmin)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + + byte[] originalBinding = order.canonicalBytes(); + byte[] receipt = + f.tx(() -> repository.settle(operation, terminal, phase, terminal.canonicalBytes())); + // A committed response may be lost. Fresh outside transport correlations never enter + // settlement identity; historical replay does not authenticate a new creator credential. + UUID firstTransportRead = UUID.randomUUID(), retryTransportRead = UUID.randomUUID(); + assertThat(firstTransportRead).isNotEqualTo(retryTransportRead); + assertThat( + f.tx( + () -> repository.settle(operation, terminal, phase, terminal.canonicalBytes()))) + .isEqualTo(receipt); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isEqualTo(1); + assertThat( + f.dsl + .fetchSingle( + "SELECT binding FROM account_selected_publication_authorizations WHERE operation_id = ?", + order.operationId()) + .get("binding", byte[].class)) + .isEqualTo(originalBinding); + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.readHeld(order); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("already settled"); + var readOwner = + new AccountPublicationAuthorizationReadService(repository, f.manager, "test"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + readOwner.requireHeld( + net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadEvidence.Request.create( + "test", order)))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + assertThat(f.tx(f::changeRoleToAdmin).getRole()).isEqualTo("admin"); + // Even after the source changes, the original committed issuance and receipt replay. + assertThat( + f.tx( + () -> repository.settle(operation, terminal, phase, terminal.canonicalBytes()))) + .isEqualTo(receipt); + for (String mutation : + List.of( + "UPDATE account_selected_publication_settlements SET world_outcome = 'ABORTED'", + "DELETE FROM account_selected_publication_settlements", + "TRUNCATE account_selected_publication_settlements")) { + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(mutation))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + } + } + + @Test + void missingAmbiguousSubstitutedAndDisagreeingOwnersKeepOriginalSourcesHeld() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var order = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var noPublication = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var published = terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED); + var wrongFence = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + order.operationId(), UUID.randomUUID(), order.input(), order.sources()); + var wrongOperation = operation(wrongFence, proof.world()); + for (Runnable rejected : + List.of( + () -> + repository.settle( + operation, noPublication, "PUBLISHED", noPublication.canonicalBytes()), + () -> + repository.settle( + operation, noPublication, "ABORTED", published.canonicalBytes()), + () -> + repository.settle( + operation, + noPublication, + "RECONCILIATION_REQUIRED", + noPublication.canonicalBytes()), + () -> repository.settle(operation, noPublication, "ABORTED", new byte[0]), + () -> repository.settle(operation, noPublication, "ABORTED", null), + () -> + repository.settle( + wrongOperation, + terminal( + wrongOperation, + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION), + "ABORTED", + terminal( + wrongOperation, + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION) + .canonicalBytes()))) { + assertThatThrownBy( + () -> + f.tx( + () -> { + rejected.run(); + return null; + })) + .isInstanceOf(RuntimeException.class); + } + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThat( + f.dsl.fetchCount(org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + + byte[] receipt = + f.tx( + () -> + repository.settle( + operation, noPublication, "ABORTED", noPublication.canonicalBytes())); + assertThatThrownBy( + () -> + f.tx( + () -> + repository.settle( + operation, published, "PUBLISHED", published.canonicalBytes()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed original"); + assertThat( + f.dsl + .fetchSingle( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + order.operationId()) + .get("receipt", byte[].class)) + .isEqualTo(receipt); + } + } + + @Test + void settlingOneOrderLeavesEveryOtherOriginalSourceParticipationPending() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var first = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var secondSelection = + selection(proof.selection().selectedCommit(), "other order", "another-publication"); + var second = service.authorize(issued.compact(), secondSelection, issued.environment()); + var operation = operation(first, proof.world()); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + f.tx(() -> repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes())); + f.tx( + () -> { + repository.readHeld(second); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + var captured = + f.tx( + () -> + f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), captured.sources(), new byte[] {1}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + } + } + + static GameDesignPublicationTerminalEvidence terminal( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence.Outcome outcome) { + if (outcome == GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION) { + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), outcome, null, null); + } + var request = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + request.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner) ? "sha256:" + "a".repeat(64) : null, + null, + null)) + .toList(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + operation.account().tenantId(), + request.canonicalVersionId(), + "release-exact", + 1, + "v2", + request.publishWorkflowId(), + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of("look"), + "generation-1", + operation.world()); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + outcome, + release, + Math.addExact(request.versionStateEpoch(), 1)); + } + + static GameDesignPublicationOperationBinding operation( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world) { + return new GameDesignPublicationOperationBinding( + account, world, IsolatedWorldPublicationInventoryFixtures.stipulated(account, world)); + } + + private static byte[] rawOperation( + String schema, byte[] accountBytes, byte[] worldBytes, byte[] inventoryBytes, String digest) { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, schema); + DraftAuthorizationFenceBinding.frame(out, accountBytes); + DraftAuthorizationFenceBinding.frame(out, worldBytes); + if (schema.equals(GameDesignPublicationOperationBinding.SCHEMA)) { + DraftAuthorizationFenceBinding.frame(out, inventoryBytes); + DraftAuthorizationFenceBinding.frame(out, digest); + } + return out.toByteArray(); + } + + private static void assertSqlState(Throwable failure, String expectedState) { + String sqlState = null; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sqlException) { + sqlState = sqlException.getSQLState(); + } + } + assertThat(sqlState).isEqualTo(expectedState); + } + + @Test + void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + Integer selectedSourceKeyWidth = + f.dsl + .fetchSingle( + "SELECT character_maximum_length FROM information_schema.columns" + + " WHERE table_schema = current_schema()" + + " AND table_name = 'account_selected_publication_sources'" + + " AND column_name = 'source_key'") + .get(0, Integer.class); + assertThat(selectedSourceKeyWidth).isEqualTo(2048); + String inventoryGuard = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('require_selected_inventory_operation_v2(bytea)'::regprocedure)") + .get(0, String.class); + assertThat(inventoryGuard) + .contains("coalesce(jsonb_agg(entry ORDER BY entry->>'regionTemplateId'), '[]'::JSONB)") + .contains("coalesce(jsonb_agg(entry ORDER BY entry->>'bindingTemplateId'), '[]'::JSONB)") + .contains( + "OR selector->'request'->'worldAffectedTuples' IS DISTINCT FROM expected_tuples") + .contains( + "OR model->'appliedEpochs' IS DISTINCT FROM expected_epochs OR expected_epochs = '[]'::JSONB") + .contains( + "Inventory differs from exact original selected Account, APPLIED graph or freeze"); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, order.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, "ABORTED"); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + byte[] receipt = out.toByteArray(); + String insert = + "INSERT INTO account_selected_publication_settlements" + + " (operation_id, fence_id, account_binding, publication_operation, game_design_outcome," + + " game_design_terminal, world_outcome, world_terminal, receipt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; + List malformed = + List.of( + new Object[] { + order.operationId(), + UUID.randomUUID(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + new byte[] {0}, + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + new byte[] {0}, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + new byte[] {0}, + "ABORTED", + new byte[] {0}, + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "PUBLISHED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + new byte[] {0} + }); + for (Object[] values : malformed) { + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, values))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + String publicInventoryJson = + new String( + operation.inventory().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + String graphDigest = operation.inventory().publicEvidence().sourceModel().graphDigest(); + byte[] substitutedInventory = + publicInventoryJson + .replace( + "\"graphDigest\":\"" + graphDigest + "\"", + "\"graphDigest\":\"sha256:" + "0".repeat(64) + "\"") + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] validOperation = operation.canonicalBytes(); + String tenantId = proof.world().request().canonicalTenantId().toString(); + String versionId = proof.world().request().canonicalVersionId().toString(); + String originalRegionTemplateId = + operation + .inventory() + .publicEvidence() + .sourceModel() + .regionGeneratorInputs() + .get(0) + .regionTemplateId() + .toString(); + String originalRegionInputs = + "\"regionGeneratorInputs\":[" + + inventoryRegionGeneratorInput(originalRegionTemplateId) + + "]"; + String unsortedRegionInputs = + "[" + + inventoryRegionGeneratorInput("00000000-0000-0000-0000-000000000002") + + "," + + inventoryRegionGeneratorInput("00000000-0000-0000-0000-000000000001") + + "]"; + assertThat(publicInventoryJson) + .contains("\"family\":\"REGION\",\"rowCount\":1") + .contains(originalRegionInputs); + byte[] unsortedRegionInventory = + publicInventoryJson + .replace( + "\"family\":\"REGION\",\"rowCount\":1", "\"family\":\"REGION\",\"rowCount\":2") + .replace(originalRegionInputs, "\"regionGeneratorInputs\":" + unsortedRegionInputs) + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] unsortedRegionOperation = + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + unsortedRegionInventory, + DraftAuthorizationFenceBinding.digest(unsortedRegionInventory)); + Object[] unsortedRegionSettlement = { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + unsortedRegionOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }; + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, unsortedRegionSettlement))) + .satisfies( + failure -> + assertSqlFailure( + failure, "23514", "Unsupported or unordered region generator input")); + String unsortedSpawnInputs = + "[" + + inventorySpawnBindingInput( + "00000000-0000-0000-0000-000000000002", + "00000000-0000-0000-0000-000000000003", + "00000000-0000-0000-0000-000000000004", + tenantId, + versionId) + + "," + + inventorySpawnBindingInput( + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000005", + "00000000-0000-0000-0000-000000000006", + tenantId, + versionId) + + "]"; + assertThat(publicInventoryJson) + .contains("\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":0") + .contains("\"spawnBindingCount\":0") + .contains("\"spawnBindingInputs\":[]"); + byte[] unsortedSpawnInventory = + publicInventoryJson + .replace( + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":0", + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":2") + .replace("\"spawnBindingCount\":0", "\"spawnBindingCount\":2") + .replace("\"spawnBindingInputs\":[]", "\"spawnBindingInputs\":" + unsortedSpawnInputs) + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] unsortedSpawnOperation = + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + unsortedSpawnInventory, + DraftAuthorizationFenceBinding.digest(unsortedSpawnInventory)); + Object[] unsortedSpawnSettlement = { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + unsortedSpawnOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }; + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, unsortedSpawnSettlement))) + .satisfies( + failure -> + assertSqlFailure( + failure, "23514", "Unsupported or unordered scoped spawn input")); + List invalidOperations = + List.of( + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + new byte[0], + DraftAuthorizationFenceBinding.digest(new byte[0])), + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + operation.inventory().canonicalBytes(), + "sha256:" + "0".repeat(64)), + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + substitutedInventory, + DraftAuthorizationFenceBinding.digest(substitutedInventory)), + rawOperation( + "game-design-publication-operation/v1", + order.canonicalBytes(), + proof.world().canonicalBytes(), + null, + null), + java.util.Arrays.copyOf(validOperation, validOperation.length + 1)); + for (byte[] invalidOperation : invalidOperations) { + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + insert, + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + invalidOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt))) + .satisfies(failure -> assertSqlState(failure, "23514")); + } + assertThat( + f.dsl.fetchCount(org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + + @Test + void sourceWriterCannotPassUncommittedSettlementAndCanRetryAfterItsCommit() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var executor = java.util.concurrent.Executors.newSingleThreadExecutor(); + try { + f.tx( + () -> { + repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes()); + int settlementPid = + f.dsl.fetchSingle("SELECT pg_backend_pid() AS pid").get("pid", Integer.class); + var writer = + executor.submit( + () -> + f.tx( + () -> { + int writerPid = + f.dsl + .fetchSingle("SELECT pg_backend_pid() AS pid") + .get("pid", Integer.class); + assertThat(writerPid).isNotEqualTo(settlementPid); + // The actual source trigger takes the same source locks NOWAIT. A + // pending + // transaction cannot release its protection to a different writer + // connection. + return f.changeRoleToAdmin(); + })); + assertThatThrownBy(() -> writer.get(10, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(org.jooq.exception.DataAccessException.class); + return null; + }); + assertThat(f.tx(f::changeRoleToAdmin).getRole()).isEqualTo("admin"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + } + + @Test + void authenticatesPreFreezeDistinctOrderReplaysExactlyAndBlocksSourceWritersAndDisclosure() + throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + var original = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var replay = service.authorize(issued.compact(), proof.selection(), issued.environment()); + assertThat(replay.canonicalBytes()).isEqualTo(original.canonicalBytes()); + assertThat(original.operationId()).isNotEqualTo(proof.original().operationId()); + assertThat(original.fenceId()).isNotEqualTo(proof.original().fenceId()); + assertThat(f.dsl.fetchCount(org.jooq.impl.DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat( + java.util.Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT world_evidence FROM account_selected_publication_authorizations" + + " WHERE operation_id = ?", + original.operationId()), + "Expected exact pre-freeze Account order") + .get("world_evidence", byte[].class)) + .isNull(); + // The immutable Account order is available before the separate World capture is correlated. + operation(original, proof.world()); + assertThat(original.sources()).hasSize(8); + var readOwner = + new AccountPublicationAuthorizationReadService( + new AccountPublicationAuthorizationRepository(f.dsl), f.manager, "test"); + var readRequest = + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence + .Request.create("test", original); + asGameDesign(() -> readOwner.requireHeld(readRequest)); + var mismatched = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + original.operationId(), UUID.randomUUID(), original.input(), original.sources()); + var unknown = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + UUID.randomUUID(), original.fenceId(), original.input(), original.sources()); + for (var rejected : List.of(mismatched, unknown)) { + assertThatThrownBy( + () -> + asGameDesign( + () -> + readOwner.requireHeld( + net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadEvidence.Request.create( + "test", rejected)))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + } + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(original.sources()); + return null; + })) + .hasMessageContaining("selected-publication"); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), original.sources(), new byte[] {1}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + // An exact retained replay remains possible while a later source change waits. + assertThat( + service + .authorize(issued.compact(), proof.selection(), issued.environment()) + .canonicalBytes()) + .isEqualTo(original.canonicalBytes()); + asGameDesign(() -> readOwner.requireHeld(readRequest)); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_authorizations SET fence_id = ?", + UUID.randomUUID()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> f.tx(() -> f.dsl.execute("DELETE FROM account_selected_publication_sources"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + var changed = selection(proof.selection().selectedCommit(), "changed notes"); + assertThatThrownBy(() -> service.authorize(issued.compact(), changed, issued.environment())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.authorize( + issued.compact() + "changed", proof.selection(), issued.environment())) + .isInstanceOf(RuntimeException.class); + // Original source/issuance identity is immutable even if a privileged SQL caller tries it. + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_authorizations SET issuance_fence = issuance_fence + 1"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_sources SET source_evidence = ?", + new byte[] {9}))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + + @Test + void earlierWaitingSourceChangeWinsAndDeniedAuthenticationCreatesNoOperation() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var source = + f.tx( + () -> + f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), source.sources(), new byte[] {2}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isTrue(); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + assertThatThrownBy( + () -> service.authorize(issued.compact(), proof.selection(), issued.environment())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source change is waiting"); + assertThatThrownBy( + () -> + service.authorize( + "unsigned-caller-claim", proof.selection(), issued.environment())) + .isInstanceOf(RuntimeException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isTrue(); + } + } + + @Test + void actualSourceWriterBlocksCreatorCaptureThenWinsBeforePublication() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + var accounts = new net.firedevops.firemud.accountservice.repository.AccountRepository(f.dsl); + var executor = java.util.concurrent.Executors.newSingleThreadExecutor(); + var attempt = + new java.util.concurrent.atomic.AtomicReference>(); + try { + f.tx( + () -> { + int blockerPid = + java.util.Objects.requireNonNull( + f.dsl.fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected PostgreSQL source-writer connection") + .get("pid", Integer.class); + var account = + java.util.Objects.requireNonNull( + accounts.findByIdForUpdate(f.account.getId()).orElseThrow(), + "Expected locked Account source before canonical role mutation"); + assertThat(account.getRole()).isNotEqualTo("player"); + attempt.set( + executor.submit( + () -> + service.authorize( + issued.compact(), proof.selection(), issued.environment()))); + long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); + Integer blockedPid = null; + while (System.nanoTime() < deadline && blockedPid == null) { + if (attempt.get().isDone()) { + try { + attempt.get().get(); + } catch (java.util.concurrent.ExecutionException failure) { + throw new AssertionError( + "Creator authorization failed before the Account-row wait was observed", + failure.getCause()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError( + "Interrupted while diagnosing completed creator authorization", + interrupted); + } + throw new AssertionError( + "Creator authorization succeeded before the source writer committed"); + } + // Activity snapshots are otherwise frozen for this blocker transaction. + f.dsl.fetch("SELECT pg_stat_clear_snapshot()"); + var blocked = + f.dsl.fetchOne( + "SELECT pid FROM pg_stat_activity WHERE datname = current_database()" + + " AND ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' LIMIT 1", + blockerPid); + if (blocked != null) blockedPid = blocked.get("pid", Integer.class); + else Thread.onSpinWait(); + } + assertThat(blockedPid) + .as("Distinct creator connection physically waits on source-writer Account row") + .isNotNull(); + assertThat(blockedPid).isNotEqualTo(blockerPid); + assertThat(attempt.get().isDone()).isFalse(); + // Actual guarded source write, held until this transaction commits. The old signed + // credential cannot authorize a publication from the newly changed Account state. + account.setRole("player"); + assertThat(accounts.save(account).getRole()).isEqualTo("player"); + return null; + }); + assertThatThrownBy(() -> attempt.get().get(10, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(RuntimeException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat(accounts.findById(f.account.getId()).orElseThrow().getRole()) + .isEqualTo("player"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + } + + private AccountControlUiOriginalOrderFixture fixture() throws Exception { + return new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary); + } + + private static void asGameDesign(Runnable action) { + io.grpc.Context.current() + .withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()) + .run(action); + } + + record Proof( + AuthoredDraftPublishSelectionBinding selection, + WorldPublishedStartLocationEvidence world, + DraftAuthorizationFenceBinding original) {} + + /** Closed World codec bytes copied in spirit from the existing isolated selector fixtures. */ + static Proof proof( + AccountControlUiOwnerSourcesFixture f, + net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService + .CapturedEnvironmentBoundary + environment) + throws Exception { + UUID version = UUID.randomUUID(), request = UUID.randomUUID(), commit = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + f.tenant, + version, + 17, + "test-private-tenant", + 11, + "test-private-tenant", + "NEW_GAME_ROW"); + List families = List.of("REGION", "ZONE", "ROOM"); + List templates = List.of(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); + List revisions = new ArrayList<>(); + List affected = new ArrayList<>(); + for (int i = 0; i < families.size(); i++) { + UUID revision = UUID.randomUUID(); + var mutation = new LinkedHashMap(); + mutation.put("logicalRevisionId", revision.toString()); + mutation.put("commitId", commit.toString()); + mutation.put("aggregateType", "WORLD_DESIGN_AGGREGATE_TYPE_" + families.get(i)); + mutation.put("aggregateId", templates.get(i).toString()); + if (i == 0) + mutation.put( + "freshGraphDeclaration", + Map.of( + "tenantId", + f.tenant.toString(), + "versionId", + version.toString(), + "startLocation", + Map.of( + "tenantId", + f.tenant.toString(), + "versionId", + version.toString(), + "roomTemplateId", + templates.get(2).toString()), + "familyCounts", + List.of( + "REGION", + "ZONE", + "ROOM", + "ROOM_EXIT", + "GENERATION_RULE", + "WORLD_ENTITY_SPAWN_BINDING") + .stream() + .map( + family -> + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_" + family, + "count", + families.contains(family) ? 1 : 0)) + .toList())); + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + revision, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + new tools.jackson.databind.ObjectMapper().writeValueAsString(mutation))); + affected.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + families.get(i), + templates.get(i).toString(), + "AGGREGATE", + templates.get(i).toString(), + "0")); + } + var draft = DraftCommitBinding.create(target, request, commit, "base-1", revisions, affected); + var selection = selection(draft, "selected publication proof"); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + request, + commit, + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + version, + "base-1", + "0", + draft.canonicalBytes(), + draft.canonicalBytes(), + draft.digest(), + f.tx(() -> f.authority.capture(f.account.getAccountUuid(), f.tenant, environment)) + .sources()); + UUID intake = UUID.randomUUID(); + var operation = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(operation, "world-draft-terminal-operation/v1"); + for (UUID id : + List.of(original.operationId(), request, commit, original.fenceId(), f.tenant, version)) + DraftAuthorizationFenceBinding.frame(operation, id.toString()); + DraftAuthorizationFenceBinding.frame(operation, draft.canonicalBytes()); + for (String value : + List.of( + "test", + f.tenant.toString(), + version.toString(), + original.operationId().toString(), + "17", + intake.toString(), + UUID.randomUUID().toString(), + "a".repeat(64), + UUID.randomUUID().toString(), + "b".repeat(64), + "c".repeat(64), + DraftAuthorizationFenceBinding.digest(original.canonicalBytes()))) + DraftAuthorizationFenceBinding.frame(operation, value); + DraftAuthorizationFenceBinding.frame(operation, original.canonicalBytes()); + List> rows = new ArrayList<>(); + for (int i = 0; i < revisions.size(); i++) { + var mapping = new LinkedHashMap(); + mapping.put("id", i + 1); + mapping.put("target_namespace", "test"); + mapping.put("canonical_tenant_id", f.tenant.toString()); + mapping.put("canonical_version_id", version.toString()); + mapping.put("family", families.get(i)); + mapping.put("template_id", templates.get(i).toString()); + mapping.put("private_row_key", 101 + i); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", original.operationId().toString()); + mapping.put("request_id", request.toString()); + mapping.put("commit_id", commit.toString()); + mapping.put("revision_id", revisions.get(i).revisionId().toString()); + mapping.put("revision_order", Integer.toString(i)); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + byte[] graph = + AccountControlUiAuthority.canonical( + Map.of( + "schemaVersion", + "2", + "canonicalTenantId", + f.tenant.toString(), + "canonicalVersionId", + version.toString(), + "rows", + rows)); + String graphDigest = DraftAuthorizationFenceBinding.digest(graph); + var receipt = + WorldDraftStartLocationEvidence.create( + "test", + original.operationId(), + request, + commit, + original.fenceId(), + DraftAuthorizationFenceBinding.digest(original.canonicalBytes()), + draft.digest(), + new RoomTemplateRef(f.tenant, version, templates.get(2)), + graphDigest); + var applied = new LinkedHashMap(); + applied.put("schema", "world-draft-graph-applied/v2"); + applied.put("status", "APPLIED"); + applied.put("operationBytesBase64", b64(operation.toByteArray())); + applied.put("graphBytesBase64", b64(graph)); + applied.put("graphDigest", graphDigest); + applied.put("startLocationReceiptBase64", b64(receipt.canonicalBytes())); + applied.put("startLocationReceiptDigest", receipt.receiptDigest()); + applied.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + Map.of( + "aggregateType", + u.aggregateType(), + "aggregateId", + u.aggregateId(), + "scopeType", + u.scopeType(), + "scopeId", + u.scopeId(), + "expectedEpoch", + "0", + "resultingEpoch", + "1")) + .toList()); + var worldRequest = + new WorldPublishedStartLocationEvidence.Request( + "test", + f.tenant, + version, + intake, + UUID.randomUUID(), + selection.intent().publishRequestId(), + selection.digest().substring(7), + 5, + PublicationDigestRequestBinding.full( + f.tenant.toString(), "17", selection.intent().publishRequestId()) + .derivedWorkflowIdentity(), + commit.toString(), + "b".repeat(64), + 3, + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList()); + return new Proof( + selection, + new WorldPublishedStartLocationEvidence( + worldRequest, + receipt.canonicalBytes(), + original.canonicalBytes(), + AccountControlUiAuthority.canonical(applied)), + original); + } + + private static String b64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static String inventorySpawnBindingInput( + String bindingTemplateId, + String roomTemplateId, + String entityTemplateId, + String tenantId, + String versionId) { + return "{\"bindingTemplateId\":\"" + + bindingTemplateId + + "\",\"entityReferenceKind\":\"ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID\",\"entityTemplateId\":\"" + + entityTemplateId + + "\",\"entityTemplateType\":\"ITEM\",\"entityTenantId\":\"" + + tenantId + + "\",\"entityVersionId\":\"" + + versionId + + "\",\"respawnDelaySeconds\":0,\"roomTemplateId\":\"" + + roomTemplateId + + "\",\"spawnCount\":1}"; + } + + private static String inventoryRegionGeneratorInput(String regionTemplateId) { + return "{\"generatorParams\":\"\",\"generatorType\":\"\",\"regionTemplateId\":\"" + + regionTemplateId + + "\"}"; + } + + private static void assertSqlFailure( + Throwable failure, String expectedState, String expectedMessage) { + java.sql.SQLException sqlFailure = null; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sqlException) sqlFailure = sqlException; + } + assertThat((Throwable) sqlFailure).isNotNull(); + var exactSqlFailure = + java.util.Objects.requireNonNull(sqlFailure, "Expected SQL failure from direct insert"); + assertThat(exactSqlFailure.getSQLState()).isEqualTo(expectedState); + assertThat(exactSqlFailure.getMessage()).contains(expectedMessage); + } + + private static AuthoredDraftPublishSelectionBinding selection( + DraftCommitBinding draft, String notes) { + return selection(draft, notes, "publication-request"); + } + + private static AuthoredDraftPublishSelectionBinding selection( + DraftCommitBinding draft, String notes, String publishRequestId) { + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + publishRequestId, + "5", + notes, + draft.requestId(), + draft.commitId(), + draft.digest()), + draft.target(), + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + draft.target(), + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java new file mode 100644 index 0000000000..98b3fce42e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java @@ -0,0 +1,246 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.Mockito.doThrow; +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 io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Context-level owner tests; supplied peer contexts are not actual TLS-positive proof. */ +class AccountPublicationAuthorizationReadServiceTest { + private final AccountPublicationAuthorizationRepository repository = + mock(AccountPublicationAuthorizationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final TransactionStatus status = mock(TransactionStatus.class); + private final AccountPublicationAuthorizationReadService service = + new AccountPublicationAuthorizationReadService(repository, transactions, "test"); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void commitsAnIndependentOwnerReadBeforeReturningHeld() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + asPeer("test", "game-design-service", () -> service.requireHeld(request)); + verify(repository).readHeld(any()); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(transactions).commit(status); + } + + @Test + void commitsAnIndependentWorldOwnerReadBeforeReturningHeld() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + asPeer("test", "world-management-service", () -> service.requireHeld(request)); + verify(repository).readHeld(any()); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(transactions).commit(status); + } + + @Test + void rejectsUnverifiedWrongWorkloadCrossNamespaceAndAmbientTransactionBeforeLookup() { + var request = request("test"); + assertCode(Status.Code.UNAUTHENTICATED, () -> service.requireHeld(request)); + for (String workload : + List.of("account-service", "game-session-service", "spring-cloud-gateway")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", workload, () -> service.requireHeld(request))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "game-design-service", () -> service.requireHeld(request))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "world-management-service", () -> service.requireHeld(request))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request("other")))); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + verifyNoInteractions(repository, transactions); + } + + @Test + void absentOrChangedOwnerStateCannotProduceHeldAndStorageFailureFailsClosed() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + doThrow(new IllegalArgumentException("absent or changed")).when(repository).readHeld(any()); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + doThrow(new org.jooq.exception.DataAccessException("offline")).when(repository).readHeld(any()); + assertCode( + Status.Code.UNAVAILABLE, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + } + + @Test + void grpcAuthenticatesBeforeDecodingMalformedCallerCarriers() { + var endpoint = new AccountPublicationAuthorizationReadGrpcService(service, "test"); + var error = new AtomicReference(); + StreamObserver observer = + new StreamObserver<>() { + @Override + public void onNext(ReadHeldPublicationAuthorizationResponse value) { + throw new AssertionError("Malformed request cannot return HELD"); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() { + throw new AssertionError("Malformed request cannot complete"); + } + }; + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer); + assertThat(Status.fromThrowable(error.get()).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + asPeer( + "test", + "account-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + asPeer( + "other", + "world-management-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + asPeer( + "test", + "world-management-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository, transactions); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(action); + } + + private static AccountPublicationAuthorizationReadEvidence.Request request(String namespace) { + UUID actor = UUID.randomUUID(), + tenant = UUID.randomUUID(), + version = UUID.randomUUID(), + revision = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 17, "test-tenant", 11, "test-tenant", "NEW_GAME_ROW"); + var draft = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", revision, DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "ROOM", + "room", + "ROOM_SCOPE", + "room", + "0"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "proof", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + return AccountPublicationAuthorizationReadEvidence.Request.create(namespace, binding); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java new file mode 100644 index 0000000000..b272b7e034 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountPublicationAuthorizationServiceTest { + @Test + void persistenceCannotBeCalledWithoutTheWritableAccountOwnerTransaction() { + var dsl = mock(DSLContext.class); + var repository = new AccountPublicationAuthorizationRepository(dsl); + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable READ_COMMITTED"); + verifyNoInteractions(dsl); + } + + @Test + void readOnlyOrDifferentIsolationCannotMintPublicationPermission() { + var dsl = mock(DSLContext.class); + var repository = new AccountPublicationAuthorizationRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + java.sql.Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + java.sql.Connection.TRANSACTION_REPEATABLE_READ); + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java new file mode 100644 index 0000000000..ed43b1f7a7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java @@ -0,0 +1,578 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +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.ArgumentMatchers.same; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationOrderGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationOrderService; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Native loopback mTLS transport proof for the unregistered selected-publication producer. */ +class AccountSelectedDraftPublicationOrderGrpcMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_ACCOUNT_URI = + "spiffe://firemud/ns/other-test/sa/account-service"; + private static final String WRONG_SERVER_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String WRONG_CLIENT_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_NAMESPACE_CLIENT_URI = + "spiffe://firemud/ns/other-test/sa/game-design-service"; + + @TempDir static Path temporaryDirectory; + private static TestPki pki; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @Test + void authenticatedGameDesignClientReachesEnvironmentCaptureThenUnresolvedOwner() + throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenThrow(Status.FAILED_PRECONDITION.asRuntimeException()); + + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + var client = newClient(server.port(), pki.gameDesignClient())) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + + assertThat(server.handlerCalls()).hasValue(1); + var calls = inOrder(terms, owner); + calls.verify(terms).captureCurrentEnvironmentBoundary(); + calls.verify(owner).authorize(eq(CREDENTIAL), any(), same(captured)); + } + } + + @Test + void trustedWrongServiceAndNamespaceGameDesignCallersAreDeniedBeforeCapture() throws Exception { + for (TestIdentity identity : List.of(pki.wrongServiceClient(), pki.otherNamespaceClient())) { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + var client = newClient(server.port(), identity)) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(1); + verifyNoInteractions(terms, owner); + } + } + } + + @Test + void missingClientCertificateFailsTlsBeforeReceiverOrOwner() throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + ClientTransport client = newClientWithoutIdentity(server.port())) { + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request()); + + assertThatThrownBy(() -> client.authorize(wire)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "missing client certificate must fail during TLS negotiation: %s", + failure) + .isTrue()); + + assertThat(server.handlerCalls()).hasValue(0); + verifyNoInteractions(terms, owner); + } + } + + @Test + void creatorCredentialMetadataIsRequiredBeforeEnvironmentCapture() throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + ClientTransport client = newClientWithIdentity(server.port(), pki.gameDesignClient())) { + assertThatThrownBy( + () -> client.authorize(AccountSelectedPublicationOrderGrpcCodec.toRequest(request()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + assertThat(server.handlerCalls()).hasValue(1); + verifyNoInteractions(terms, owner); + } + } + + @Test + void clientRejectsTrustedWrongServiceAndNamespaceAccountServerIdentities() throws Exception { + for (TestIdentity identity : List.of(pki.wrongServiceServer(), pki.otherNamespaceServer())) { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(identity, owner, terms); + var client = newClient(server.port(), pki.gameDesignClient())) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(0); + verifyNoInteractions(terms, owner); + } + } + } + + private static TransportServer startServer( + TestIdentity serverIdentity, + AccountSelectedDraftPublicationOrderService owner, + AccountHostedTermsService terms) + throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + ServerInterceptor countHandlerCalls = + new ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + handlerCalls.incrementAndGet(); + return next.startCall(call, headers); + } + }; + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new AccountSelectedDraftPublicationOrderGrpcService(owner, terms, NAMESPACE), + countHandlerCalls, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new TransportServer(server, handlerCalls); + } + + private static AccountSelectedPublicationOrderClient newClient(int port, TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + return new AccountSelectedPublicationOrderClient( + endpoints, + pki.clientProperties(temporaryDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ClientTransport newClientWithoutIdentity(int port) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCaCert(pki.caCertificatePem().toString()); + ManagedChannel channel = + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false); + return new ClientTransport(channel); + } + + private static ClientTransport newClientWithIdentity(int port, TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var channel = + new GrpcChannelFactory() + .buildChannel( + endpoints.getAccountService(), + 6565, + pki.clientProperties(temporaryDirectory, identity), + false); + return new ClientTransport(channel); + } + + private static AccountSelectedPublicationOrderGrpcCodec.Request request() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19, "tenant-key", 42, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "fixture", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, CREDENTIAL); + } + + private static final String CREDENTIAL = "original.secret.credential"; + + private record TransportServer(Server server, AtomicInteger handlerCalls) + implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private void authorize( + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest request) { + AccountSelectedPublicationOrderServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .authorizeSelectedPublication(request); + } + + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback gRPC client did not terminate"); + } + } + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + Path caCertificatePem, + TestIdentity accountServer, + TestIdentity wrongServiceServer, + TestIdentity otherNamespaceServer, + TestIdentity gameDesignClient, + TestIdentity wrongServiceClient, + TestIdentity otherNamespaceClient) { + private static final String STORE_PASSWORD = "test-only-store-password"; + + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("selected-publication-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD selected publication test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("selected-publication-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var ca = readCertificate(caFile); + return new TestPki( + ca, + caFile, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-service-server", WRONG_SERVER_URI, true), + issueIdentity( + directory, caStore, caFile, "other-namespace-server", WRONG_ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false), + issueIdentity( + directory, caStore, caFile, "wrong-service-client", WRONG_CLIENT_URI, false), + issueIdentity( + directory, + caStore, + caFile, + "other-namespace-client", + OTHER_NAMESPACE_CLIENT_URI, + false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + writePem( + directory.resolve(identity.alias() + ".client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + writePem( + directory.resolve(identity.alias() + ".client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()) + .toString()); + tls.setCaCert(caCertificatePem.toString()); + tls.setPlaintext(false); + return tls; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + ArrayList command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java new file mode 100644 index 0000000000..53a1c94d72 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java @@ -0,0 +1,305 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Context-level receiver units, not mounted-certificate or real Account currentness proof. */ +class AccountSelectedDraftPublicationOrderGrpcServiceTest { + private static final String CREDENTIAL = "original.secret.credential"; + private final AccountSelectedDraftPublicationOrderService owner = + mock(AccountSelectedDraftPublicationOrderService.class); + private final AccountHostedTermsService terms = mock(AccountHostedTermsService.class); + private final AccountSelectedDraftPublicationOrderGrpcService receiver = + new AccountSelectedDraftPublicationOrderGrpcService(owner, terms, "test"); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeMalformedDecodeAndCaptureAndDeniesWorld() { + assertThat(invoke(null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String workload : + List.of("world-management-service", "account-service", "game-session-service")) { + assertThat(peer("test", workload, () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(peer("other", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + authorized(() -> invoke(AuthorizeSelectedPublicationRequest.getDefaultInstance())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner, terms); + } + + @Test + void boundInterceptorAuthenticatesBeforeTouchingMalformedCredentialMetadata() { + var headers = mock(io.grpc.Metadata.class); + assertThat(boundCode(headers)).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer("test", "world-management-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(headers, owner, terms); + var malformed = new io.grpc.Metadata(); + malformed.put( + io.grpc.Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + io.grpc.Metadata.BINARY_BYTE_MARSHALLER), + new byte[] {(byte) 128}); + assertThat(peer("test", "game-design-service", () -> boundCode(malformed))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer("test", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(owner, terms); + } + + @SuppressWarnings("unchecked") + private Status.Code boundCode(io.grpc.Metadata headers) { + var method = + (io.grpc.ServerMethodDefinition< + AuthorizeSelectedPublicationRequest, AuthorizeSelectedPublicationResponse>) + receiver.bindService().getMethods().iterator().next(); + io.grpc.ServerCall + call = mock(io.grpc.ServerCall.class); + method.getServerCallHandler().startCall(call, headers); + var status = org.mockito.ArgumentCaptor.forClass(Status.class); + org.mockito.Mockito.verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any()); + return status.getValue().getCode(); + } + + @Test + void deniesAmbientSqlNamespaceAndUnknownFieldsBeforeCapture() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(authorized(() -> invoke(null)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThat(authorized(() -> invoke(null)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clearSynchronization(); + var request = request(); + assertThat( + authorized(() -> invoke(request.toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + authorized( + () -> + invoke( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner, terms); + } + + @Test + void + automaticallyCapturesAccountEnvironmentAndHandsOffOriginalCredentialAndSelectionOutsideSql() { + var request = request(); + var decoded = AccountSelectedPublicationOrderGrpcCodec.fromRequest(request, CREDENTIAL); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + UUID actor = UUID.randomUUID(); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + actor, decoded.selection()), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + when(terms.captureCurrentEnvironmentBoundary()) + .thenAnswer( + call -> { + outsideSql(); + return captured; + }); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenAnswer( + call -> { + outsideSql(); + assertThat( + call.getArgument(1, AuthoredDraftPublishSelectionBinding.class) + .canonicalBytes()) + .isEqualTo(decoded.originalSelection()); + return binding; + }); + var result = authorized(() -> invoke(request)); + assertThat(result.error()).isNull(); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse(decoded, result.response()) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + assertThat(result.response().toString()).doesNotContain(CREDENTIAL); + } + + @Test + void unavailableCaptureReturnsSanitizedFailure() { + when(terms.captureCurrentEnvironmentBoundary()) + .thenThrow(new IllegalStateException(CREDENTIAL)); + var denied = authorized(() -> invoke(request())); + assertThat(denied.code()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + verifyNoInteractions(owner); + } + + @Test + void secretBearingOwnerStatusReturnsOnlyItsCodeAndSanitizedDescription() { + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenThrow(Status.PERMISSION_DENIED.withDescription(CREDENTIAL).asRuntimeException()); + var denied = authorized(() -> invoke(request())); + assertThat(denied.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + assertThat(denied.error().getCause()).isNull(); + } + + private record Result(AuthorizeSelectedPublicationResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private Result invoke(AuthorizeSelectedPublicationRequest request) { + var response = new AtomicReference(); + var error = new AtomicReference(); + receiver.authorizeSelectedPublication( + request, + new io.grpc.stub.StreamObserver<>() { + @Override + public void onNext(AuthorizeSelectedPublicationResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() {} + }); + return new Result(response.get(), error.get()); + } + + private static void outsideSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static T authorized(java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, + AccountSelectedPublicationOrderCredentials.Credential.of(CREDENTIAL)); + var prior = context.attach(); + try { + return peer("test", "game-design-service", action); + } finally { + context.detach(prior); + } + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static AuthorizeSelectedPublicationRequest request() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19, "tenant-key", 42, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "fixture", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return AccountSelectedPublicationOrderGrpcCodec.toRequest( + AccountSelectedPublicationOrderGrpcCodec.Request.create("test", selected, CREDENTIAL)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java new file mode 100644 index 0000000000..375ee54ec9 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java @@ -0,0 +1,292 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.ArgumentMatchers.same; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Composition ordering units with stipulated peer context and mocked owner evidence/producer. These + * fixture values are not genuine cross-owner mTLS, creator or PostgreSQL proof. + */ +class AccountSelectedDraftPublicationOrderServiceTest { + private static final String COMPACT_JWT = "original-compact-creator-jwt"; + private final AuthoredDraftPublishSelectionReadClient client = + mock(AuthoredDraftPublishSelectionReadClient.class); + private final AccountPublicationAuthorizationService owner = + mock(AccountPublicationAuthorizationService.class); + private final CapturedEnvironmentBoundary environment = mock(CapturedEnvironmentBoundary.class); + private final AccountSelectedDraftPublicationOrderService service = + new AccountSelectedDraftPublicationOrderService(client, owner, "test"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void deniesMissingWrongServiceAndCrossNamespacePeerBeforeTransportOrOwner() { + // Null lookup also proves authentication precedes carrier inspection. + assertCode(Status.Code.UNAUTHENTICATED, () -> service.authorize(null, null, null)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", workload, () -> service.authorize(null, null, null))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "game-design-service", () -> service.authorize(null, null, null))); + verifyNoInteractions(client, owner); + } + + @Test + void rejectsActualTransactionAndSynchronizationBeforeRemoteRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + verifyNoInteractions(client, owner); + } + + @Test + void exactReadCompletesBeforeOwnerReceivesUnchangedCreatorJwtEnvironmentAndSelection() { + var lookup = selection(); + var result = mock(AccountPublicationAuthorizationBinding.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var request = + invocation.getArgument( + 0, AuthoredDraftPublishSelectionReadEvidence.Request.class); + assertThat(request.targetNamespace()).isEqualTo("test"); + assertThat(request.originalSelection()).containsExactly(lookup.canonicalBytes()); + assertThat(request.selectionDigest()).isEqualTo(lookup.digest()); + return fixtureEvidence(request); + }); + when(owner.authorize(eq(COMPACT_JWT), eq(lookup), same(environment))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return result; + }); + assertThat(authorized(() -> service.authorize(COMPACT_JWT, lookup, environment))) + .isSameAs(result); + var request = ArgumentCaptor.forClass(AuthoredDraftPublishSelectionReadEvidence.Request.class); + var order = inOrder(client, owner); + order.verify(client).read(request.capture()); + order.verify(owner).authorize(eq(COMPACT_JWT), eq(lookup), same(environment)); + order.verifyNoMoreInteractions(); + assertThat(request.getValue().binding()).isEqualTo(lookup); + } + + @Test + void missingOrSubstitutedReadbackNeverInvokesAccountOwner() { + when(client.read(any())).thenReturn(null); + assertThatThrownBy( + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))) + .isInstanceOf(IllegalStateException.class); + for (String changed : List.of("namespace", "readIdentity", "selection")) { + doAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, AuthoredDraftPublishSelectionReadEvidence.Request.class); + if ("selection".equals(changed)) { + var original = request.binding(); + var intent = original.intent(); + var replaced = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + "changed notes", + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()), + original.target(), + original.selectedCommit(), + new VisibilityFence( + original.target(), + original.fenceRequestId(), + original.fenceCommitId(), + original.fenceInputDigest(), + original.fenceResultVectorJson(), + OffsetDateTime.parse(original.fenceCreatedAt()))); + return fixtureEvidence( + new AuthoredDraftPublishSelectionReadEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + request.readRequestId(), + replaced.canonicalBytes(), + replaced.digest())); + } + return fixtureEvidence( + new AuthoredDraftPublishSelectionReadEvidence.Request( + request.schemaVersion(), + "namespace".equals(changed) ? "other" : request.targetNamespace(), + "readIdentity".equals(changed) + ? UUID.randomUUID() + : request.readRequestId(), + request.originalSelection(), + request.selectionDigest())); + }) + .when(client) + .read(any()); + assertThatThrownBy( + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from the exact publication order request"); + } + verifyNoInteractions(owner); + } + + @Test + void unavailableOrDeniedSelectionReadNeverInvokesOwner() { + for (Status failure : List.of(Status.UNAVAILABLE, Status.NOT_FOUND, Status.PERMISSION_DENIED)) { + doThrow(failure.asRuntimeException()).when(client).read(any()); + assertCode( + failure.getCode(), + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + } + verifyNoInteractions(owner); + } + + @Test + void lowerLevelCreatorDenialPropagatesAfterExactOwnerRead() { + when(client.read(any())).thenAnswer(invocation -> fixtureEvidence(invocation.getArgument(0))); + when(owner.authorize(any(), any(), any())) + .thenThrow(Status.PERMISSION_DENIED.asRuntimeException()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + var order = inOrder(client, owner); + order.verify(client).read(any()); + order.verify(owner).authorize(eq(COMPACT_JWT), eq(selection()), same(environment)); + } + + private static AuthoredDraftPublishSelectionReadEvidence fixtureEvidence( + AuthoredDraftPublishSelectionReadEvidence.Request request) { + var evidence = mock(AuthoredDraftPublishSelectionReadEvidence.class); + when(evidence.request()).thenReturn(request); + return evidence; + } + + private static T authorized(Supplier action) { + return asPeer("test", "game-design-service", action); + } + + private static T asPeer(String namespace, String workload, Supplier action) { + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static AuthoredDraftPublishSelectionBinding selection() { + UUID tenant = uuid("22222222-2222-4222-8222-222222222222"); + UUID version = uuid("33333333-3333-4333-8333-333333333333"); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "5", + "test selection", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return selected; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java new file mode 100644 index 0000000000..a85039965e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java @@ -0,0 +1,377 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Composition seams only: canonical codec outputs, owner results and peer identity are stipulated + * here. Actual PostgreSQL, codec integrity and mounted-certificate mTLS are separate proof. + */ +class AccountSelectedDraftPublicationSettlementServiceTest { + private final AccountPublicationAuthorizationRepository repository = + mock(AccountPublicationAuthorizationRepository.class); + private final GameDesignPublicationTerminalClient gameDesign = + mock(GameDesignPublicationTerminalClient.class); + private final WorldPublicationTerminalReadClient world = + mock(WorldPublicationTerminalReadClient.class); + private final OwnerTransactions transactions = new OwnerTransactions(); + private final AccountSelectedDraftPublicationSettlementService service = + new AccountSelectedDraftPublicationSettlementService( + repository, gameDesign, world, transactions, "test"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeMalformedDecodeOrOwnerReads() { + assertCode(Status.Code.UNAUTHENTICATED, () -> service.settle(null)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("test", workload, () -> service.settle(new byte[] {0}))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("other", "game-design-service", () -> service.settle(null))); + assertThatThrownBy(() -> authorized(() -> service.settle(new byte[] {0}))) + .isInstanceOf(RuntimeException.class); + verifyNoInteractions(repository, gameDesign, world); + assertThat(transactions.begins).isZero(); + } + + @Test + void deniesAmbientTransactionAndSynchronizationBeforeDecode() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null))); + verifyNoInteractions(repository, gameDesign, world); + } + + @Test + void agreeingOwnersCommitThenSeparatelyReadBackAndRetriesUseFreshReadCorrelations() { + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = new CodecOutputs(outcome)) { + var gameDesignReads = new ArrayList(); + var worldReads = new ArrayList(); + doAnswer( + call -> { + assertNoSql(); + var request = + call.getArgument(0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class); + gameDesignReads.add(request.readRequestId()); + return gameDesignEvidence(request, fixture.terminal); + }) + .when(gameDesign) + .read(any()); + doAnswer( + call -> { + assertNoSql(); + var request = + call.getArgument(0, WorldPublicationTerminalReadEvidence.Request.class); + worldReads.add(request.readRequestId()); + return worldEvidence(request, fixture.terminal, request.expectedWorldOutcome()); + }) + .when(world) + .read(any()); + var calls = new AtomicInteger(); + int priorCommits = transactions.commits; + byte[] receipt = new byte[] {9, 8}; + doAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_READ_COMMITTED); + assertThat(transactions.commits - priorCommits) + .isEqualTo(calls.getAndIncrement()); + assertThat(call.getArgument(0, GameDesignPublicationOperationBinding.class)) + .isSameAs(fixture.operation); + assertThat(call.getArgument(1, GameDesignPublicationTerminalEvidence.class)) + .isSameAs(fixture.terminal); + assertThat(call.getArgument(2, String.class)).isEqualTo(fixture.phase.name()); + assertThat(call.getArgument(3, byte[].class)) + .containsExactly(fixture.terminalBytes); + return receipt.clone(); + }) + .when(repository) + .settle(any(), any(), anyString(), any()); + assertThat(authorized(() -> service.settle(fixture.operationBytes))) + .containsExactly(receipt); + assertThat(authorized(() -> service.settle(fixture.operationBytes))) + .containsExactly(receipt); + assertThat(calls).hasValue(4); + assertThat(transactions.commits - priorCommits).isEqualTo(4); + assertThat(gameDesignReads).hasSize(2).doesNotHaveDuplicates(); + assertThat(worldReads).hasSize(2).doesNotHaveDuplicates(); + assertNoSql(); + } + } + } + + @Test + void missingSubstitutedOrUnavailableGameDesignResultNeverReadsWorldOrWritesAccount() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(gameDesign.read(any())).thenReturn(null); + assertFailure(fixture); + doAnswer( + call -> { + var request = + call.getArgument(0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class); + return gameDesignEvidence( + new GameDesignPublicationTerminalReadEvidence.ReadRequest( + 1, "test", UUID.randomUUID(), request.operationBytes()), + fixture.terminal); + }) + .when(gameDesign) + .read(any()); + assertFailure(fixture); + var substituted = mock(GameDesignPublicationTerminalEvidence.class); + when(substituted.canonicalBytes()).thenReturn(new byte[] {99}); + doAnswer(call -> gameDesignEvidence(call.getArgument(0), substituted)) + .when(gameDesign) + .read(any()); + assertFailure(fixture); + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(gameDesign).read(any()); + assertCode( + Status.Code.UNAVAILABLE, () -> authorized(() -> service.settle(fixture.operationBytes))); + verifyNoInteractions(world, repository); + assertThat(transactions.begins).isZero(); + } + } + + @Test + void + worldNamespaceMismatchMissingChangedRequestTerminalPhaseAndUnavailableKeepAccountUntouched() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(fixture.worldRequest.targetNamespace()).thenReturn("other"); + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(gameDesign, world, repository); + when(fixture.worldRequest.targetNamespace()).thenReturn("test"); + when(gameDesign.read(any())) + .thenAnswer(call -> gameDesignEvidence(call.getArgument(0), fixture.terminal)); + for (String changed : + List.of("missing", "correlation", "namespace", "phase", "terminal", "operation")) { + doAnswer( + call -> { + var request = + call.getArgument(0, WorldPublicationTerminalReadEvidence.Request.class); + if (changed.equals("missing")) return null; + var response = worldEvidence(request, fixture.terminal, fixture.phase); + if (changed.equals("correlation") || changed.equals("namespace")) { + // Mock the returned request itself to exercise a substituted owner echo without + // treating a structurally invalid carrier as a genuine codec result. + when(response.request()) + .thenReturn(mock(WorldPublicationTerminalReadEvidence.Request.class)); + } + if (changed.equals("phase")) + when(response.worldOutcome()) + .thenReturn(WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED); + if (changed.equals("terminal")) + when(response.worldTerminalEvidence()).thenReturn(new byte[] {99}); + if (changed.equals("operation")) { + var other = mock(GameDesignPublicationTerminalEvidence.class); + when(other.operationBytes()).thenReturn(new byte[] {99}); + when(response.terminalEvidence()).thenReturn(other); + } + return response; + }) + .when(world) + .read(any()); + assertFailure(fixture); + } + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(world).read(any()); + assertCode( + Status.Code.UNAVAILABLE, () -> authorized(() -> service.settle(fixture.operationBytes))); + verifyNoInteractions(repository); + assertThat(transactions.begins).isZero(); + } + } + + @Test + void changedPostCommitReadbackCannotReturnSuccess() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(gameDesign.read(any())) + .thenAnswer(call -> gameDesignEvidence(call.getArgument(0), fixture.terminal)); + when(world.read(any())) + .thenAnswer(call -> worldEvidence(call.getArgument(0), fixture.terminal, fixture.phase)); + when(repository.settle(any(), any(), anyString(), any())) + .thenReturn(new byte[] {1}, new byte[] {2}); + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs"); + assertThat(transactions.commits).isEqualTo(2); + assertNoSql(); + } + } + + private void assertFailure(CodecOutputs fixture) { + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(RuntimeException.class); + } + + private static GameDesignPublicationTerminalReadEvidence.ReadResult gameDesignEvidence( + GameDesignPublicationTerminalReadEvidence.ReadRequest request, + GameDesignPublicationTerminalEvidence terminal) { + var result = mock(GameDesignPublicationTerminalReadEvidence.ReadResult.class); + when(result.request()).thenReturn(request); + when(result.terminalEvidence()).thenReturn(java.util.Optional.ofNullable(terminal)); + return result; + } + + private static WorldPublicationTerminalReadEvidence worldEvidence( + WorldPublicationTerminalReadEvidence.Request request, + GameDesignPublicationTerminalEvidence terminal, + WorldPublicationTerminalReadEvidence.WorldOutcome phase) { + byte[] terminalBytes = terminal.canonicalBytes(); + var result = mock(WorldPublicationTerminalReadEvidence.class); + when(result.request()).thenReturn(request); + when(result.terminalEvidence()).thenReturn(terminal); + when(result.worldTerminalEvidence()).thenReturn(terminalBytes); + when(result.worldOutcome()).thenReturn(phase); + return result; + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static T authorized(Supplier action) { + return peer("test", "game-design-service", action); + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static final class CodecOutputs implements AutoCloseable { + final byte[] operationBytes = new byte[] {11}; + final byte[] terminalBytes = new byte[] {22}; + final GameDesignPublicationOperationBinding operation = + mock(GameDesignPublicationOperationBinding.class); + final GameDesignPublicationTerminalEvidence terminal = + mock(GameDesignPublicationTerminalEvidence.class); + final WorldPublishedStartLocationEvidence.Request worldRequest = + mock(WorldPublishedStartLocationEvidence.Request.class); + final WorldPublicationTerminalReadEvidence.WorldOutcome phase; + final org.mockito.MockedStatic operations = + mockStatic(GameDesignPublicationOperationBinding.class); + final org.mockito.MockedStatic terminals = + mockStatic(GameDesignPublicationTerminalEvidence.class); + + CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome outcome) { + var world = mock(WorldPublishedStartLocationEvidence.class); + when(operation.canonicalBytes()).thenReturn(operationBytes); + when(operation.world()).thenReturn(world); + when(world.request()).thenReturn(worldRequest); + when(worldRequest.targetNamespace()).thenReturn("test"); + when(terminal.canonicalBytes()).thenReturn(terminalBytes); + when(terminal.operationBytes()).thenReturn(operationBytes); + when(terminal.worldEvidence()).thenReturn(world); + when(terminal.outcome()).thenReturn(outcome); + operations + .when(() -> GameDesignPublicationOperationBinding.fromStored(operationBytes)) + .thenReturn(operation); + terminals + .when(() -> GameDesignPublicationTerminalEvidence.fromStored(terminalBytes)) + .thenReturn(terminal); + phase = + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED + : WorldPublicationTerminalReadEvidence.WorldOutcome.ABORTED; + } + + @Override + public void close() { + terminals.close(); + operations.close(); + } + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java new file mode 100644 index 0000000000..79273b345a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java @@ -0,0 +1,137 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.CompositeCallCredentials; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Strict explicit mTLS client; never registers or enables the Account producer. */ +public final class AccountSelectedPublicationOrderClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub> { + private final String namespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountSelectedPublicationOrderClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory factory, + String namespace) { + super(endpoints, requireMtls(tls), factory, AccountSelectedPublicationOrderClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account selected-publication client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account selected-publication stub unavailable"); + initialized = true; + } + + public AccountPublicationAuthorizationBinding authorize( + AccountSelectedPublicationOrderGrpcCodec.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException( + "Account selected-publication transport requires no owner transaction"); + Objects.requireNonNull(request); + if (!namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Account selected-publication namespace mismatch"); + var current = stub(); + if (closed || !initialized || current == null) + throw new IllegalStateException("Account selected-publication client unavailable"); + try { + var response = + current + .withCallCredentials( + new CompositeCallCredentials( + new GrpcServerPeerIdentityCallCredentials( + "spiffe://firemud/ns/" + namespace + "/sa/account-service"), + AccountSelectedPublicationOrderCredentials.forCall( + request.originalCreatorCredential()))) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .authorizeSelectedPublication( + AccountSelectedPublicationOrderGrpcCodec.toRequest(request)); + return AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, response); + } catch (StatusRuntimeException unavailable) { + // Remote diagnostics are not trusted to exclude credential-bearing request data. + throw Status.fromCode(unavailable.getStatus().getCode()) + .withDescription("Account selected-publication order denied or unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Account returned invalid selected-publication order evidence"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + return AccountSelectedPublicationOrderServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private static CommonGrpcClientProperties requireMtls(CommonGrpcClientProperties tls) { + if (tls == null || tls.isPlaintext()) + throw new IllegalArgumentException("Account selected-publication requires workload mTLS"); + for (String configured : + new String[] {tls.getCertChain(), tls.getPrivateKey(), tls.getCaCert()}) { + if (configured == null || configured.isBlank() || configured.trim().startsWith("classpath:")) + throw new IllegalArgumentException( + "Account selected-publication requires readable file-backed TLS material"); + Path file; + try { + file = Path.of(configured.trim()); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Account selected-publication requires file-backed TLS material"); + } + if (!Files.isRegularFile(file) || !Files.isReadable(file)) + throw new IllegalArgumentException( + "Account selected-publication requires readable file-backed TLS material"); + } + return tls; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java new file mode 100644 index 0000000000..a62175efec --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.CallCredentials; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Executor; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; + +/** + * Purpose-specific protected metadata for the original creator credential. Never log metadata: + * metadata's wire serialization necessarily contains the secret, unlike this redacted wrapper. The + * receiver must authenticate its workload peer before reading or decoding this header. + */ +public final class AccountSelectedPublicationOrderCredentials { + public static final Context.Key CONTEXT_KEY = + Context.key("account-selected-publication-original-creator"); + public static final Metadata.Key HEADER = + Metadata.Key.of( + "firemud-selected-publication-creator-bin", + new Metadata.BinaryMarshaller<>() { + @Override + public byte[] toBytes(Credential value) { + return value.bytes.clone(); + } + + // Parsing deliberately defers all credential validation until after workload + // authentication. + @Override + public Credential parseBytes(byte[] serialized) { + return new Credential(serialized); + } + }); + + private AccountSelectedPublicationOrderCredentials() {} + + public static final class Credential { + private final byte[] bytes; + + private Credential(byte[] bytes) { + this.bytes = bytes.clone(); + } + + public static Credential of(String value) { + if (value == null + || value.isEmpty() + || value.length() > AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES + || value.chars().anyMatch(c -> c <= 32 || c >= 127)) throw invalid(); + return new Credential(value.getBytes(StandardCharsets.US_ASCII)); + } + + public String value() { + if (bytes.length == 0 + || bytes.length > AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES) + throw invalid(); + for (byte value : bytes) if (value <= 32 || value >= 127) throw invalid(); + return new String(bytes, StandardCharsets.US_ASCII); + } + + @Override + public String toString() { + return "SelectedPublicationCredential[redacted]"; + } + } + + /** Only after authenticating the exact same-namespace Game Design peer. */ + public static Credential readAuthenticated(Metadata headers) { + var values = headers.getAll(HEADER); + if (values == null) throw invalid(); + var iterator = values.iterator(); + if (!iterator.hasNext()) throw invalid(); + Credential credential = iterator.next(); + if (iterator.hasNext()) throw invalid(); + credential.value(); + return credential; + } + + public static CallCredentials forCall(String value) { + var credential = Credential.of(value); + return new CallCredentials() { + @Override + public void applyRequestMetadata( + RequestInfo info, Executor executor, MetadataApplier applier) { + if (info.getSecurityLevel() != SecurityLevel.PRIVACY_AND_INTEGRITY + || !AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod() + .getFullMethodName() + .equals(info.getMethodDescriptor().getFullMethodName())) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Protected selected-publication transport required")); + return; + } + var headers = new Metadata(); + headers.put(HEADER, credential); + applier.apply(headers); + } + + @Override + public void thisUsesUnstableApi() {} + + @Override + public String toString() { + return "SelectedPublicationCallCredentials[redacted]"; + } + }; + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-publication credential metadata"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java new file mode 100644 index 0000000000..93c01ecb90 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed producer transport. Credential data never appears in responses or diagnostics. */ +public final class AccountSelectedPublicationOrderGrpcCodec { + public static final int MAX_CREDENTIAL_BYTES = 16384; + public static final int MAX_SELECTION_BYTES = 1048576; + + private AccountSelectedPublicationOrderGrpcCodec() {} + + public record Request( + int schemaVersion, + String targetNamespace, + UUID requestId, + byte[] originalSelection, + String originalCreatorCredential) { + public Request { + if (schemaVersion != 1 + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || requestId == null + || requestId.equals(new UUID(0, 0))) { + throw invalid(); + } + if (originalSelection == null + || originalSelection.length == 0 + || originalSelection.length > MAX_SELECTION_BYTES + || originalCreatorCredential == null + || originalCreatorCredential.isEmpty() + || originalCreatorCredential.length() > MAX_CREDENTIAL_BYTES + || originalCreatorCredential.chars().anyMatch(c -> c <= 32 || c >= 127)) { + throw invalid(); + } + originalSelection = originalSelection.clone(); + var selection = decodeSelection(originalSelection); + if (!Arrays.equals(originalSelection, selection.canonicalBytes())) throw invalid(); + } + + public static Request create( + String namespace, AuthoredDraftPublishSelectionBinding selection, String credential) { + return new Request(1, namespace, UUID.randomUUID(), selection.canonicalBytes(), credential); + } + + @Override + public byte[] originalSelection() { + return originalSelection.clone(); + } + + public AuthoredDraftPublishSelectionBinding selection() { + return decodeSelection(originalSelection); + } + + @Override + public String toString() { + return "AccountSelectedPublicationOrder.Request[redacted]"; + } + } + + public static AuthorizeSelectedPublicationRequest toRequest(Request request) { + Objects.requireNonNull(request); + return AuthorizeSelectedPublicationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .build(); + } + + /** Invoke only after authenticating the exact same-namespace Game Design workload. */ + public static Request fromRequest(AuthorizeSelectedPublicationRequest wire, String credential) { + try { + noUnknown(wire); + UUID id = UUID.fromString(wire.getRequestId()); + if (!id.toString().equals(wire.getRequestId())) throw invalid(); + return new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + id, + wire.getOriginalSelection().toByteArray(), + credential); + } catch (RuntimeException malformed) { + // Do not retain a parsing cause that could contain credential-bearing request data. + throw invalid(); + } + } + + public static AuthorizeSelectedPublicationResponse toResponse( + Request request, AccountPublicationAuthorizationBinding binding) { + requireSelection(request, binding); + return AuthorizeSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .setPublicationAuthorizationBinding(ByteString.copyFrom(binding.canonicalBytes())) + .build(); + } + + public static AccountPublicationAuthorizationBinding fromResponse( + Request request, AuthorizeSelectedPublicationResponse wire) { + try { + noUnknown(wire); + if (wire.getSchemaVersion() != request.schemaVersion() + || !wire.getTargetNamespace().equals(request.targetNamespace()) + || !wire.getRequestId().equals(request.requestId().toString()) + || !Arrays.equals(wire.getOriginalSelection().toByteArray(), request.originalSelection()) + || wire.getPublicationAuthorizationBinding().size() > MAX_SELECTION_BYTES) + throw invalid(); + var binding = + AccountPublicationAuthorizationBinding.fromStored( + wire.getPublicationAuthorizationBinding().toByteArray()); + requireSelection(request, binding); + return binding; + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static void requireSelection( + Request request, AccountPublicationAuthorizationBinding binding) { + if (binding == null + || !Arrays.equals( + request.originalSelection(), binding.input().selection().canonicalBytes())) + throw invalid(); + } + + private static AuthoredDraftPublishSelectionBinding decodeSelection(byte[] bytes) { + try { + return AuthoredDraftPublishSelectionBinding.fromStored( + new String(bytes, StandardCharsets.UTF_8), DraftAuthorizationFenceBinding.digest(bytes)); + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static void noUnknown(Message wire) { + if (wire == null || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-publication order transport evidence"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java new file mode 100644 index 0000000000..26d4ac5fde --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.common.publication; + +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Stub configuration/codec units; mocked channels do not prove an mTLS handshake. */ +class AccountSelectedPublicationOrderClientTest { + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var tls = tls(directory); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + tls.setPlaintext(false); + for (String bad : + new String[] { + null, + "", + "classpath:credential.pem", + directory.toString(), + directory.resolve("missing.pem").toString() + }) { + tls.setCertChain(bad); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var valid = tls(directory); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), valid, factory, "Test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void configuresExactAccountPeerDeadlineAndValidatesEchoOutsideSql(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + when(factory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new AccountSelectedPublicationOrderClient(endpoints, tls(directory), factory, "test"); + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), "original.secret.credential"); + try { + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + client.init(); + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + var initialized = (io.grpc.stub.AbstractStub) field.get(client); + var credentials = initialized.getCallOptions().getCredentials(); + assertThat(credentials).isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + var peerField = + GrpcServerPeerIdentityCallCredentials.class.getDeclaredField("expectedPeerUri"); + peerField.setAccessible(true); + assertThat(peerField.get(credentials)) + .isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + var stub = + mock( + AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withCallCredentials(any())).thenReturn(stub); + field.set(client, stub); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.clearSynchronization(); + var wrongNamespace = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "other", binding.input().selection(), "original.secret.credential"); + assertThatThrownBy(() -> client.authorize(wrongNamespace)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(stub); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + when(stub.authorizeSelectedPublication(any())).thenReturn(response); + assertThat(client.authorize(request).canonicalBytes()).isEqualTo(binding.canonicalBytes()); + verify(stub).withDeadlineAfter(5, TimeUnit.SECONDS); + var wire = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest.class); + verify(stub).authorizeSelectedPublication(wire.capture()); + assertThat(wire.getValue().toString()).doesNotContain(request.originalCreatorCredential()); + var perCall = org.mockito.ArgumentCaptor.forClass(io.grpc.CallCredentials.class); + verify(stub).withCallCredentials(perCall.capture()); + assertThat(perCall.getValue()).isInstanceOf(io.grpc.CompositeCallCredentials.class); + when(stub.authorizeSelectedPublication(any())) + .thenReturn(response.toBuilder().setTargetNamespace("other").build()); + assertThatThrownBy(() -> client.authorize(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageNotContaining(request.originalCreatorCredential()); + when(stub.authorizeSelectedPublication(any())) + .thenThrow( + io.grpc.Status.UNAVAILABLE + .withDescription(request.originalCreatorCredential()) + .asRuntimeException()); + assertThatThrownBy(() -> client.authorize(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageNotContaining(request.originalCreatorCredential()) + .hasNoCause(); + } finally { + client.close(); + } + assertThatThrownBy(client::init).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private-key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "ca").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java new file mode 100644 index 0000000000..a003a624f5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.common.publication; + +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.when; + +import io.grpc.CallCredentials; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import java.nio.charset.StandardCharsets; +import java.util.List; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationOrderCredentialsTest { + private static final String SECRET = "original.secret.credential"; + private static final Metadata.Key RAW = + Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + Metadata.BINARY_BYTE_MARSHALLER); + + @Test + void carrierAndWrapperAreRedactedAndApplyOnlyToProtectedExactMethod() { + var credentials = AccountSelectedPublicationOrderCredentials.forCall(SECRET); + assertThat(credentials.toString()).doesNotContain(SECRET); + assertThat(AccountSelectedPublicationOrderCredentials.Credential.of(SECRET).toString()) + .doesNotContain(SECRET); + var info = mock(CallCredentials.RequestInfo.class); + when(info.getSecurityLevel()).thenReturn(SecurityLevel.PRIVACY_AND_INTEGRITY); + org.mockito.Mockito.doReturn( + AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod()) + .when(info) + .getMethodDescriptor(); + var applier = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, applier); + var captured = org.mockito.ArgumentCaptor.forClass(Metadata.class); + verify(applier).apply(captured.capture()); + assertThat( + AccountSelectedPublicationOrderCredentials.readAuthenticated(captured.getValue()) + .value()) + .isEqualTo(SECRET); + for (var level : List.of(SecurityLevel.NONE, SecurityLevel.INTEGRITY)) { + when(info.getSecurityLevel()).thenReturn(level); + var denied = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, denied); + verify(denied) + .fail( + org.mockito.ArgumentMatchers.argThat( + status -> status.getCode() == io.grpc.Status.Code.UNAUTHENTICATED)); + } + when(info.getSecurityLevel()).thenReturn(SecurityLevel.PRIVACY_AND_INTEGRITY); + org.mockito.Mockito.doReturn( + AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod() + .toBuilder() + .setFullMethodName("different/Method") + .build()) + .when(info) + .getMethodDescriptor(); + var denied = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, denied); + verify(denied).fail(org.mockito.ArgumentMatchers.any()); + } + + @Test + void + authenticatedReadRejectsMissingDuplicateOversizedAndMalformedHeadersWithoutSecretDiagnostics() { + var missing = new Metadata(); + var duplicate = new Metadata(); + duplicate.put(RAW, SECRET.getBytes(StandardCharsets.US_ASCII)); + duplicate.put(RAW, SECRET.getBytes(StandardCharsets.US_ASCII)); + for (var headers : + List.of( + missing, + duplicate, + raw(new byte[0]), + raw(new byte[] {(byte) 128}), + raw((SECRET + "\n").getBytes(StandardCharsets.US_ASCII)), + raw(new byte[16385]))) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderCredentials.readAuthenticated(headers)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(SECRET) + .hasNoCause(); + } + var exact = + AccountSelectedPublicationOrderCredentials.readAuthenticated( + raw(SECRET.getBytes(StandardCharsets.US_ASCII))); + assertThat(exact.value()).isEqualTo(SECRET); + assertThat(exact.toString()).doesNotContain(SECRET); + } + + private static Metadata raw(byte[] bytes) { + var headers = new Metadata(); + headers.put(RAW, bytes); + return headers; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java new file mode 100644 index 0000000000..9b39340b8a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationOrderGrpcCodecTest { + private static final String CREDENTIAL = "original.secret.credential"; + + @Test + void preservesOriginalCredentialAndCanonicalSelectionWithoutEchoingSecret() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + var decoded = AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, CREDENTIAL); + assertThat(decoded.originalCreatorCredential()).isEqualTo(CREDENTIAL); + assertThat(decoded.originalSelection()).isEqualTo(request.originalSelection()); + assertThat(decoded.requestId()).isEqualTo(request.requestId()); + assertThat(decoded.toString()).doesNotContain(CREDENTIAL); + assertThat(wire.toString()).doesNotContain(CREDENTIAL); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + assertThat(response.toString()).doesNotContain(CREDENTIAL); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + var fresh = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse( + fresh, AccountSelectedPublicationOrderGrpcCodec.toResponse(fresh, binding)) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + } + + @Test + void rejectsUnknownNoncanonicalOversizedAndMissingRequestFieldsWithoutSecretDiagnostics() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + for (AuthorizeSelectedPublicationRequest invalid : + List.of( + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setRequestId("1-1-1-1-1").build(), + wire.toBuilder().setRequestId(new UUID(0, 0).toString()).build(), + wire.toBuilder().setRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA").build(), + wire.toBuilder().setUnknownFields(unknown()).build(), + wire.toBuilder().clearOriginalSelection().build(), + wire.toBuilder().setOriginalSelection(ByteString.copyFrom(new byte[1048577])).build(), + wire.toBuilder() + .setOriginalSelection( + wire.getOriginalSelection().concat(ByteString.copyFromUtf8(" "))) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderGrpcCodec.fromRequest(invalid, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + for (String invalid : List.of("", "x".repeat(16385), CREDENTIAL + "\n")) { + assertThatThrownBy(() -> AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, invalid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + } + + @Test + void rejectsChangedResponseEchoBindingAndUnknownFields() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + for (var invalid : + List.of( + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder().clearOriginalSelection().build(), + response.toBuilder().setUnknownFields(unknown()).build(), + response.toBuilder().clearPublicationAuthorizationBinding().build(), + response.toBuilder() + .setPublicationAuthorizationBinding(ByteString.copyFrom(new byte[] {1})) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java index 042d2ccc78..f92a8c58d1 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java @@ -18,8 +18,8 @@ import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; -import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java index 588133d367..f23215b237 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java @@ -27,8 +27,8 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; -import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; From e2bc4933957110de8ca9772950350bbefd2b26c5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:52:04 +1300 Subject: [PATCH 08/61] Align settlement ordering fixture with complete read correlation identities --- ...ctedDraftPublicationSettlementService.java | 7 +- ...horizationMtlsPostgresIntegrationTest.java | 73 +++++++++++++------ ...nAuthorizationPostgresIntegrationTest.java | 3 +- ...DraftPublicationSettlementServiceTest.java | 23 +++++- 4 files changed, 75 insertions(+), 31 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java index 52729abfb6..14ebe403b7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java @@ -3,11 +3,11 @@ import io.grpc.Status; import java.util.Arrays; import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; import org.springframework.transaction.PlatformTransactionManager; @@ -58,7 +58,8 @@ public byte[] settle(byte[] originalOperation) { throw new IllegalArgumentException("Exact original publication operation namespace required"); } var gameDesignRequest = - GameDesignPublicationTerminalReadEvidence.ReadRequest.create(workloadNamespace, operation.canonicalBytes()); + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + workloadNamespace, operation.canonicalBytes()); var gameDesign = gameDesignClient.read(gameDesignRequest); var terminal = gameDesign == null ? null : gameDesign.terminalEvidence().orElse(null); if (gameDesign == null || !gameDesignRequest.equals(gameDesign.request()) || terminal == null) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java index 85bf9e3102..3bd11eb575 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -25,7 +25,9 @@ import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -38,8 +40,6 @@ import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadGrpcCodec; import net.firedevops.firemud.test.TestContainerImages; @@ -65,7 +65,8 @@ class AccountPublicationAuthorizationMtlsPostgresIntegrationTest { private static final Network NETWORK = Network.newNetwork(); @Container - static final PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static final GenericContainer redis = @@ -392,50 +393,76 @@ void twoAuthenticatedTerminalOwnersSettleActualAccountOrderAndReadBackAfterCommi .GameDesignPublicationTerminalReadServiceImplBase() { @Override public void readGameDesignPublicationTerminal( - net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest wire, + net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest + wire, io.grpc.stub.StreamObserver< - net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalResponse> + net.firedevops.firemud.gamedesign.v1 + .ReadGameDesignPublicationTerminalResponse> observer) { try { requireAccountClient(); var request = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wire); gdReads.add(request.readRequestId().toString()); if (mode.get().equals("gd-missing")) throw Status.NOT_FOUND.asRuntimeException(); - if (mode.get().equals("gd-unavailable")) throw Status.UNAVAILABLE.asRuntimeException(); - var result = new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult( - request, - net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status.valueOf(terminal.outcome().name()), - java.util.Optional.of(terminal)); - var response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result).toBuilder(); - if (mode.get().startsWith("gd-") && !mode.get().equals("gd-missing") && !mode.get().equals("gd-unavailable")) { + if (mode.get().equals("gd-unavailable")) + throw Status.UNAVAILABLE.asRuntimeException(); + var result = + new net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadResult( + request, + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.Status.valueOf( + terminal.outcome().name()), + java.util.Optional.of(terminal)); + var response = + GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result) + .toBuilder(); + if (mode.get().startsWith("gd-") + && !mode.get().equals("gd-missing") + && !mode.get().equals("gd-unavailable")) { byte[] echoedRequest = request.canonicalBytes(); byte[] terminalBytes = terminal.canonicalBytes(); if (mode.get().equals("gd-correlation")) { - echoedRequest = new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest( - 1, request.targetNamespace(), UUID.randomUUID(), request.operationBytes()).canonicalBytes(); + echoedRequest = + new net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadRequest( + 1, + request.targetNamespace(), + UUID.randomUUID(), + request.operationBytes()) + .canonicalBytes(); } else if (mode.get().equals("gd-operation")) { var invalidRequest = new java.io.ByteArrayOutputStream(); - DraftAuthorizationFenceBinding.frame(invalidRequest, - net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest.SCHEMA); + DraftAuthorizationFenceBinding.frame( + invalidRequest, + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadRequest.SCHEMA); DraftAuthorizationFenceBinding.frame(invalidRequest, "1"); - DraftAuthorizationFenceBinding.frame(invalidRequest, request.targetNamespace()); - DraftAuthorizationFenceBinding.frame(invalidRequest, request.readRequestId().toString()); + DraftAuthorizationFenceBinding.frame( + invalidRequest, request.targetNamespace()); + DraftAuthorizationFenceBinding.frame( + invalidRequest, request.readRequestId().toString()); DraftAuthorizationFenceBinding.frame(invalidRequest, new byte[0]); echoedRequest = invalidRequest.toByteArray(); } else if (mode.get().equals("gd-unknown")) { var invalid = new java.io.ByteArrayOutputStream(); - DraftAuthorizationFenceBinding.frame(invalid, GameDesignPublicationTerminalEvidence.SCHEMA); + DraftAuthorizationFenceBinding.frame( + invalid, GameDesignPublicationTerminalEvidence.SCHEMA); DraftAuthorizationFenceBinding.frame(invalid, operation.canonicalBytes()); DraftAuthorizationFenceBinding.frame(invalid, "UNKNOWN"); terminalBytes = invalid.toByteArray(); } var invalidResponse = new java.io.ByteArrayOutputStream(); - DraftAuthorizationFenceBinding.frame(invalidResponse, - net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult.SCHEMA); + DraftAuthorizationFenceBinding.frame( + invalidResponse, + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadResult.SCHEMA); DraftAuthorizationFenceBinding.frame(invalidResponse, echoedRequest); - DraftAuthorizationFenceBinding.frame(invalidResponse, terminal.outcome().name()); + DraftAuthorizationFenceBinding.frame( + invalidResponse, terminal.outcome().name()); DraftAuthorizationFenceBinding.frame(invalidResponse, terminalBytes); - response.setCanonicalResponseBytes(com.google.protobuf.ByteString.copyFrom(invalidResponse.toByteArray())); + response.setCanonicalResponseBytes( + com.google.protobuf.ByteString.copyFrom(invalidResponse.toByteArray())); } observer.onNext(response.build()); observer.onCompleted(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index 6f5208f155..17add7af1e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -44,7 +44,8 @@ class AccountPublicationAuthorizationPostgresIntegrationTest { private static final Network NETWORK = Network.newNetwork(); @Container - static final PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static final GenericContainer redis = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java index a85039965e..1308014d88 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java @@ -18,11 +18,11 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; @@ -92,7 +92,8 @@ void agreeingOwnersCommitThenSeparatelyReadBackAndRetriesUseFreshReadCorrelation call -> { assertNoSql(); var request = - call.getArgument(0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class); + call.getArgument( + 0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class); gameDesignReads.add(request.readRequestId()); return gameDesignEvidence(request, fixture.terminal); }) @@ -156,7 +157,8 @@ void missingSubstitutedOrUnavailableGameDesignResultNeverReadsWorldOrWritesAccou doAnswer( call -> { var request = - call.getArgument(0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class); + call.getArgument( + 0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class); return gameDesignEvidence( new GameDesignPublicationTerminalReadEvidence.ReadRequest( 1, "test", UUID.randomUUID(), request.operationBytes()), @@ -321,6 +323,19 @@ private static final class CodecOutputs implements AutoCloseable { CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome outcome) { var world = mock(WorldPublishedStartLocationEvidence.class); + // Stipulated codec outputs include identities required by the current read correlation. + var account = mock(net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding.class); + var input = mock(net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding.PreallocationInput.class); + var selection = mock(net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.class); + var intent = mock(net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent.class); + when(operation.account()).thenReturn(account); + when(account.operationId()).thenReturn(UUID.randomUUID()); + when(account.fenceId()).thenReturn(UUID.randomUUID()); + when(account.input()).thenReturn(input); + when(input.selection()).thenReturn(selection); + when(selection.intent()).thenReturn(intent); + when(intent.selectedCommitRequestId()).thenReturn(UUID.randomUUID()); + when(intent.selectedCommitId()).thenReturn(UUID.randomUUID()); when(operation.canonicalBytes()).thenReturn(operationBytes); when(operation.world()).thenReturn(world); when(world.request()).thenReturn(worldRequest); From d9f734cc51d01ca9fde6582e832fea24e9b432d7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:57:36 +1300 Subject: [PATCH 09/61] Preserve passing publication owner fixture and correct tracker spacing --- .../player-access-and-session.md | 1 - ...DraftPublicationSettlementServiceTest.java | 19 +++++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) 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 43ceb1b2ee..c886b422a0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,6 @@ This is a non-normative implementation tracker for player access and session. Ca The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. Source/currentness, caller, retention and focused physical proof remain pending. These owners remain unregistered and grant no publication finalizer, player admission or runtime authority. - ### Selected recipient source intake preparation R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. R35 freshly passes the successor disclosure composition at the actual V1008–V1010 repository frontier, including physical source-writer exclusion until exact reservation abort; its static, formatting and documentation checks pass. The earlier V1007-only source proof retains separate R33 attribution. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority. diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java index 1308014d88..bb106f9ad1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java @@ -324,10 +324,21 @@ private static final class CodecOutputs implements AutoCloseable { CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome outcome) { var world = mock(WorldPublishedStartLocationEvidence.class); // Stipulated codec outputs include identities required by the current read correlation. - var account = mock(net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding.class); - var input = mock(net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding.PreallocationInput.class); - var selection = mock(net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.class); - var intent = mock(net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent.class); + var account = + mock( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding + .class); + var input = + mock( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding + .PreallocationInput.class); + var selection = + mock( + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.class); + var intent = + mock( + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding + .PublishIntent.class); when(operation.account()).thenReturn(account); when(account.operationId()).thenReturn(UUID.randomUUID()); when(account.fenceId()).thenReturn(UUID.randomUUID()); From 8eee2481469a070128b5958a33351bbd5a611b87 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:04:16 +1300 Subject: [PATCH 10/61] Compose actual Account and authenticated World admission in full owner proof --- ...nerPublicationPostgresIntegrationTest.java | 102 +++++++++++++----- ...electedFullPublicationEvidenceFixture.java | 43 +++++++- 2 files changed, 115 insertions(+), 30 deletions(-) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 2f2d3ca395..d268cca9ac 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -166,6 +166,17 @@ class SelectedFullOwnerPublicationPostgresIntegrationTest { static final PostgreSQLContainer GAME_LOGIC_POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + private static final org.testcontainers.containers.Network ACCOUNT_NETWORK = org.testcontainers.containers.Network.newNetwork(); + @Container static final PostgreSQLContainer ACCOUNT_POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container static final org.testcontainers.containers.GenericContainer ACCOUNT_REDIS = + new org.testcontainers.containers.GenericContainer<>(TestContainerImages.redis()) + .withNetwork(ACCOUNT_NETWORK).withNetworkAliases("selected-reservation-primary").withExposedPorts(6379) + .withCommand("redis-server", "--bind", "0.0.0.0", "--protected-mode", "no", "--appendonly", "yes", "--appendfsync", "always"); + @Container static final org.testcontainers.containers.GenericContainer ACCOUNT_REPLICA = + new org.testcontainers.containers.GenericContainer<>(TestContainerImages.redis()) + .withNetwork(ACCOUNT_NETWORK).dependsOn(ACCOUNT_REDIS) + .withCommand("redis-server", "--bind", "0.0.0.0", "--protected-mode", "no", "--appendonly", "yes", "--appendfsync", "always", "--replicaof", "selected-reservation-primary", "6379"); + @TempDir Path temporary; @Test @@ -182,9 +193,11 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema var worldSource = registerControlledWorldSource(gds, draft.target()); DraftCommitBinding commit = selectedCommit(gds, draft.target()); applyGameDesignCommit(gds, commit); + var delivery = new net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository(gds.dsl()) + .read(worldSource.operationId()).orElseThrow(); var worldGraph = WorldSelectedFullPublicationEvidenceFixture.applyGraph( - world.dsl(), world.transactions(), NAMESPACE, commit, worldSource); + world.dsl(), world.transactions(), NAMESPACE, commit, worldSource, delivery.request().intakeRequestId()); completeGameDesignCommit(gds, commit, worldGraph.applied()); String publishRequestId = "selected-full-" + UUID.randomUUID(); @@ -206,6 +219,15 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())) .reserve(intent) .selection()); + try (var accountFixture = new AccountControlUiOriginalOrderFixture( + ACCOUNT_POSTGRES.getJdbcUrl(), ACCOUNT_POSTGRES.getUsername(), ACCOUNT_POSTGRES.getPassword(), + ACCOUNT_REDIS.getHost(), ACCOUNT_REDIS.getMappedPort(6379), temporary.resolve("account-original"), draft.target().canonicalTenantId())) { + var issuedCreator = accountFixture.issueCreator(); + var accountSources = issuedCreator.sources(); + var publicationAuthorization = new AccountPublicationAuthorizationService(issuedCreator.actors(), accountSources.fences, + new AccountPublicationAuthorizationRepository(accountSources.dsl)).authorize( + issuedCreator.compact(), AuthoredDraftPublishSelectionBinding.fromStored(selection.canonicalJson(), selection.digest()), + issuedCreator.environment()); var worldOwners = WorldSelectedFullPublicationEvidenceFixture.applyFreezeAndCapture( world.dsl(), @@ -214,7 +236,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema AuthoredDraftPublishSelectionBinding.fromStored( selection.canonicalJson(), selection.digest()), worldGraph, - SelectedFullOwnerPublicationPostgresIntegrationTest::controlledAccountBinding); + ignored -> publicationAuthorization); assertThat(worldOwners.selectedWorldDigest().digestSchemaVersion()).isEqualTo(4); assertThat(worldOwners.appliedResultBytes()).isNotEmpty(); assertThat(worldOwners.graphBytes()).isNotEmpty(); @@ -342,22 +364,6 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema AuthoredDraftPublishSelectionBinding.fromStored( selection.canonicalJson(), selection.digest()); var accountBinding = worldOwners.accountBinding(); - var templateSourceRead = - new SelectedDraftTemplateWorldSourceAssociation.SourceRead( - worldOwners.sourceReadRequest(), worldOwners.sourceReadReceipt()); - var selectedOwnerReservation = - gds.write() - .execute( - ignored -> - new SelectedDraftPublicationOwner(gds.dsl()) - .reserve( - intent, - accountBinding, - worldOwners.startLocationEvidence(), - worldOwners.inventoryEvidence(), - templateSourceRead)); - assertThat(selectedOwnerReservation.selection().canonicalBytes()) - .containsExactly(selectionBinding.canonicalBytes()); Long gdsBundleBefore = gds.dsl() @@ -369,10 +375,23 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema assertThat(gdsBundleBefore).isZero(); ProofPki pki = new ProofPki(temporary.resolve("selected-full-pki")); + Server accountServer = null; + Server worldServer = null; Server entityServer = null; Server automationServer = null; Server gameLogicServer = null; + // This case recovers the exact already-committed World freeze. Mutable owner reads must not repeat. + var replaySelection = org.mockito.Mockito.mock(net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient.class); + var replayVersion = org.mockito.Mockito.mock(net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient.class); + var replayAccount = org.mockito.Mockito.mock(net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient.class); + var replaySource = org.mockito.Mockito.mock(net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient.class); try { + accountServer = ownerServer(pki, "account-service", new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService(new AccountPublicationAuthorizationRepository(accountSources.dsl), + accountSources.manager, NAMESPACE), NAMESPACE)); + var worldReaders = WorldSelectedFullPublicationEvidenceFixture.reservationReadEndpoints( + world.dsl(), world.transactions(), NAMESPACE, replaySelection, replayVersion, replayAccount, replaySource); + worldServer = ownerServer(pki, "world-management-service", worldReaders.toArray(io.grpc.BindableService[]::new)); entityServer = ownerServer( pki, @@ -408,11 +427,23 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema new net.firedevops.firemud.common.security.PublicationReadGuard(NAMESPACE))); var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService(loopback(accountServer)); + endpoints.setWorldManagementService(loopback(worldServer)); endpoints.setEntityManagementService(loopback(entityServer)); endpoints.setAutomationScriptingService(loopback(automationServer)); endpoints.setGameLogicService(loopback(gameLogicServer)); var channelFactory = new GrpcChannelFactory(); - try (var entityClient = + try (var accountClient = new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var freezeClient = new net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var inventoryClient = new net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var selectorClient = new net.firedevops.firemud.common.world.WorldPublishedStartLocationClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var sourceClient = new net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var entityClient = new ReadyEntityManagementClient( endpoints, pki.client("game-design-service"), channelFactory); var automationClient = @@ -421,6 +452,18 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema var gameLogicClient = new ReadyGameLogicClient( endpoints, pki.client("game-design-service"), channelFactory)) { + accountClient.init(); + freezeClient.init(); + inventoryClient.init(); + selectorClient.init(); + sourceClient.init(); + var admission = new net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationAdmissionService( + gds.dsl(), gds.transactions(), accountClient, freezeClient, inventoryClient, selectorClient, sourceClient, NAMESPACE); + var selectedOwnerReservation = admission.admitAndReserve(intent, accountBinding); + assertThat(selectedOwnerReservation.selection().canonicalBytes()).containsExactly(selectionBinding.canonicalBytes()); + var reservationReplay = admission.admitAndReserve(intent, accountBinding); + assertThat(reservationReplay.operation().canonicalBytes()).containsExactly(selectedOwnerReservation.operation().canonicalBytes()); + org.mockito.Mockito.verifyNoInteractions(replaySelection, replayVersion, replayAccount, replaySource); ReflectionTestUtils.setField(gameLogicClient, "workloadNamespace", NAMESPACE); entityClient.connect(); automationClient.connect(); @@ -657,11 +700,14 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); } } finally { + stop(accountServer); + stop(worldServer); stop(entityServer); stop(automationServer); stop(gameLogicServer); } } + } private static Draft createDraft(Store gds) { Version savedVersion = @@ -1097,18 +1143,14 @@ private static String loopback(Server server) { return "127.0.0.1:" + server.getPort(); } - private static Server ownerServer(ProofPki pki, String service, io.grpc.BindableService handler) + private static Server ownerServer(ProofPki pki, String service, io.grpc.BindableService... handlers) throws Exception { var identity = pki.server(service); - return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) - .trustManager(pki.ca().toFile()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())) - .build() - .start(); + var builder = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca().toFile()).clientAuth(ClientAuth.REQUIRE).build()); + for (var handler : handlers) builder.addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())); + return builder.build().start(); } private static void stop(Server server) throws InterruptedException { @@ -1260,6 +1302,8 @@ private static final class ProofPki { for (String service : List.of( "game-design-service", + "account-service", + "world-management-service", "entity-management-service", "automation-scripting-service", "game-logic-service")) { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java index 5e2a083f46..65a40de784 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java @@ -334,6 +334,15 @@ public static AppliedGraph applyGraph( String namespace, DraftCommitBinding selectedCommit, AuthoredWorldSourceEvidence controlledWorldSource) { + return applyGraph(worldDsl, worldTransactions, namespace, selectedCommit, controlledWorldSource, UUID.randomUUID()); + } + + /** Uses the existing GDS outbox's original World intake identity in composed proof. */ + public static AppliedGraph applyGraph( + DSLContext worldDsl, PlatformTransactionManager worldTransactions, String namespace, + DraftCommitBinding selectedCommit, AuthoredWorldSourceEvidence controlledWorldSource, + UUID originalIntakeRequestId) { + Objects.requireNonNull(originalIntakeRequestId, "originalIntakeRequestId"); Objects.requireNonNull(worldDsl, "worldDsl"); Objects.requireNonNull(worldTransactions, "worldTransactions"); Objects.requireNonNull(selectedCommit, "selectedCommit"); @@ -349,7 +358,7 @@ public static AppliedGraph applyGraph( write.execute( status -> intakeRepository.acceptFresh( - namespace, UUID.randomUUID(), controlledWorldSource))); + namespace, originalIntakeRequestId, controlledWorldSource))); var versionStateRequest = new AuthoredWorldVersionStateEvidence.Request( 1, @@ -568,4 +577,36 @@ private static WorldPublishedStartLocationEvidence publishedStartLocationEvidenc source.appliedResult().application().operation().accountBindingBytes(), source.appliedResult().canonicalBytes()); } + + /** Explicit test-only composition of existing readers; no runtime registration or authority. */ + public static java.util.List reservationReadEndpoints( + DSLContext dsl, PlatformTransactionManager transactions, String namespace, + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient selectionClient, + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient versionClient, + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient accountClient, + net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient sourceClient) { + var intake = new WorldAuthoredSourceIntakeRepository(dsl); + var fence = new WorldDesignPublicationFenceRepository(dsl, intake); + var topology = new WorldDraftTopologyCommitRepository(dsl, fence, JSON); + var applications = new WorldDraftGraphApplicationRepository(dsl, fence, JSON); + var digest = digestService(dsl); + var authorization = new WorldSelectedDraftPublicationAuthorizationRepository(dsl); + var inventory = new WorldSelectedPublicationArtifactInventoryRepository(dsl); + var frozen = new WorldCanonicalFrozenTopologyRepository( + dsl, new WorldAuthoredGraphSnapshotRepository(dsl), topology, digest); + var service = new WorldSelectedDraftPublicationFreezeService( + namespace, selectionClient, versionClient, accountClient, intake, fence, + new WorldSelectedDraftPublicationCheckpointRepository(fence, applications, topology, digest), + authorization, inventory, applications, + new WorldSelectedPublicationSelectorCapture(namespace, + new WorldCanonicalFrozenTopologyService(frozen, transactions)), transactions); + return java.util.List.of( + new WorldSelectedDraftPublicationFreezeGrpcService(service, + new WorldSelectedPublicationArtifactInventoryReadService(namespace, fence, authorization, inventory), namespace), + new WorldPublishedStartLocationReadGrpcService( + new WorldPublishedStartLocationRepository(dsl, frozen, applications), namespace), + new WorldAuthoredSourceIntakeGrpcService( + new WorldAuthoredSourceIntakeService(sourceClient, intake, transactions, namespace), namespace)); + } + } From 67067c94ba1abbe0f764e11fd7f7af22cb5e4611 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:08:44 +1300 Subject: [PATCH 11/61] Record Account native qualification and format composed reservation proof --- ...ame-authoring-publishing-and-activation.md | 4 +- .../player-access-and-session.md | 2 +- ...nerPublicationPostgresIntegrationTest.java | 1104 +++++++++-------- ...electedFullPublicationEvidenceFixture.java | 63 +- 4 files changed, 649 insertions(+), 524 deletions(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index e1cb4ad0ef..0af0981100 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for game authoring, publishing, a ### Selected publication reservation preparation -An unregistered reservation adapter independently reads the retained selection, exact Account HELD evidence, World freeze/inventory/selector and original World source/delivery before the existing local reservation transaction. Its ten focused ordering/refusal units and GDS static/format/docs pass; remote inputs remain transport doubles, not physical authenticated admission. The coherent continuation includes the missing Account selected-publication producer, HELD read, typed order transport and exact terminal-settlement owner over existing V93 storage; current-contract reconciliation and their focused/native proof remain pending. No migration or parallel terminal codec is introduced. Current client types and binding guards remain authoritative. This does not supply through-commit Account protection, failed-selection recovery, a reachable publication finalizer or a production entrypoint; fresh/PENDING publication and runtime authority remain denied. +An unregistered reservation adapter independently reads the retained selection, exact Account HELD evidence, World freeze/inventory/selector and original World source/delivery before the existing local reservation transaction. Its ten focused ordering/refusal units pass. The coherent continuation includes Account's missing selected-publication producer, HELD read, typed order transport and exact terminal-settlement owner over existing V93 storage. R4 freshly passes eleven Account PostgreSQL cases, including three authenticated both-owner settlement cases, with zero failures, errors or skips. Common's seven typed-order units and Account's twenty-five owner units pass. Scoped static, formatting and documentation checks pass. No migration or parallel terminal codec is introduced; current client types and binding guards remain authoritative. + +The existing Full composition is extended in source to use a sixth actual Account store and its normal Redis issuance fixture, authenticated Account HELD and World committed-freeze replay/read endpoints before the real GDS reservation. This composed proof is not yet qualified; the ten adapter units use transport doubles. Controlled upstream creator, issuer, environment and PKI are not genuine runtime authority. These unregistered components do not supply accepted through-commit Account protection, failed-selection recovery, a reachable publication finalizer or a production entrypoint; fresh/PENDING publication and runtime authority remain denied. ### Selected-full owner publication preparation 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 c886b422a0..237da1c590 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected publication owner preparation -The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. Source/currentness, caller, retention and focused physical proof remain pending. These owners remain unregistered and grant no publication finalizer, player admission or runtime authority. +The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. R4 freshly passes all eleven focused PostgreSQL cases, including three real mTLS both-owner settlement cases, with zero failures, errors or skips. Account's twenty-five focused units and Common's seven typed-order units pass; affected static, formatting and documentation checks pass. Passive capture owns both exact run-created PostgreSQL containers without ownership gaps or observer errors. Original caller/currentness and byte-correlated terminal refusal are component proof under controlled creator, issuer, environment and PKI. These owners remain unregistered and grant no publication finalizer, player admission, genuine authority or runtime activation. ### Selected recipient source intake preparation diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index d268cca9ac..bddae913f5 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -76,8 +76,6 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; -import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; -import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; @@ -166,16 +164,48 @@ class SelectedFullOwnerPublicationPostgresIntegrationTest { static final PostgreSQLContainer GAME_LOGIC_POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); - private static final org.testcontainers.containers.Network ACCOUNT_NETWORK = org.testcontainers.containers.Network.newNetwork(); - @Container static final PostgreSQLContainer ACCOUNT_POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); - @Container static final org.testcontainers.containers.GenericContainer ACCOUNT_REDIS = + private static final org.testcontainers.containers.Network ACCOUNT_NETWORK = + org.testcontainers.containers.Network.newNetwork(); + + @Container + static final PostgreSQLContainer ACCOUNT_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final org.testcontainers.containers.GenericContainer ACCOUNT_REDIS = new org.testcontainers.containers.GenericContainer<>(TestContainerImages.redis()) - .withNetwork(ACCOUNT_NETWORK).withNetworkAliases("selected-reservation-primary").withExposedPorts(6379) - .withCommand("redis-server", "--bind", "0.0.0.0", "--protected-mode", "no", "--appendonly", "yes", "--appendfsync", "always"); - @Container static final org.testcontainers.containers.GenericContainer ACCOUNT_REPLICA = + .withNetwork(ACCOUNT_NETWORK) + .withNetworkAliases("selected-reservation-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final org.testcontainers.containers.GenericContainer ACCOUNT_REPLICA = new org.testcontainers.containers.GenericContainer<>(TestContainerImages.redis()) - .withNetwork(ACCOUNT_NETWORK).dependsOn(ACCOUNT_REDIS) - .withCommand("redis-server", "--bind", "0.0.0.0", "--protected-mode", "no", "--appendonly", "yes", "--appendfsync", "always", "--replicaof", "selected-reservation-primary", "6379"); + .withNetwork(ACCOUNT_NETWORK) + .dependsOn(ACCOUNT_REDIS) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "selected-reservation-primary", + "6379"); @TempDir Path temporary; @@ -193,11 +223,19 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema var worldSource = registerControlledWorldSource(gds, draft.target()); DraftCommitBinding commit = selectedCommit(gds, draft.target()); applyGameDesignCommit(gds, commit); - var delivery = new net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository(gds.dsl()) - .read(worldSource.operationId()).orElseThrow(); + var delivery = + new net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository( + gds.dsl()) + .read(worldSource.operationId()) + .orElseThrow(); var worldGraph = WorldSelectedFullPublicationEvidenceFixture.applyGraph( - world.dsl(), world.transactions(), NAMESPACE, commit, worldSource, delivery.request().intakeRequestId()); + world.dsl(), + world.transactions(), + NAMESPACE, + commit, + worldSource, + delivery.request().intakeRequestId()); completeGameDesignCommit(gds, commit, worldGraph.applied()); String publishRequestId = "selected-full-" + UUID.randomUUID(); @@ -219,495 +257,559 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())) .reserve(intent) .selection()); - try (var accountFixture = new AccountControlUiOriginalOrderFixture( - ACCOUNT_POSTGRES.getJdbcUrl(), ACCOUNT_POSTGRES.getUsername(), ACCOUNT_POSTGRES.getPassword(), - ACCOUNT_REDIS.getHost(), ACCOUNT_REDIS.getMappedPort(6379), temporary.resolve("account-original"), draft.target().canonicalTenantId())) { - var issuedCreator = accountFixture.issueCreator(); - var accountSources = issuedCreator.sources(); - var publicationAuthorization = new AccountPublicationAuthorizationService(issuedCreator.actors(), accountSources.fences, - new AccountPublicationAuthorizationRepository(accountSources.dsl)).authorize( - issuedCreator.compact(), AuthoredDraftPublishSelectionBinding.fromStored(selection.canonicalJson(), selection.digest()), - issuedCreator.environment()); - var worldOwners = - WorldSelectedFullPublicationEvidenceFixture.applyFreezeAndCapture( - world.dsl(), - world.transactions(), - NAMESPACE, - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson(), selection.digest()), - worldGraph, - ignored -> publicationAuthorization); - assertThat(worldOwners.selectedWorldDigest().digestSchemaVersion()).isEqualTo(4); - assertThat(worldOwners.appliedResultBytes()).isNotEmpty(); - assertThat(worldOwners.graphBytes()).isNotEmpty(); - assertThat(worldOwners.inventoryEvidence().freezeEvidence()) - .isEqualTo(worldOwners.freezeEvidence()); - - var sourceScopeActor = UUID.randomUUID(); - var entityAuthorization = - selectedOwnerAuthorization(gds, selection, Owner.ENTITY_MANAGEMENT, sourceScopeActor); - var entityWorldRead = - SelectedOwnerWorldInventoryReadEvidence.create( - NAMESPACE, entityAuthorization, worldOwners.freezeEvidence()); - var entityInputs = - new SelectedOwnerEmptySourceInputs( - entityAuthorization, - new SelectedOwnerWorldInventoryReadEvidence( - entityWorldRead, worldOwners.inventoryEvidence())); - var entityRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); - var entityReceipt = - entityRepository.retainFresh( - entityInputs, - EntityEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())); - assertThat( - entityRepository - .read(entityReceipt.targetNamespace(), entityReceipt.intakeRequestId()) - .orElseThrow() - .canonicalBytes()) - .containsExactly(entityReceipt.canonicalBytes()); - assertThat( - entityRepository - .retainFresh( - entityInputs, - EntityEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())) - .canonicalBytes()) - .containsExactly(entityReceipt.canonicalBytes()); - - var automationAuthorization = - selectedOwnerAuthorization(gds, selection, Owner.AUTOMATION_SCRIPTING, sourceScopeActor); - var automationWorldRead = - SelectedOwnerWorldInventoryReadEvidence.create( - NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()); - var automationInputs = - new SelectedOwnerEmptySourceInputs( - automationAuthorization, - new SelectedOwnerWorldInventoryReadEvidence( - automationWorldRead, worldOwners.inventoryEvidence())); - var automationRepository = new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); - var automationReceipt = - automationRepository.retainFresh( - automationInputs, - net.firedevops.firemud.common.automation.sourceintake - .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())); - assertThat( - automationRepository - .read(automationReceipt.targetNamespace(), automationReceipt.intakeRequestId()) - .orElseThrow() - .canonicalBytes()) - .containsExactly(automationReceipt.canonicalBytes()); - assertThat( - automationRepository - .retainFresh( - automationInputs, - net.firedevops.firemud.common.automation.sourceintake - .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())) - .canonicalBytes()) - .containsExactly(automationReceipt.canonicalBytes()); - - var synchronizedSources = - new GameDesignSourceRepository(gds.dsl()) - .readSynchronized(draft.target(), commit.commitId()) - .orElseThrow(); - var gameplaySnapshot = synchronizedSources.gameplayEvidence().orElseThrow(); - var gameplaySource = new GameplayRuleSelectedSource(gameplaySnapshot.canonicalJson()); - var glAuthorization = - new GameLogicIntakeAuthorizationBinding( - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - sourceScopeActor, - gameplaySource, - controlledAccountSources(sourceScopeActor, draft.target().canonicalTenantId())); - var glOperation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, glAuthorization); - var glTerminal = - GameLogicGameplayRuleIntakeTerminal.retained( - glOperation, - gameplaySource.canonicalBytes(), - gameplaySource.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); - var glOwner = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); - gameLogic - .write() - .execute( - ignored -> { - glOwner.lockOperation(glAuthorization.operationId()); - glOwner.insertTerminal(glTerminal); - return null; - }); - var committedGlTerminal = glOwner.findTerminal(glAuthorization.operationId()).orElseThrow(); - assertThat(committedGlTerminal.canonicalBytes()).containsExactly(glTerminal.canonicalBytes()); - - var selectedReceiptRepository = new SelectedDraftGameLogicReceiptRepository(gds.dsl()); - var glReceiptCandidate = - new SelectedDraftGameLogicReceipt( - selection, - glAuthorization, - new AccountGameLogicIntakeSettlementEvidence(committedGlTerminal)); - var glReceipt = - gds.write().execute(ignored -> selectedReceiptRepository.retain(glReceiptCandidate)); - assertThat( - selectedReceiptRepository - .readForPublication( - PublicationDigestRequestBinding.full( - draft.target().canonicalTenantId().toString(), - Long.toString(draft.version().getId()), - publishRequestId)) - .orElseThrow() - .receipt() - .canonicalBytes()) - .containsExactly(glReceipt.receipt().canonicalBytes()); - - var selectionBinding = - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson(), selection.digest()); - var accountBinding = worldOwners.accountBinding(); - - Long gdsBundleBefore = - gds.dsl() - .fetchSingle( - "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", - draft.version().getTenantId(), - draft.version().getId()) - .get(0, Long.class); - assertThat(gdsBundleBefore).isZero(); - - ProofPki pki = new ProofPki(temporary.resolve("selected-full-pki")); - Server accountServer = null; - Server worldServer = null; - Server entityServer = null; - Server automationServer = null; - Server gameLogicServer = null; - // This case recovers the exact already-committed World freeze. Mutable owner reads must not repeat. - var replaySelection = org.mockito.Mockito.mock(net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient.class); - var replayVersion = org.mockito.Mockito.mock(net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient.class); - var replayAccount = org.mockito.Mockito.mock(net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient.class); - var replaySource = org.mockito.Mockito.mock(net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient.class); - try { - accountServer = ownerServer(pki, "account-service", new AccountPublicationAuthorizationReadGrpcService( - new AccountPublicationAuthorizationReadService(new AccountPublicationAuthorizationRepository(accountSources.dsl), - accountSources.manager, NAMESPACE), NAMESPACE)); - var worldReaders = WorldSelectedFullPublicationEvidenceFixture.reservationReadEndpoints( - world.dsl(), world.transactions(), NAMESPACE, replaySelection, replayVersion, replayAccount, replaySource); - worldServer = ownerServer(pki, "world-management-service", worldReaders.toArray(io.grpc.BindableService[]::new)); - entityServer = - ownerServer( - pki, - "entity-management-service", - new EntitySelectedEmptyPublicationDigestGrpcReceiver( - new EntitySelectedEmptyPublicationDigestService(NAMESPACE, entityRepository), - NAMESPACE, - new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); - automationServer = - ownerServer( - pki, - "automation-scripting-service", - new AutomationSelectedEmptyPublicationDigestGrpcReceiver( - new AutomationSelectedEmptyPublicationDigestService( - NAMESPACE, automationRepository), - NAMESPACE, - new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); - gameLogicServer = - ownerServer( - pki, - "game-logic-service", - new GameLogicGrpcService( + try (var accountFixture = + new AccountControlUiOriginalOrderFixture( + ACCOUNT_POSTGRES.getJdbcUrl(), + ACCOUNT_POSTGRES.getUsername(), + ACCOUNT_POSTGRES.getPassword(), + ACCOUNT_REDIS.getHost(), + ACCOUNT_REDIS.getMappedPort(6379), + temporary.resolve("account-original"), + draft.target().canonicalTenantId())) { + var issuedCreator = accountFixture.issueCreator(); + var accountSources = issuedCreator.sources(); + var publicationAuthorization = + new AccountPublicationAuthorizationService( + issuedCreator.actors(), + accountSources.fences, + new AccountPublicationAuthorizationRepository(accountSources.dsl)) + .authorize( + issuedCreator.compact(), + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + issuedCreator.environment()); + var worldOwners = + WorldSelectedFullPublicationEvidenceFixture.applyFreezeAndCapture( + world.dsl(), + world.transactions(), + NAMESPACE, + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + worldGraph, + ignored -> publicationAuthorization); + assertThat(worldOwners.selectedWorldDigest().digestSchemaVersion()).isEqualTo(4); + assertThat(worldOwners.appliedResultBytes()).isNotEmpty(); + assertThat(worldOwners.graphBytes()).isNotEmpty(); + assertThat(worldOwners.inventoryEvidence().freezeEvidence()) + .isEqualTo(worldOwners.freezeEvidence()); + + var sourceScopeActor = UUID.randomUUID(); + var entityAuthorization = + selectedOwnerAuthorization(gds, selection, Owner.ENTITY_MANAGEMENT, sourceScopeActor); + var entityWorldRead = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence()); + var entityInputs = + new SelectedOwnerEmptySourceInputs( + entityAuthorization, + new SelectedOwnerWorldInventoryReadEvidence( + entityWorldRead, worldOwners.inventoryEvidence())); + var entityRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); + var entityReceipt = + entityRepository.retainFresh( + entityInputs, + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())); + assertThat( + entityRepository + .read(entityReceipt.targetNamespace(), entityReceipt.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + assertThat( + entityRepository + .retainFresh( + entityInputs, + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())) + .canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + + var automationAuthorization = + selectedOwnerAuthorization(gds, selection, Owner.AUTOMATION_SCRIPTING, sourceScopeActor); + var automationWorldRead = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()); + var automationInputs = + new SelectedOwnerEmptySourceInputs( + automationAuthorization, + new SelectedOwnerWorldInventoryReadEvidence( + automationWorldRead, worldOwners.inventoryEvidence())); + var automationRepository = + new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); + var automationReceipt = + automationRepository.retainFresh( + automationInputs, + net.firedevops.firemud.common.automation.sourceintake + .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())); + assertThat( + automationRepository + .read(automationReceipt.targetNamespace(), automationReceipt.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + assertThat( + automationRepository + .retainFresh( + automationInputs, + net.firedevops.firemud.common.automation.sourceintake + .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())) + .canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + + var synchronizedSources = + new GameDesignSourceRepository(gds.dsl()) + .readSynchronized(draft.target(), commit.commitId()) + .orElseThrow(); + var gameplaySnapshot = synchronizedSources.gameplayEvidence().orElseThrow(); + var gameplaySource = new GameplayRuleSelectedSource(gameplaySnapshot.canonicalJson()); + var glAuthorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + sourceScopeActor, + gameplaySource, + controlledAccountSources(sourceScopeActor, draft.target().canonicalTenantId())); + var glOperation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, glAuthorization); + var glTerminal = + GameLogicGameplayRuleIntakeTerminal.retained( + glOperation, + gameplaySource.canonicalBytes(), + gameplaySource.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var glOwner = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); + gameLogic + .write() + .execute( + ignored -> { + glOwner.lockOperation(glAuthorization.operationId()); + glOwner.insertTerminal(glTerminal); + return null; + }); + var committedGlTerminal = glOwner.findTerminal(glAuthorization.operationId()).orElseThrow(); + assertThat(committedGlTerminal.canonicalBytes()).containsExactly(glTerminal.canonicalBytes()); + + var selectedReceiptRepository = new SelectedDraftGameLogicReceiptRepository(gds.dsl()); + var glReceiptCandidate = + new SelectedDraftGameLogicReceipt( + selection, + glAuthorization, + new AccountGameLogicIntakeSettlementEvidence(committedGlTerminal)); + var glReceipt = + gds.write().execute(ignored -> selectedReceiptRepository.retain(glReceiptCandidate)); + assertThat( + selectedReceiptRepository + .readForPublication( + PublicationDigestRequestBinding.full( + draft.target().canonicalTenantId().toString(), + Long.toString(draft.version().getId()), + publishRequestId)) + .orElseThrow() + .receipt() + .canonicalBytes()) + .containsExactly(glReceipt.receipt().canonicalBytes()); + + var selectionBinding = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + var accountBinding = worldOwners.accountBinding(); + + Long gdsBundleBefore = + gds.dsl() + .fetchSingle( + "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + draft.version().getTenantId(), + draft.version().getId()) + .get(0, Long.class); + assertThat(gdsBundleBefore).isZero(); + + ProofPki pki = new ProofPki(temporary.resolve("selected-full-pki")); + Server accountServer = null; + Server worldServer = null; + Server entityServer = null; + Server automationServer = null; + Server gameLogicServer = null; + // This case recovers the exact already-committed World freeze. Mutable owner reads must not + // repeat. + var replaySelection = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient + .class); + var replayVersion = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient.class); + var replayAccount = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient + .class); + var replaySource = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient.class); + try { + accountServer = + ownerServer( + pki, + "account-service", + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + new AccountPublicationAuthorizationRepository(accountSources.dsl), + accountSources.manager, + NAMESPACE), + NAMESPACE)); + var worldReaders = + WorldSelectedFullPublicationEvidenceFixture.reservationReadEndpoints( + world.dsl(), + world.transactions(), + NAMESPACE, + replaySelection, + replayVersion, + replayAccount, + replaySource); + worldServer = + ownerServer( + pki, + "world-management-service", + worldReaders.toArray(io.grpc.BindableService[]::new)); + entityServer = + ownerServer( + pki, + "entity-management-service", + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + new EntitySelectedEmptyPublicationDigestService(NAMESPACE, entityRepository), + NAMESPACE, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); + automationServer = + ownerServer( + pki, + "automation-scripting-service", + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + new AutomationSelectedEmptyPublicationDigestService( + NAMESPACE, automationRepository), + NAMESPACE, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); + gameLogicServer = + ownerServer( + pki, + "game-logic-service", + new GameLogicGrpcService( + null, + null, + null, + null, + null, + null, + new GameLogicDraftDesignDigestServiceImpl( + new GameLogicPublicationSourceReadService(glOwner, NAMESPACE)), + null, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry(), + new net.firedevops.firemud.common.security.PublicationReadGuard(NAMESPACE))); + + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService(loopback(accountServer)); + endpoints.setWorldManagementService(loopback(worldServer)); + endpoints.setEntityManagementService(loopback(entityServer)); + endpoints.setAutomationScriptingService(loopback(automationServer)); + endpoints.setGameLogicService(loopback(gameLogicServer)); + var channelFactory = new GrpcChannelFactory(); + try (var accountClient = + new net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var freezeClient = + new net.firedevops.firemud.common.publication + .WorldSelectedDraftPublicationFreezeClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var inventoryClient = + new net.firedevops.firemud.common.publication + .WorldSelectedPublicationArtifactInventoryClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var selectorClient = + new net.firedevops.firemud.common.world.WorldPublishedStartLocationClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var sourceClient = + new net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var entityClient = + new ReadyEntityManagementClient( + endpoints, pki.client("game-design-service"), channelFactory); + var automationClient = + new ReadyAutomationScriptingClient( + endpoints, pki.client("game-design-service"), channelFactory); + var gameLogicClient = + new ReadyGameLogicClient( + endpoints, pki.client("game-design-service"), channelFactory)) { + accountClient.init(); + freezeClient.init(); + inventoryClient.init(); + selectorClient.init(); + sourceClient.init(); + var admission = + new net.firedevops.firemud.gamedesign.publication + .SelectedDraftPublicationAdmissionService( + gds.dsl(), + gds.transactions(), + accountClient, + freezeClient, + inventoryClient, + selectorClient, + sourceClient, + NAMESPACE); + var selectedOwnerReservation = admission.admitAndReserve(intent, accountBinding); + assertThat(selectedOwnerReservation.selection().canonicalBytes()) + .containsExactly(selectionBinding.canonicalBytes()); + var reservationReplay = admission.admitAndReserve(intent, accountBinding); + assertThat(reservationReplay.operation().canonicalBytes()) + .containsExactly(selectedOwnerReservation.operation().canonicalBytes()); + org.mockito.Mockito.verifyNoInteractions( + replaySelection, replayVersion, replayAccount, replaySource); + ReflectionTestUtils.setField(gameLogicClient, "workloadNamespace", NAMESPACE); + entityClient.connect(); + automationClient.connect(); + gameLogicClient.connect(); + var gate = + new PublishGateServiceImpl( null, null, + entityClient, + gameLogicClient, + automationClient, + gds.dsl(), + gds.transactions(), + NAMESPACE); + VersionDto versionDto = versionDto(draft.version()); + var publicationRequest = + PublicationDigestRequestBinding.full( + draft.target().canonicalTenantId().toString(), + Long.toString(draft.version().getId()), + publishRequestId); + var participantDigests = + gate.collectSelectedFullVersionParticipantDigests( + versionDto, publicationRequest, publicationRequest.derivedWorkflowIdentity()); + assertThat(participantDigests) + .extracting(PublishParticipantDigestDto::participantKey) + .containsExactly( + "WORLD_MANAGEMENT", + "ENTITY_MANAGEMENT", + "GAME_LOGIC", + "AUTOMATION_SCRIPTING", + "GAME_DESIGN_CONTROL_PLANE"); + assertThat(participantDigests) + .extracting(PublishParticipantDigestDto::digestSchemaVersion) + .containsExactly(4, 3, 1, 6, 2); + assertThat(participantDigests) + .filteredOn(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey())) + .singleElement() + .satisfies( + digest -> + assertThat(digest.contentDigest()) + .isEqualTo(worldOwners.selectedWorldDigest().contentDigest())); + assertThat(participantDigests) + .filteredOn(digest -> "GAME_LOGIC".equals(digest.participantKey())) + .singleElement() + .satisfies(digest -> assertThat(digest.abilitySchemaDigest()).startsWith("sha256:")); + gate.assertSelectedGatePassed(versionDto, participantDigests); + + var altered = new ArrayList<>(participantDigests); + int automationIndex = 3; + var validAutomation = altered.get(automationIndex); + altered.set( + automationIndex, + new PublishParticipantDigestDto( + validAutomation.participantKey(), + validAutomation.scopeValue(), + validAutomation.baseVersionId(), + validAutomation.appliedCommitId(), + validAutomation.contentDigest(), + 5, + validAutomation.abilitySchemaDigest(), + validAutomation.errorCode(), + validAutomation.errorMessage())); + gate.assertSelectedGatePassed(versionDto, participantDigests); + assertThatThrownBy(() -> gate.assertSelectedGatePassed(versionDto, altered)) + .isInstanceOf(RuntimeException.class); + + var releaseService = + new PublishedReleaseBundleServiceImpl( + new PublishedReleaseBundleRepository(gds.dsl()), + new VersionRepository(gds.dsl()), + new ObjectMapper()); + var controlledEmptyManifest = controlledEmptyManifest(); + var artifactRepository = + new net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository( + gds.dsl()); + var versions = new VersionRepository(gds.dsl()); + var artifactService = + new net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl( + artifactRepository, null, + versions, null, null, null, - new GameLogicDraftDesignDigestServiceImpl( - new GameLogicPublicationSourceReadService(glOwner, NAMESPACE)), null, - new io.micrometer.core.instrument.simple.SimpleMeterRegistry(), - new net.firedevops.firemud.common.security.PublicationReadGuard(NAMESPACE))); - - var endpoints = new ServiceEndpointsProperties(); - endpoints.setAccountService(loopback(accountServer)); - endpoints.setWorldManagementService(loopback(worldServer)); - endpoints.setEntityManagementService(loopback(entityServer)); - endpoints.setAutomationScriptingService(loopback(automationServer)); - endpoints.setGameLogicService(loopback(gameLogicServer)); - var channelFactory = new GrpcChannelFactory(); - try (var accountClient = new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient( - endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); - var freezeClient = new net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient( - endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); - var inventoryClient = new net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient( - endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); - var selectorClient = new net.firedevops.firemud.common.world.WorldPublishedStartLocationClient( - endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); - var sourceClient = new net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient( - endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); - var entityClient = - new ReadyEntityManagementClient( - endpoints, pki.client("game-design-service"), channelFactory); - var automationClient = - new ReadyAutomationScriptingClient( - endpoints, pki.client("game-design-service"), channelFactory); - var gameLogicClient = - new ReadyGameLogicClient( - endpoints, pki.client("game-design-service"), channelFactory)) { - accountClient.init(); - freezeClient.init(); - inventoryClient.init(); - selectorClient.init(); - sourceClient.init(); - var admission = new net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationAdmissionService( - gds.dsl(), gds.transactions(), accountClient, freezeClient, inventoryClient, selectorClient, sourceClient, NAMESPACE); - var selectedOwnerReservation = admission.admitAndReserve(intent, accountBinding); - assertThat(selectedOwnerReservation.selection().canonicalBytes()).containsExactly(selectionBinding.canonicalBytes()); - var reservationReplay = admission.admitAndReserve(intent, accountBinding); - assertThat(reservationReplay.operation().canonicalBytes()).containsExactly(selectedOwnerReservation.operation().canonicalBytes()); - org.mockito.Mockito.verifyNoInteractions(replaySelection, replayVersion, replayAccount, replaySource); - ReflectionTestUtils.setField(gameLogicClient, "workloadNamespace", NAMESPACE); - entityClient.connect(); - automationClient.connect(); - gameLogicClient.connect(); - var gate = - new PublishGateServiceImpl( - null, - null, - entityClient, - gameLogicClient, - automationClient, - gds.dsl(), - gds.transactions(), - NAMESPACE); - VersionDto versionDto = versionDto(draft.version()); - var publicationRequest = - PublicationDigestRequestBinding.full( - draft.target().canonicalTenantId().toString(), - Long.toString(draft.version().getId()), - publishRequestId); - var participantDigests = - gate.collectSelectedFullVersionParticipantDigests( - versionDto, publicationRequest, publicationRequest.derivedWorkflowIdentity()); - assertThat(participantDigests) - .extracting(PublishParticipantDigestDto::participantKey) - .containsExactly( - "WORLD_MANAGEMENT", - "ENTITY_MANAGEMENT", - "GAME_LOGIC", - "AUTOMATION_SCRIPTING", - "GAME_DESIGN_CONTROL_PLANE"); - assertThat(participantDigests) - .extracting(PublishParticipantDigestDto::digestSchemaVersion) - .containsExactly(4, 3, 1, 6, 2); - assertThat(participantDigests) - .filteredOn(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey())) - .singleElement() - .satisfies( - digest -> - assertThat(digest.contentDigest()) - .isEqualTo(worldOwners.selectedWorldDigest().contentDigest())); - assertThat(participantDigests) - .filteredOn(digest -> "GAME_LOGIC".equals(digest.participantKey())) - .singleElement() - .satisfies(digest -> assertThat(digest.abilitySchemaDigest()).startsWith("sha256:")); - gate.assertSelectedGatePassed(versionDto, participantDigests); - - var altered = new ArrayList<>(participantDigests); - int automationIndex = 3; - var validAutomation = altered.get(automationIndex); - altered.set( - automationIndex, - new PublishParticipantDigestDto( - validAutomation.participantKey(), - validAutomation.scopeValue(), - validAutomation.baseVersionId(), - validAutomation.appliedCommitId(), - validAutomation.contentDigest(), - 5, - validAutomation.abilitySchemaDigest(), - validAutomation.errorCode(), - validAutomation.errorMessage())); - gate.assertSelectedGatePassed(versionDto, participantDigests); - assertThatThrownBy(() -> gate.assertSelectedGatePassed(versionDto, altered)) - .isInstanceOf(RuntimeException.class); - - var releaseService = - new PublishedReleaseBundleServiceImpl( - new PublishedReleaseBundleRepository(gds.dsl()), - new VersionRepository(gds.dsl()), - new ObjectMapper()); - var controlledEmptyManifest = controlledEmptyManifest(); - var artifactRepository = - new net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository( - gds.dsl()); - var versions = new VersionRepository(gds.dsl()); - var artifactService = - new net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl( - artifactRepository, - null, - versions, - null, - null, - null, - null, - null, - new ObjectMapper()); - var assetPublication = - new net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository( - gds.dsl()); - var exportSnapshot = - gds.write() - .execute( - ignored -> - assetPublication.freezeOrReadSnapshot( - versionDto.tenantId(), versionDto.versionNumber())); - assertThat(exportSnapshot.items()).isEmpty(); - gds.write() - .execute( - ignored -> - artifactService.stageExport( - versionDto.tenantId(), - versionDto.id(), - versionDto.versionNumber(), - publicationRequest.derivedWorkflowIdentity())); - var candidateService = - new net.firedevops.firemud.gamedesign.service.impl - .VersionAssetExportCandidateServiceImpl( - versions, - new GameRepository(gds.dsl()), - new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( - gds.dsl()), - artifactRepository, - assetPublication, - gds.transactions(), - new ObjectMapper()); - // Controlled delivery origin and manifest metadata; no object-store or public delivery - // proof. - var candidate = - new net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate( - controlledEmptyManifest, "https://controlled.invalid/assets"); - assertThat( - candidateService.recordExportCandidate( - versionDto.tenantId(), versionDto.versionNumber(), candidate)) - .isEqualTo(candidate); - assertThat( - candidateService.readExportCandidate( - versionDto.tenantId(), versionDto.versionNumber())) - .isEqualTo(candidate); - assertThatThrownBy( - () -> - gds.write() - .execute( - ignored -> - releaseService.createFullVersionBundle( - versionDto, - publicationRequest.derivedWorkflowIdentity(), - controlledEmptyManifest, - "controlled-generation-input", - altered, - worldOwners.startLocationEvidence()))) - .isInstanceOf(RuntimeException.class); - assertThat( - gds.dsl() - .fetchSingle( - "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", - draft.version().getTenantId(), - draft.version().getId()) - .get(0, Long.class)) - .isZero(); - - PublishedReleaseBundleService releaseOwner = releaseService; - var written = - gds.write() - .execute( - ignored -> { - String workflow = publicationRequest.derivedWorkflowIdentity(); - var exported = - artifactService.markExportedUnattested( - versionDto.tenantId(), - versionDto.id(), - versionDto.versionNumber(), - workflow, - controlledEmptyManifest); - var result = + null, + new ObjectMapper()); + var assetPublication = + new net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository( + gds.dsl()); + var exportSnapshot = + gds.write() + .execute( + ignored -> + assetPublication.freezeOrReadSnapshot( + versionDto.tenantId(), versionDto.versionNumber())); + assertThat(exportSnapshot.items()).isEmpty(); + gds.write() + .execute( + ignored -> + artifactService.stageExport( + versionDto.tenantId(), + versionDto.id(), + versionDto.versionNumber(), + publicationRequest.derivedWorkflowIdentity())); + var candidateService = + new net.firedevops.firemud.gamedesign.service.impl + .VersionAssetExportCandidateServiceImpl( + versions, + new GameRepository(gds.dsl()), + new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( + gds.dsl()), + artifactRepository, + assetPublication, + gds.transactions(), + new ObjectMapper()); + // Controlled delivery origin and manifest metadata; no object-store or public delivery + // proof. + var candidate = + new net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate( + controlledEmptyManifest, "https://controlled.invalid/assets"); + assertThat( + candidateService.recordExportCandidate( + versionDto.tenantId(), versionDto.versionNumber(), candidate)) + .isEqualTo(candidate); + assertThat( + candidateService.readExportCandidate( + versionDto.tenantId(), versionDto.versionNumber())) + .isEqualTo(candidate); + assertThatThrownBy( + () -> + gds.write() + .execute( + ignored -> + releaseService.createFullVersionBundle( + versionDto, + publicationRequest.derivedWorkflowIdentity(), + controlledEmptyManifest, + "controlled-generation-input", + altered, + worldOwners.startLocationEvidence()))) + .isInstanceOf(RuntimeException.class); + assertThat( + gds.dsl() + .fetchSingle( + "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + draft.version().getTenantId(), + draft.version().getId()) + .get(0, Long.class)) + .isZero(); + + PublishedReleaseBundleService releaseOwner = releaseService; + var written = + gds.write() + .execute( + ignored -> { + String workflow = publicationRequest.derivedWorkflowIdentity(); + var exported = + artifactService.markExportedUnattested( + versionDto.tenantId(), + versionDto.id(), + versionDto.versionNumber(), + workflow, + controlledEmptyManifest); + var result = + releaseOwner.createFullVersionBundle( + versionDto, + workflow, + controlledEmptyManifest, + "controlled-generation-input", + participantDigests, + worldOwners.startLocationEvidence()); + var version = + versions + .findByTenantIdAndIdForUpdate( + versionDto.tenantId(), versionDto.id()) + .orElseThrow(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch( + Math.addExact(version.getVersionStateEpoch(), 1L)); + versions.save(version); + artifactService.markPublished( + versionDto.tenantId(), + versionDto.id(), + exported.stateEpoch(), + workflow, + controlledEmptyManifest.manifestHash()); + var attempts = + new net.firedevops.firemud.gamedesign.repository + .PublishAttemptRepository(gds.dsl()); + var attempt = + attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow(); + attempt.setStatus( + net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); + attempts.save(attempt); + var operation = selectedOwnerReservation.operation(); + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationOperationRepository(gds.dsl()) + .seal( + operation.tenantKey(), + workflow, + operation.versionId(), + operation.selectionDigest(), + true); + return result; + }); + assertThat(written.attestationSchemaVersion()).isEqualTo("v4"); + assertThat(written.participantDigests()).containsExactlyElementsOf(participantDigests); + assertThat(written.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(worldOwners.startLocationEvidence().canonicalBytes()); + String committedBundleRow = bundleOwnerRow(gds, draft.version()); + var independentRead = + new PublishedReleaseBundleServiceImpl( + new PublishedReleaseBundleRepository(gds.dsl()), + new VersionRepository(gds.dsl()), + new ObjectMapper()) + .findPublishedReleaseBundle( + draft.version().getTenantId(), draft.version().getId()) + .orElseThrow(); + assertThat(independentRead).isEqualTo(written); + assertThat(independentRead.attestationSchemaVersion()).isEqualTo("v4"); + assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + + var replay = + gds.write() + .execute( + ignored -> releaseOwner.createFullVersionBundle( versionDto, - workflow, + publicationRequest.derivedWorkflowIdentity(), controlledEmptyManifest, "controlled-generation-input", participantDigests, - worldOwners.startLocationEvidence()); - var version = - versions - .findByTenantIdAndIdForUpdate(versionDto.tenantId(), versionDto.id()) - .orElseThrow(); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch( - Math.addExact(version.getVersionStateEpoch(), 1L)); - versions.save(version); - artifactService.markPublished( - versionDto.tenantId(), - versionDto.id(), - exported.stateEpoch(), - workflow, - controlledEmptyManifest.manifestHash()); - var attempts = - new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( - gds.dsl()); - var attempt = - attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow(); - attempt.setStatus( - net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); - attempts.save(attempt); - var operation = selectedOwnerReservation.operation(); - new net.firedevops.firemud.gamedesign.publication - .GameDesignPublicationOperationRepository(gds.dsl()) - .seal( - operation.tenantKey(), - workflow, - operation.versionId(), - operation.selectionDigest(), - true); - return result; - }); - assertThat(written.attestationSchemaVersion()).isEqualTo("v4"); - assertThat(written.participantDigests()).containsExactlyElementsOf(participantDigests); - assertThat(written.worldPublishedStartLocationEvidence().canonicalBytes()) - .containsExactly(worldOwners.startLocationEvidence().canonicalBytes()); - String committedBundleRow = bundleOwnerRow(gds, draft.version()); - var independentRead = - new PublishedReleaseBundleServiceImpl( - new PublishedReleaseBundleRepository(gds.dsl()), - new VersionRepository(gds.dsl()), - new ObjectMapper()) - .findPublishedReleaseBundle(draft.version().getTenantId(), draft.version().getId()) - .orElseThrow(); - assertThat(independentRead).isEqualTo(written); - assertThat(independentRead.attestationSchemaVersion()).isEqualTo("v4"); - assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); - - var replay = - gds.write() - .execute( - ignored -> - releaseOwner.createFullVersionBundle( - versionDto, - publicationRequest.derivedWorkflowIdentity(), - controlledEmptyManifest, - "controlled-generation-input", - participantDigests, - worldOwners.startLocationEvidence())); - assertThat(replay).isEqualTo(written); - assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + worldOwners.startLocationEvidence())); + assertThat(replay).isEqualTo(written); + assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + } + } finally { + stop(accountServer); + stop(worldServer); + stop(entityServer); + stop(automationServer); + stop(gameLogicServer); } - } finally { - stop(accountServer); - stop(worldServer); - stop(entityServer); - stop(automationServer); - stop(gameLogicServer); } } - } private static Draft createDraft(Store gds) { Version savedVersion = @@ -1036,17 +1138,6 @@ private static void completeGameDesignCommit( }); } - private static AccountPublicationAuthorizationBinding controlledAccountBinding( - AuthoredDraftPublishSelectionBinding selection) { - UUID actor = UUID.randomUUID(); - var input = new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection); - return new AccountPublicationAuthorizationBinding( - UUID.randomUUID(), - UUID.randomUUID(), - input, - controlledAccountSources(actor, selection.intent().canonicalTenantId())); - } - private static SelectedOwnerIntakeAuthorizationBinding selectedOwnerAuthorization( Store gds, AuthoredDraftPublishSelection selection, Owner recipient, UUID actor) { var scope = @@ -1143,13 +1234,18 @@ private static String loopback(Server server) { return "127.0.0.1:" + server.getPort(); } - private static Server ownerServer(ProofPki pki, String service, io.grpc.BindableService... handlers) - throws Exception { + private static Server ownerServer( + ProofPki pki, String service, io.grpc.BindableService... handlers) throws Exception { var identity = pki.server(service); - var builder = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext(GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) - .trustManager(pki.ca().toFile()).clientAuth(ClientAuth.REQUIRE).build()); - for (var handler : handlers) builder.addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())); + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + for (var handler : handlers) + builder.addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())); return builder.build().start(); } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java index 65a40de784..54580dff9f 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java @@ -334,13 +334,22 @@ public static AppliedGraph applyGraph( String namespace, DraftCommitBinding selectedCommit, AuthoredWorldSourceEvidence controlledWorldSource) { - return applyGraph(worldDsl, worldTransactions, namespace, selectedCommit, controlledWorldSource, UUID.randomUUID()); + return applyGraph( + worldDsl, + worldTransactions, + namespace, + selectedCommit, + controlledWorldSource, + UUID.randomUUID()); } /** Uses the existing GDS outbox's original World intake identity in composed proof. */ public static AppliedGraph applyGraph( - DSLContext worldDsl, PlatformTransactionManager worldTransactions, String namespace, - DraftCommitBinding selectedCommit, AuthoredWorldSourceEvidence controlledWorldSource, + DSLContext worldDsl, + PlatformTransactionManager worldTransactions, + String namespace, + DraftCommitBinding selectedCommit, + AuthoredWorldSourceEvidence controlledWorldSource, UUID originalIntakeRequestId) { Objects.requireNonNull(originalIntakeRequestId, "originalIntakeRequestId"); Objects.requireNonNull(worldDsl, "worldDsl"); @@ -580,10 +589,14 @@ private static WorldPublishedStartLocationEvidence publishedStartLocationEvidenc /** Explicit test-only composition of existing readers; no runtime registration or authority. */ public static java.util.List reservationReadEndpoints( - DSLContext dsl, PlatformTransactionManager transactions, String namespace, - net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient selectionClient, + DSLContext dsl, + PlatformTransactionManager transactions, + String namespace, + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient + selectionClient, net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient versionClient, - net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient accountClient, + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient + accountClient, net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient sourceClient) { var intake = new WorldAuthoredSourceIntakeRepository(dsl); var fence = new WorldDesignPublicationFenceRepository(dsl, intake); @@ -592,21 +605,35 @@ public static java.util.List reservationReadEndpoints( var digest = digestService(dsl); var authorization = new WorldSelectedDraftPublicationAuthorizationRepository(dsl); var inventory = new WorldSelectedPublicationArtifactInventoryRepository(dsl); - var frozen = new WorldCanonicalFrozenTopologyRepository( - dsl, new WorldAuthoredGraphSnapshotRepository(dsl), topology, digest); - var service = new WorldSelectedDraftPublicationFreezeService( - namespace, selectionClient, versionClient, accountClient, intake, fence, - new WorldSelectedDraftPublicationCheckpointRepository(fence, applications, topology, digest), - authorization, inventory, applications, - new WorldSelectedPublicationSelectorCapture(namespace, - new WorldCanonicalFrozenTopologyService(frozen, transactions)), transactions); + var frozen = + new WorldCanonicalFrozenTopologyRepository( + dsl, new WorldAuthoredGraphSnapshotRepository(dsl), topology, digest); + var service = + new WorldSelectedDraftPublicationFreezeService( + namespace, + selectionClient, + versionClient, + accountClient, + intake, + fence, + new WorldSelectedDraftPublicationCheckpointRepository( + fence, applications, topology, digest), + authorization, + inventory, + applications, + new WorldSelectedPublicationSelectorCapture( + namespace, new WorldCanonicalFrozenTopologyService(frozen, transactions)), + transactions); return java.util.List.of( - new WorldSelectedDraftPublicationFreezeGrpcService(service, - new WorldSelectedPublicationArtifactInventoryReadService(namespace, fence, authorization, inventory), namespace), + new WorldSelectedDraftPublicationFreezeGrpcService( + service, + new WorldSelectedPublicationArtifactInventoryReadService( + namespace, fence, authorization, inventory), + namespace), new WorldPublishedStartLocationReadGrpcService( new WorldPublishedStartLocationRepository(dsl, frozen, applications), namespace), new WorldAuthoredSourceIntakeGrpcService( - new WorldAuthoredSourceIntakeService(sourceClient, intake, transactions, namespace), namespace)); + new WorldAuthoredSourceIntakeService(sourceClient, intake, transactions, namespace), + namespace)); } - } From b1c90ed7bcc17f6dc664445ccbfb938bf8259645 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:12:19 +1300 Subject: [PATCH 12/61] Record actual six-store admission qualification and its authority limits --- .../game-authoring-publishing-and-activation.md | 6 ++++-- .../implementation-tracking/player-access-and-session.md | 2 +- ...SelectedFullOwnerPublicationPostgresIntegrationTest.java | 1 - 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 0af0981100..511100827c 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,9 +8,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ### Selected publication reservation preparation -An unregistered reservation adapter independently reads the retained selection, exact Account HELD evidence, World freeze/inventory/selector and original World source/delivery before the existing local reservation transaction. Its ten focused ordering/refusal units pass. The coherent continuation includes Account's missing selected-publication producer, HELD read, typed order transport and exact terminal-settlement owner over existing V93 storage. R4 freshly passes eleven Account PostgreSQL cases, including three authenticated both-owner settlement cases, with zero failures, errors or skips. Common's seven typed-order units and Account's twenty-five owner units pass. Scoped static, formatting and documentation checks pass. No migration or parallel terminal codec is introduced; current client types and binding guards remain authoritative. +An unregistered reservation adapter independently reads the retained selection, exact Account HELD evidence, World freeze/inventory/selector and original World source/delivery before the existing local reservation transaction. Its ten focused ordering/refusal units pass. The coherent continuation includes Account's missing selected-publication producer, HELD read, typed order transport and exact terminal-settlement owner over existing V93 storage. R4 freshly passes eleven Account PostgreSQL cases, including three mTLS cases for the order producer, HELD reads and settlement, with zero failures, errors or skips. Common's seven typed-order units and Account's twenty-five owner units pass. Scoped static, formatting and documentation checks pass. No migration or parallel terminal codec is introduced; current client types and binding guards remain authoritative. -The existing Full composition is extended in source to use a sixth actual Account store and its normal Redis issuance fixture, authenticated Account HELD and World committed-freeze replay/read endpoints before the real GDS reservation. This composed proof is not yet qualified; the ten adapter units use transport doubles. Controlled upstream creator, issuer, environment and PKI are not genuine runtime authority. These unregistered components do not supply accepted through-commit Account protection, failed-selection recovery, a reachable publication finalizer or a production entrypoint; fresh/PENDING publication and runtime authority remain denied. +R6 freshly passes the extended Full PostgreSQL composition with zero failures, errors or skips. It uses a sixth actual Account store and its normal Redis issuance fixture, authenticated Account HELD and World committed-freeze replay/read endpoints before real GDS admission/reservation and exact reservation retry. The original GDS delivery intake identity is preserved through World application; mutable World retry readers are asserted unused. The existing atomic v4 bundle/terminal commit and immutable readback still execute. Passive capture owns all six exact run-created PostgreSQL containers with zero ownership gaps or observer errors. R6's only gate failure is an unused Java import after removing a now-obsolete controlled Account binding helper; its native and static cases pass. R7 passes canonical formatting and documentation checks after that import-only correction; the successful native proof retains R6 attribution. + +The World freeze was previously committed by the actual fixture; this case does not prove a fresh authenticated World begin. Account's settlement proof controls the two remote terminal owners. Upstream creator, issuer, environment, PKI and other declared source/candidate inputs remain controlled. These unregistered components do not supply accepted through-commit Account protection, failed-selection recovery, a reachable publication finalizer or a production entrypoint; fresh/PENDING publication and runtime authority remain denied. All genuine Gameplay handoffs remain open. ### Selected-full owner publication preparation 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 237da1c590..f614570b53 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected publication owner preparation -The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. R4 freshly passes all eleven focused PostgreSQL cases, including three real mTLS both-owner settlement cases, with zero failures, errors or skips. Account's twenty-five focused units and Common's seven typed-order units pass; affected static, formatting and documentation checks pass. Passive capture owns both exact run-created PostgreSQL containers without ownership gaps or observer errors. Original caller/currentness and byte-correlated terminal refusal are component proof under controlled creator, issuer, environment and PKI. These owners remain unregistered and grant no publication finalizer, player admission, genuine authority or runtime activation. +The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. R4 freshly passes all eleven focused PostgreSQL cases, including three mTLS cases for the order producer, HELD reads and settlement, with zero failures, errors or skips. Account's twenty-five focused units and Common's seven typed-order units pass; affected static, formatting and documentation checks pass. Passive capture owns both exact run-created PostgreSQL containers without ownership gaps or observer errors. Original caller/currentness and byte-correlated terminal refusal are component proof under controlled creator, issuer, environment and PKI; the Account settlement test controls both remote terminal owners. These owners remain unregistered and grant no publication finalizer, player admission, genuine authority or runtime activation. ### Selected recipient source intake preparation diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index bddae913f5..9b244e6920 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -53,7 +53,6 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; -import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; From aa9743f201d997d9e9f39565818d06dc6e0e5e17 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:17:35 +1300 Subject: [PATCH 13/61] Prove Account settlement against actual GDS and World terminal owners --- ...nerPublicationPostgresIntegrationTest.java | 154 ++++++++++++++++++ 1 file changed, 154 insertions(+) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 9b244e6920..f291799b6e 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -52,6 +52,7 @@ import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; @@ -799,6 +800,14 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema worldOwners.startLocationEvidence())); assertThat(replay).isEqualTo(written); assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + completeActualWorldAndAccountTerminals( + gds, + world, + accountSources.dsl, + accountSources.manager, + pki, + selectedOwnerReservation.operation()); + assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); } } finally { stop(accountServer); @@ -810,6 +819,151 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema } } + /** + * Actual immutable owner terminals; the local Account caller context is explicitly controlled. + */ + private static void completeActualWorldAndAccountTerminals( + Store gds, + Store world, + org.jooq.DSLContext accountDsl, + org.springframework.transaction.PlatformTransactionManager accountTransactions, + ProofPki pki, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation) + throws Exception { + var gdsOwner = + new net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationService( + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationOperationRepository(gds.dsl()), + gds.transactions()); + Server gdsTerminalServer = + ownerServer( + pki, + "game-design-service", + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationTerminalReadGrpcService(gdsOwner, NAMESPACE)); + Server worldTerminalServer = null; + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService(loopback(gdsTerminalServer)); + var channels = new GrpcChannelFactory(); + try (var worldGdsRead = + new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + worldGdsRead.init(); + var worldRepository = + new net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalRepository( + world.dsl(), world.transactions()); + var worldOwner = + net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalService + .authenticated(worldRepository, worldGdsRead, NAMESPACE); + worldTerminalServer = + ownerServer( + pki, + "world-management-service", + new net.firedevops.firemud.worldmanagement.tenant + .WorldPublicationTerminalCompletionGrpcService(worldOwner, NAMESPACE), + new net.firedevops.firemud.worldmanagement.tenant + .WorldPublicationTerminalReadGrpcService( + new net.firedevops.firemud.worldmanagement.tenant + .WorldPublicationTerminalReadService(worldRepository, NAMESPACE), + NAMESPACE)); + endpoints.setWorldManagementService(loopback(worldTerminalServer)); + try (var accountGdsRead = + new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var accountWorldRead = + new net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var producer = + net.firedevops.firemud.gamedesign.publication + .GameDesignWorldPublicationTerminalProducer.usingFileBackedMtls( + gdsOwner, endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + accountGdsRead.init(); + accountWorldRead.init(); + var accountOwner = + new AccountSelectedDraftPublicationSettlementService( + new AccountPublicationAuthorizationRepository(accountDsl), + accountGdsRead, + accountWorldRead, + accountTransactions, + NAMESPACE); + var binding = + net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding + .fromStored(operation.canonicalBytes()); + var caller = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service") + .orElseThrow()); + // No caller transport is asserted here: this is the actual Account owner plus its two mTLS + // reads. + assertThatThrownBy(() -> caller.call(() -> accountOwner.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertThat( + accountDsl + .fetchSingle( + "SELECT count(*) FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, Long.class)) + .isZero(); + var published = + producer.reconcile( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence + .Outcome.PUBLISHED); + assertThat(published.operationBytes()).containsExactly(operation.canonicalBytes()); + assertThat( + producer + .reconcile( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + published.outcome()) + .canonicalBytes()) + .containsExactly(published.canonicalBytes()); + byte[] receipt = caller.call(() -> accountOwner.settle(operation.canonicalBytes())); + assertThat(receipt).isNotEmpty(); + String retained = + accountDsl + .fetchSingle( + "SELECT to_jsonb(s)::text || ':' || xmin::text FROM account_selected_publication_settlements s WHERE operation_id = ?", + binding.account().operationId()) + .get(0, String.class); + assertThat(caller.call(() -> accountOwner.settle(operation.canonicalBytes()))) + .containsExactly(receipt); + assertThat( + accountDsl + .fetchSingle( + "SELECT to_jsonb(s)::text || ':' || xmin::text FROM account_selected_publication_settlements s WHERE operation_id = ?", + binding.account().operationId()) + .get(0, String.class)) + .isEqualTo(retained); + assertThat( + accountDsl + .fetchSingle( + "SELECT game_design_terminal FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, byte[].class)) + .containsExactly(published.canonicalBytes()); + assertThat( + accountDsl + .fetchSingle( + "SELECT world_terminal FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, byte[].class)) + .containsExactly(published.canonicalBytes()); + } + } finally { + stop(worldTerminalServer); + stop(gdsTerminalServer); + } + } + private static Draft createDraft(Store gds) { Version savedVersion = gds.write() From de8860eb61ae80a660f6415ac374d93304ba6688 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:31:22 +1300 Subject: [PATCH 14/61] Converge Account settlement inventory to canonical selected closure profile --- design/project-management/ai-observations.md | 2 + ...selected_publication_closure_inventory.sql | 73 ++++++++++++++++ ...nAuthorizationPostgresIntegrationTest.java | 68 +++++++++++++++ ...nerPublicationPostgresIntegrationTest.java | 87 +++++++++++++++++++ 4 files changed, 230 insertions(+) create mode 100644 services/account-service/src/main/resources/db/migration/V1011__selected_publication_closure_inventory.sql diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 1fa88444b2..6f25569e82 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -346,3 +346,5 @@ Entry format: - `2026-10-16`: A multiline conflict-marker resolver truncated three trailing file portions during an unpublished selected-owner carry. Native `git merge-file` reconstruction from the exact parents recovered the complete files. Bound marker lines explicitly, verify conflict counts and file tails, and inspect the final net diff against both original parents before committing; a clean whitespace check alone cannot detect lost content. - 2026-10-15: Selected-full digest fixture R41/R42 produced different fixed-golden values from otherwise unchanged source. The fixture serialized `Map.of` payloads into strings inside a canonical binding; outer canonicalization preserves string contents and therefore does not normalize the inner map order. Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof. No production digest or retained bytes were changed. R44 and the fresh R45 JVM agree on the normalized vector; all 686 GDS unit cases pass in R45. + +- 2026-10-15: Separate selected-publication owner proofs missed an Account settlement profile gap. The actual GDS terminal → authenticated World completion → both real terminal reads composition reached Account V94 and failed with SQLSTATE 23514 because its inventory validator still admitted only inventory/1 + World/3, while the current canonical producer retains closure inventory/2 + World/4. Preserve that failed composition beside prior component passes; a forward validator correction needs exact profile/refusal and existing-settlement byte/row-version upgrade proof. Do not rewrite installed migrations or treat controlled terminal readbacks as actual producer composition. Correction and qualification are in progress. diff --git a/services/account-service/src/main/resources/db/migration/V1011__selected_publication_closure_inventory.sql b/services/account-service/src/main/resources/db/migration/V1011__selected_publication_closure_inventory.sql new file mode 100644 index 0000000000..2168ef26f4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1011__selected_publication_closure_inventory.sql @@ -0,0 +1,73 @@ +-- Preserve retained Account settlement rows and the original v1 inventory profile. Admit only the explicit closure-qualified v2 +-- profile. Publication-operation bytes and historical migration definitions remain immutable. +-- [jooq ignore start] +DO $migration$ +DECLARE + inventory_function REGPROCEDURE := + '"${serviceSchema}".require_selected_inventory_operation_v2(bytea)'::REGPROCEDURE; + original_definition TEXT; + model_shape_anchor TEXT := $anchor$ (model, ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'])$anchor$; + model_shape_replacement TEXT := $replacement$ (model, CASE + WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + THEN ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs','inboundSourceClosure'] + ELSE ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'] + END)$replacement$; + profile_anchor TEXT := $anchor$ OR inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$anchor$; + profile_replacement TEXT := $replacement$ OR (( + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v1' + AND inventory->'schemaVersion' = '1'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + AND model->'graphSchemaVersion' = '2'::JSONB + AND checkpoint->'digestSchemaVersion' = '3'::JSONB + AND selector->'request'->'digestSchemaVersion' = '3'::JSONB + AND NOT (model ? 'inboundSourceClosure') + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 16) + OR + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1' + AND model->'graphSchemaVersion' = '3'::JSONB + AND checkpoint->'digestSchemaVersion' = '4'::JSONB + AND selector->'request'->'digestSchemaVersion' = '4'::JSONB + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 17 + AND model ?& ARRAY['modelId', 'graphSchemaVersion', 'graphDigest', + 'topologyResultDigest', 'familyCounts', 'regionGeneratorInputs', + 'generationRuleFields', 'regionFields', 'zoneFields', 'roomFields', + 'roomExitFields', 'spawnBindingFields', 'spawnBindingInputs', + 'generationRuleInputCount', 'spawnBindingCount', 'appliedEpochs', + 'inboundSourceClosure'] + AND model->'inboundSourceClosure' IS NOT DISTINCT FROM + '{"schemaVersion":1,"familyCounts":[{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING","count":0}]}'::JSONB) + ) IS NOT TRUE) OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$replacement$; + model_count_anchor TEXT := $anchor$ OR (SELECT count(*) FROM jsonb_object_keys(model)) <> 16$anchor$; + model_count_replacement TEXT := $replacement$ OR (SELECT count(*) FROM jsonb_object_keys(model)) <> (CASE + WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB THEN 17 ELSE 16 END)$replacement$; + legacy_model_anchor TEXT := $anchor$ OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB$anchor$; +BEGIN + SELECT pg_get_functiondef(inventory_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, model_shape_anchor, ''))) + / length(model_shape_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, profile_anchor, ''))) + / length(profile_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, legacy_model_anchor, ''))) + / length(legacy_model_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, model_count_anchor, ''))) + / length(model_count_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact Account V94 inventory profile and complete model guards'; + END IF; + original_definition := replace(original_definition, model_shape_anchor, model_shape_replacement); + original_definition := replace(original_definition, profile_anchor, profile_replacement); + -- The paired profile guard above checks both model identifiers and graph schemas. Keep the + -- generation-rule and artifact-decision restrictions below unchanged for both profiles. + original_definition := replace(original_definition, legacy_model_anchor, ''); + original_definition := replace(original_definition, model_count_anchor, model_count_replacement); + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index 17add7af1e..74f59e9470 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -1008,6 +1008,74 @@ void actualSourceWriterBlocksCreatorCaptureThenWinsBeforePublication() throws Ex } } + @Test + void closureInventoryUpgradePreservesOriginalLegacySettlementsAndExactReplay() throws Exception { + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + java.time.Clock.systemUTC(), + "1010")) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var terminal = terminal(operation, outcome); + String phase = + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + byte[] receipt = + f.tx(() -> repository.settle(operation, terminal, phase, terminal.canonicalBytes())); + var before = publicationRetentionRows(f.dsl); + f.upgradeToCurrent(); + assertThat(publicationRetentionRows(f.dsl)).isEqualTo(before); + f.dsl.fetch( + "SELECT require_selected_inventory_operation_v2(?::bytea)", operation.canonicalBytes()); + assertThat( + f.tx( + () -> repository.settle(operation, terminal, phase, terminal.canonicalBytes()))) + .containsExactly(receipt); + assertThat(publicationRetentionRows(f.dsl)).isEqualTo(before); + } + } + } + + private static java.util.Map> publicationRetentionRows( + org.jooq.DSLContext dsl) { + var result = new java.util.LinkedHashMap>(); + for (String table : + java.util.List.of( + "account_selected_publication_authorizations", + "account_selected_publication_sources", + "account_selected_publication_settlements", + "account_control_ui_issuance_operations", + "flyway_schema_history")) { + String filter = + table.equals("flyway_schema_history") ? " WHERE version IS DISTINCT FROM '1011'" : ""; + result.put( + table, + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM " + + table + + " r" + + filter + + " ORDER BY 1") + .getValues(0, String.class)); + } + return result; + } + private AccountControlUiOriginalOrderFixture fixture() throws Exception { return new AccountControlUiOriginalOrderFixture( postgres.getJdbcUrl(), diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index f291799b6e..0fd48595d2 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -830,6 +830,7 @@ private static void completeActualWorldAndAccountTerminals( ProofPki pki, net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation) throws Exception { + requireAccountClosureInventoryRefusals(accountDsl, operation); var gdsOwner = new net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationService( new net.firedevops.firemud.gamedesign.publication @@ -964,6 +965,92 @@ private static void completeActualWorldAndAccountTerminals( } } + private static void requireAccountClosureInventoryRefusals( + org.jooq.DSLContext dsl, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation) + throws Exception { + dsl.fetch( + "SELECT require_selected_inventory_operation_v2(?::bytea)", operation.canonicalBytes()); + var mapper = new ObjectMapper(); + java.util.List> changes = + java.util.List.of( + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("sourceModel")) + .remove("inboundSourceClosure"), + tree -> + ((tools.jackson.databind.node.ObjectNode) + tree.at("/sourceModel/inboundSourceClosure/familyCounts/0")) + .put("count", 1), + tree -> + ((tools.jackson.databind.node.ArrayNode) + tree.at("/sourceModel/inboundSourceClosure/familyCounts")) + .remove(6), + tree -> { + var families = + (tools.jackson.databind.node.ArrayNode) + tree.at("/sourceModel/inboundSourceClosure/familyCounts"); + families.add(families.remove(0)); + }, + tree -> + ((tools.jackson.databind.node.ObjectNode) + tree.at("/sourceModel/inboundSourceClosure")) + .put("unknown", 1), + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("sourceModel")) + .put("unknown", 1), + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("sourceModel")) + .put("graphSchemaVersion", 2), + tree -> tree.put("schemaVersion", 1), + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("checkpoint")) + .put("digestSchemaVersion", 3)); + var before = + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM account_selected_publication_authorizations r ORDER BY 1") + .getValues(0, String.class); + for (var change : changes) { + var tree = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(operation.inventory().canonicalBytes()); + change.accept(tree); + byte[] inventory = mapper.writeValueAsBytes(tree); + var raw = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, + net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding.SCHEMA); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, operation.account().canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, operation.world().canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame(raw, inventory); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, + "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(inventory))); + assertThatThrownBy( + () -> + dsl.fetch( + "SELECT require_selected_inventory_operation_v2(?::bytea)", + raw.toByteArray())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .satisfies( + failure -> { + var cause = failure; + while (cause != null && !(cause instanceof java.sql.SQLException)) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(java.sql.SQLException.class); + assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("23514"); + }); + } + assertThat( + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM account_selected_publication_authorizations r ORDER BY 1") + .getValues(0, String.class)) + .isEqualTo(before); + } + private static Draft createDraft(Store gds) { Version savedVersion = gds.write() From 705207dd29d32e588303f1182676b69ba6a78dec Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:36:00 +1300 Subject: [PATCH 15/61] Allow exact pre-closure Account frontier in historical proof fixture --- .../service/session/AccountControlUiOwnerSourcesFixture.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 94bcb6acc7..0e668aa749 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -138,9 +138,10 @@ final class AccountControlUiOwnerSourcesFixture { && !"160.1".equals(migrationTarget) && !"1006".equals(migrationTarget) && !"1007".equals(migrationTarget) - && !"1009".equals(migrationTarget)) { + && !"1009".equals(migrationTarget) + && !"1010".equals(migrationTarget)) { throw new IllegalArgumentException( - "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, or 1009 selected-owner predecessor is supported"); + "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, 1009 selected-owner predecessor, or 1010 selected-publication closure predecessor is supported"); } this.tenant = Objects.requireNonNull(tenant); String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); From ba5866ef0734e9892f01adf2c802c241c68bfd49 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:37:43 +1300 Subject: [PATCH 16/61] Record actual publication settlement and retained-history qualification --- design/project-management/ai-observations.md | 2 ++ .../game-authoring-publishing-and-activation.md | 8 +++++--- .../implementation-tracking/player-access-and-session.md | 4 +++- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 6f25569e82..68b8ff9a4c 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -348,3 +348,5 @@ Entry format: - 2026-10-15: Selected-full digest fixture R41/R42 produced different fixed-golden values from otherwise unchanged source. The fixture serialized `Map.of` payloads into strings inside a canonical binding; outer canonicalization preserves string contents and therefore does not normalize the inner map order. Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof. No production digest or retained bytes were changed. R44 and the fresh R45 JVM agree on the normalized vector; all 686 GDS unit cases pass in R45. - 2026-10-15: Separate selected-publication owner proofs missed an Account settlement profile gap. The actual GDS terminal → authenticated World completion → both real terminal reads composition reached Account V94 and failed with SQLSTATE 23514 because its inventory validator still admitted only inventory/1 + World/3, while the current canonical producer retains closure inventory/2 + World/4. Preserve that failed composition beside prior component passes; a forward validator correction needs exact profile/refusal and existing-settlement byte/row-version upgrade proof. Do not rewrite installed migrations or treat controlled terminal readbacks as actual producer composition. Correction and qualification are in progress. + +- 2026-10-15 follow-up: Account's forward V1011 now converges the exact inventory/1 + World/3 and closure inventory/2 + World/4 validation profiles while retaining the original framing, digest, source and artifact guards. R14 passes the actual six-store terminal-to-settlement composition and nine malformed-profile refusals; R16 passes original PUBLISHED and NO_PUBLICATION settlement upgrade/replay with unchanged stored bytes and row versions. A test-only V1010 predecessor allowlist omission was corrected separately. These controlled component proofs supply no genuine creator, issuer, environment or deployed authority. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 511100827c..0dd6c0a0aa 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -8,11 +8,13 @@ This is a non-normative implementation tracker for game authoring, publishing, a ### Selected publication reservation preparation -An unregistered reservation adapter independently reads the retained selection, exact Account HELD evidence, World freeze/inventory/selector and original World source/delivery before the existing local reservation transaction. Its ten focused ordering/refusal units pass. The coherent continuation includes Account's missing selected-publication producer, HELD read, typed order transport and exact terminal-settlement owner over existing V93 storage. R4 freshly passes eleven Account PostgreSQL cases, including three mTLS cases for the order producer, HELD reads and settlement, with zero failures, errors or skips. Common's seven typed-order units and Account's twenty-five owner units pass. Scoped static, formatting and documentation checks pass. No migration or parallel terminal codec is introduced; current client types and binding guards remain authoritative. +The unregistered reservation adapter independently reads the retained selection, exact Account HELD evidence, World freeze/inventory/selector and original World source/delivery before the existing local reservation transaction. The coherent continuation supplies Account's selected-publication producer, HELD read, typed order transport and exact terminal-settlement owner. Current terminal clients and binding guards remain authoritative; no parallel terminal codec is introduced. The ten GDS ordering/refusal units, twenty-five Account owner units and seven Common typed-order units pass with their original focused attribution. -R6 freshly passes the extended Full PostgreSQL composition with zero failures, errors or skips. It uses a sixth actual Account store and its normal Redis issuance fixture, authenticated Account HELD and World committed-freeze replay/read endpoints before real GDS admission/reservation and exact reservation retry. The original GDS delivery intake identity is preserved through World application; mutable World retry readers are asserted unused. The existing atomic v4 bundle/terminal commit and immutable readback still execute. Passive capture owns all six exact run-created PostgreSQL containers with zero ownership gaps or observer errors. R6's only gate failure is an unused Java import after removing a now-obsolete controlled Account binding helper; its native and static cases pass. R7 passes canonical formatting and documentation checks after that import-only correction; the successful native proof retains R6 attribution. +R14 freshly passes eleven Account native cases and the extended six-store Full composition with zero failures, errors or skips in those cases. The composition uses the actual Account store and normal Redis issuance fixture, authenticated Account HELD and World committed-freeze replay/read endpoints before real GDS admission/reservation and exact retry. The original GDS delivery intake identity is preserved through World application; mutable World retry readers are asserted unused. The atomic v4 bundle/terminal commit and immutable readback still execute. The actual Game Design terminal receiver, authenticated Game Design-to-World completion producer and World's independent Game Design terminal read then supply both real terminal owners to Account settlement. Settlement before World completion refuses without a receipt; successful settlement and exact retry preserve the original terminal bytes, receipt and row version. Nine direct malformed closure/profile mutations are refused by Account SQL. The local inbound Account caller context is explicitly controlled; its two outbound terminal reads execute real mTLS. Passive capture owns all eight run-created PostgreSQL containers without gaps or observer errors. -The World freeze was previously committed by the actual fixture; this case does not prove a fresh authenticated World begin. Account's settlement proof controls the two remote terminal owners. Upstream creator, issuer, environment, PKI and other declared source/candidate inputs remain controlled. These unregistered components do not supply accepted through-commit Account protection, failed-selection recovery, a reachable publication finalizer or a production entrypoint; fresh/PENDING publication and runtime authority remain denied. All genuine Gameplay handoffs remain open. +The composed proof exposed Account V94's obsolete inventory profile. Forward V1011 converges the validator to the same exact legacy inventory/1 + World/3 and explicit closure inventory/2 + World/4 pairs already owned by Game Design and World. All remaining frame, digest, source, artifact, selected-commit and owner-correlation guards remain enforced; installed migrations and retained rows are unchanged. R14's sole failure was the new historical fixture's unsupported V1010 target. After adding that exact test-only predecessor, R16 freshly passes the V1010-to-current upgrade and replay case for both original terminal outcomes, retaining authorization, source, settlement, issuer and prior Flyway rows including row versions. Scoped generation, compilation, static analysis, formatting and documentation checks pass; the other native cases retain R14 attribution. + +The World freeze was previously committed by the actual fixture; this case does not prove a fresh authenticated World begin. Upstream creator, issuer, environment, PKI and other declared source/candidate inputs remain controlled. These components remain unregistered and do not supply accepted through-commit production authority, failed-selection recovery, a reachable publication finalizer or a production entrypoint. Fresh/PENDING publication and runtime authority remain denied. All genuine Gameplay handoffs remain open. The complete boundary is assigned to Gameplay's existing receiving PR, with no additional extraction PR. ### Selected-full owner publication preparation 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 f614570b53..a58297cb31 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected publication owner preparation -The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. R4 freshly passes all eleven focused PostgreSQL cases, including three mTLS cases for the order producer, HELD reads and settlement, with zero failures, errors or skips. Account's twenty-five focused units and Common's seven typed-order units pass; affected static, formatting and documentation checks pass. Passive capture owns both exact run-created PostgreSQL containers without ownership gaps or observer errors. Original caller/currentness and byte-correlated terminal refusal are component proof under controlled creator, issuer, environment and PKI; the Account settlement test controls both remote terminal owners. These owners remain unregistered and grant no publication finalizer, player admission, genuine authority or runtime activation. +The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. R14 freshly passes eleven focused Account native cases and the real six-store Game Design/World terminal-to-Account settlement composition, including refusal before World completion, exact post-commit receipt replay and nine malformed closure/profile refusals. The latter uses both actual terminal owners and mTLS reads; the local inbound Account caller context remains explicitly controlled. Forward V1011 accepts only the canonical paired legacy and closure inventory profiles, preserving the existing frame, correlation, source and artifact guards. No installed migration is rewritten. + +R16 freshly passes the added V1010-to-current retained-settlement upgrade case for both original terminal outcomes after the test fixture explicitly supports that predecessor. Authorization, source, settlement, issuer and prior Flyway rows retain their exact bytes and row versions through upgrade and replay. The other twelve passing native cases retain R14 attribution; all have zero skips. Account's twenty-five focused units and Common's seven typed-order units retain their preceding pass, and affected generation, static, formatting and documentation checks pass. R14's passive capture owns all eight exact run-created PostgreSQL containers; R16 owns its one, with no ownership gaps or observer errors. Upstream creator, issuer, environment and PKI remain controlled. These owners remain unregistered and grant no publication finalizer, player admission, genuine authority or runtime activation. ### Selected recipient source intake preparation From 9e5fc00a33ace241cb552258a89b665da5be9313 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 06:19:16 +1300 Subject: [PATCH 17/61] Exercise fresh authenticated World publication begin with actual owner reads --- ...nerPublicationPostgresIntegrationTest.java | 223 +++++++++++++++++- ...electedFullPublicationEvidenceFixture.java | 85 ++----- 2 files changed, 233 insertions(+), 75 deletions(-) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 0fd48595d2..d3c8764865 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -279,14 +279,16 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema selection.canonicalJson(), selection.digest()), issuedCreator.environment()); var worldOwners = - WorldSelectedFullPublicationEvidenceFixture.applyFreezeAndCapture( - world.dsl(), - world.transactions(), - NAMESPACE, + freshAuthenticatedWorldFreeze( + gds, + world, + accountSources.dsl, + accountSources.manager, AuthoredDraftPublishSelectionBinding.fromStored( selection.canonicalJson(), selection.digest()), worldGraph, - ignored -> publicationAuthorization); + publicationAuthorization, + new ProofPki(temporary.resolve("fresh-world-begin-pki"))); assertThat(worldOwners.selectedWorldDigest().digestSchemaVersion()).isEqualTo(4); assertThat(worldOwners.appliedResultBytes()).isNotEmpty(); assertThat(worldOwners.graphBytes()).isNotEmpty(); @@ -819,6 +821,217 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema } } + /** Fresh World begin uses real owner reads before any World freeze attempt exists. */ + private static WorldSelectedFullPublicationEvidenceFixture.Result freshAuthenticatedWorldFreeze( + Store gds, + Store world, + org.jooq.DSLContext accountDsl, + org.springframework.transaction.PlatformTransactionManager accountTransactions, + AuthoredDraftPublishSelectionBinding selection, + WorldSelectedFullPublicationEvidenceFixture.AppliedGraph graph, + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding account, + ProofPki pki) + throws Exception { + var selectionCalls = new java.util.concurrent.atomic.AtomicInteger(); + var versionCalls = new java.util.concurrent.atomic.AtomicInteger(); + var heldCalls = new java.util.concurrent.atomic.AtomicInteger(); + var unavailableAccount = new java.util.concurrent.atomic.AtomicBoolean(true); + var unavailableGds = new java.util.concurrent.atomic.AtomicBoolean(); + var sources = + new net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository( + gds.dsl()); + Server gdsServer = + ownerServer( + pki, + "game-design-service", + observedRead( + new net.firedevops.firemud.gamedesign.draft + .GameDesignSelectedDraftPublicationReadGrpcService( + new AuthoredDraftPublishSelectionRepository( + gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())), + NAMESPACE), + selectionCalls, + unavailableGds), + observedRead( + new net.firedevops.firemud.gamedesign.service.impl + .AuthoredWorldVersionStateGrpcService( + new net.firedevops.firemud.gamedesign.service.impl + .AuthoredWorldVersionStateService(gds.transactions(), sources), + NAMESPACE), + versionCalls, + unavailableGds), + new net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceReadGrpcService( + sources, NAMESPACE)); + Server accountServer = null; + Server worldServer = null; + try { + accountServer = + ownerServer( + pki, + "account-service", + observedRead( + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + new AccountPublicationAuthorizationRepository(accountDsl), + accountTransactions, + NAMESPACE), + NAMESPACE), + heldCalls, + unavailableAccount)); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService(loopback(gdsServer)); + endpoints.setAccountService(loopback(accountServer)); + var channels = new GrpcChannelFactory(); + try (var selectionClient = + new net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var versionClient = + new net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var accountClient = + new net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var sourceClient = + new net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + selectionClient.init(); + versionClient.init(); + accountClient.init(); + sourceClient.init(); + var handlers = + WorldSelectedFullPublicationEvidenceFixture.reservationReadEndpoints( + world.dsl(), + world.transactions(), + NAMESPACE, + selectionClient, + versionClient, + accountClient, + sourceClient); + worldServer = + ownerServer( + pki, "world-management-service", handlers.toArray(io.grpc.BindableService[]::new)); + endpoints.setWorldManagementService(loopback(worldServer)); + try (var freeze = + new net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + freeze.init(); + var intent = selection.intent(); + var request = + net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence + .Request.create( + NAMESPACE, + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + selection.digest().substring("sha256:".length()), + account); + var before = freezeOwnerRows(world.dsl()); + for (String empty : + List.of( + "world_design_publication_fence_attempt", + "world_design_publication_account_binding", + "world_selected_publication_artifact_inventory", + "world_canonical_frozen_topology")) { + assertThat(before.get(empty)).as("no prior %s", empty).isEmpty(); + } + assertThat( + world + .dsl() + .fetchSingle( + "SELECT owner_freeze_phase FROM world_design_publication_fence_owner") + .get(0, String.class)) + .isEqualTo("OPEN"); + assertThatThrownBy(() -> freeze.begin(request)).isInstanceOf(RuntimeException.class); + assertThat(freezeOwnerRows(world.dsl())).isEqualTo(before); + assertThat(selectionCalls.get()).isEqualTo(1); + assertThat(versionCalls.get()).isEqualTo(1); + assertThat(heldCalls.get()).isEqualTo(1); + unavailableAccount.set(false); + var created = freeze.begin(request); + assertThat(created.request()).isEqualTo(request); + assertThat(created.acknowledgement().ownerFreezePhase()) + .isEqualTo( + net.firedevops.firemud.common.publication + .WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN); + assertThat(selectionCalls.get()).isEqualTo(2); + assertThat(versionCalls.get()).isEqualTo(2); + assertThat(heldCalls.get()).isEqualTo(2); + var retained = + WorldSelectedFullPublicationEvidenceFixture.readCommittedFreeze( + world.dsl(), NAMESPACE, selection, graph, account, created); + var committed = freezeOwnerRows(world.dsl()); + for (String written : + List.of( + "world_design_publication_fence_attempt", + "world_design_publication_account_binding", + "world_selected_publication_artifact_inventory", + "world_canonical_frozen_topology")) { + assertThat(committed.get(written)).as("one committed %s", written).hasSize(1); + } + unavailableAccount.set(true); + unavailableGds.set(true); + assertThat(freeze.begin(request)).isEqualTo(created); + assertThat(freezeOwnerRows(world.dsl())).isEqualTo(committed); + assertThat(selectionCalls.get()).isEqualTo(2); + assertThat(versionCalls.get()).isEqualTo(2); + assertThat(heldCalls.get()).isEqualTo(2); + return retained; + } + } + } finally { + stop(worldServer); + stop(accountServer); + stop(gdsServer); + } + } + + private static java.util.Map> freezeOwnerRows( + org.jooq.DSLContext dsl) { + var result = new java.util.LinkedHashMap>(); + for (String table : + List.of( + "world_design_publication_fence_owner", + "world_design_publication_fence_attempt", + "world_design_publication_account_binding", + "world_selected_publication_artifact_inventory", + "world_canonical_frozen_topology")) { + result.put( + table, + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM " + table + " r ORDER BY 1") + .getValues(0, String.class)); + } + return result; + } + + private static io.grpc.BindableService observedRead( + io.grpc.BindableService owner, + java.util.concurrent.atomic.AtomicInteger calls, + java.util.concurrent.atomic.AtomicBoolean unavailable) { + return () -> + ServerInterceptors.intercept( + owner, + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata metadata, + io.grpc.ServerCallHandler next) { + calls.incrementAndGet(); + if (unavailable.get()) { + call.close( + io.grpc.Status.UNAVAILABLE.withDescription( + "test-only owner transport outage"), + new io.grpc.Metadata()); + return new io.grpc.ServerCall.Listener<>() {}; + } + return next.startCall(call, metadata); + } + }); + } + /** * Actual immutable owner terminals; the local Account caller context is explicitly controlled. */ diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java index 54580dff9f..545d4eeffb 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java @@ -3,7 +3,6 @@ import java.util.List; import java.util.Objects; import java.util.UUID; -import java.util.function.Function; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -13,7 +12,6 @@ import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; @@ -109,26 +107,19 @@ public DraftCommitBinding selectedCommit() { } } - /** - * Applies and freezes the exact already-retained GDS selection in current World owners. - * - *

The supplied selection is read from GDS's synchronized Version/commit owner before this - * method is called. The callback supplies only controlled upstream Account authorization bytes; - * its selected binding must be byte-for-byte that retained selection. - */ - public static Result applyFreezeAndCapture( + /** Independently reads actual owner rows after the authenticated World begin has committed. */ + public static Result readCommittedFreeze( DSLContext worldDsl, - PlatformTransactionManager worldTransactions, String namespace, AuthoredDraftPublishSelectionBinding selection, AppliedGraph worldGraph, - Function - controlledAccountBindingFactory) { + AccountPublicationAuthorizationBinding accountBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { Objects.requireNonNull(worldDsl, "worldDsl"); - Objects.requireNonNull(worldTransactions, "worldTransactions"); Objects.requireNonNull(selection, "selection"); Objects.requireNonNull(worldGraph, "worldGraph"); - Objects.requireNonNull(controlledAccountBindingFactory, "controlledAccountBindingFactory"); + Objects.requireNonNull(accountBinding, "accountBinding"); + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); var target = selection.target(); DraftCommitBinding binding = selection.selectedCommit(); @@ -153,9 +144,6 @@ public static Result applyFreezeAndCapture( var applied = worldGraph.applied(); requireExactAppliedReadback(applications, topology, application, plan, applied); - AccountPublicationAuthorizationBinding accountBinding = - Objects.requireNonNull( - controlledAccountBindingFactory.apply(selection), "controlled Account binding"); if (!selection.equals(accountBinding.input().selection())) { throw new IllegalArgumentException( "Controlled Account binding does not retain the exact GDS synchronized selection"); @@ -188,45 +176,7 @@ public static Result applyFreezeAndCapture( var authorizationRepository = new WorldSelectedDraftPublicationAuthorizationRepository(worldDsl); var inventoryRepository = new WorldSelectedPublicationArtifactInventoryRepository(worldDsl); - var checkpointRepository = - new WorldSelectedDraftPublicationCheckpointRepository( - fence, applications, topology, digestService); - var capturedCheckpoint = - new java.util.concurrent.atomic.AtomicReference< - WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint>(); - var createdCheckpointInTransaction = new java.util.concurrent.atomic.AtomicBoolean(); - var freezeTransaction = new TransactionTemplate(worldTransactions); - freezeTransaction.setIsolationLevel( - org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); - var frozenAttempt = - Objects.requireNonNull( - freezeTransaction.execute( - status -> { - createdCheckpointInTransaction.set(false); - var attempt = - fence.claimFreeze( - freeze, - () -> { - var captured = checkpointRepository.captureWithSource(freeze, plan); - capturedCheckpoint.set(captured); - createdCheckpointInTransaction.set(true); - return captured.checkpoint(); - }); - var retainedAccount = - authorizationRepository.retainOrRequireExact( - attempt, accountBinding, createdCheckpointInTransaction.get()); - if (!java.util.Arrays.equals( - retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) { - throw new IllegalStateException( - "World did not retain the exact original Account publication binding"); - } - inventoryRepository.retainOrRequireExact( - attempt, - retainedAccount, - createdCheckpointInTransaction.get(), - capturedCheckpoint.get()); - return attempt; - })); + var frozenAttempt = fence.readAttempt(freeze).orElseThrow(); var retainedAccount = authorizationRepository.readCommitted(frozenAttempt).orElseThrow(); if (!java.util.Arrays.equals( @@ -252,10 +202,11 @@ public static Result applyFreezeAndCapture( frozenAttempt.checkpoint().appliedCommitId(), frozenAttempt.checkpoint().contentDigest(), frozenAttempt.checkpoint().digestSchemaVersion()); - var freezeEvidence = - WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( - freezeRequest, - WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + if (!freezeRequest.equals(freezeEvidence.request()) + || !acknowledgement.equals(freezeEvidence.acknowledgement())) { + throw new IllegalStateException( + "Authenticated begin differs from independent committed World rows"); + } var inventoryEvidence = new WorldSelectedPublicationArtifactInventoryReadService( namespace, fence, authorizationRepository, inventoryRepository) @@ -265,13 +216,7 @@ public static Result applyFreezeAndCapture( var frozenRepository = new WorldCanonicalFrozenTopologyRepository( worldDsl, new WorldAuthoredGraphSnapshotRepository(worldDsl), topology, digestService); - var captured = - new WorldCanonicalFrozenTopologyService(frozenRepository, worldTransactions) - .capture(new WorldCanonicalFrozenTopology.Request(plan, captureRequest)); - var committedCapture = frozenRepository.readCommitted(captureRequest).orElseThrow(); - if (!java.util.Arrays.equals(committedCapture.graphBytes(), captured.graphBytes())) { - throw new IllegalStateException("Committed World frozen-graph readback changed bytes"); - } + var captured = frozenRepository.readCommitted(captureRequest).orElseThrow(); var publishedSource = new WorldPublishedStartLocationRepository(worldDsl, frozenRepository, applications) .readCommitted(captureRequest) @@ -279,8 +224,8 @@ public static Result applyFreezeAndCapture( var worldEvidence = publishedStartLocationEvidence(publishedSource); var worldDigest = new WorldDraftDesignDigestService.WorldDraftDesignDigest( - Long.toString(capturedCheckpoint.get().owner().localTenantKey()), - Long.toString(capturedCheckpoint.get().owner().localVersionKey()), + Long.toString(worldGraph.sourceIntake().localTenantKey()), + Long.toString(worldGraph.versionIdentity().localVersionKey()), frozenAttempt.checkpoint().appliedCommitId(), frozenAttempt.checkpoint().contentDigest(), frozenAttempt.checkpoint().digestSchemaVersion()); From f886b9eceba2616720921227b52b61ca9788d0a3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 06:22:07 +1300 Subject: [PATCH 18/61] Record fresh authenticated World freeze begin proof and remaining holds --- .../game-authoring-publishing-and-activation.md | 4 +++- .../implementation-tracking/world-runtime-and-movement.md | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 0dd6c0a0aa..01cd16b473 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -14,7 +14,9 @@ R14 freshly passes eleven Account native cases and the extended six-store Full c The composed proof exposed Account V94's obsolete inventory profile. Forward V1011 converges the validator to the same exact legacy inventory/1 + World/3 and explicit closure inventory/2 + World/4 pairs already owned by Game Design and World. All remaining frame, digest, source, artifact, selected-commit and owner-correlation guards remain enforced; installed migrations and retained rows are unchanged. R14's sole failure was the new historical fixture's unsupported V1010 target. After adding that exact test-only predecessor, R16 freshly passes the V1010-to-current upgrade and replay case for both original terminal outcomes, retaining authorization, source, settlement, issuer and prior Flyway rows including row versions. Scoped generation, compilation, static analysis, formatting and documentation checks pass; the other native cases retain R14 attribution. -The World freeze was previously committed by the actual fixture; this case does not prove a fresh authenticated World begin. Upstream creator, issuer, environment, PKI and other declared source/candidate inputs remain controlled. These components remain unregistered and do not supply accepted through-commit production authority, failed-selection recovery, a reachable publication finalizer or a production entrypoint. Fresh/PENDING publication and runtime authority remain denied. All genuine Gameplay handoffs remain open. The complete boundary is assigned to Gameplay's existing receiving PR, with no additional extraction PR. +FreshBeginR3 freshly passes the same six-store composition with a fresh authenticated World begin, rather than a fixture-created freeze. World starts with its owner OPEN and no attempt, Account correlation, inventory or canonical frozen capture. Actual Game Design selection and source-qualified Version handlers and Account HELD are called over mTLS. A controlled Account transport outage refuses before World effects, preserving all five owner tables including row versions; enabling the real read creates the exact FROZEN checkpoint, Account correlation, complete inventory and selector capture. An exact begin retry succeeds with both mutable upstream transports denied and without repeating any owner reads or changing retained rows. The World fixture now only reads the independently committed result. The later actual reservation, v4 bundle and terminal-to-Account settlement still pass in that same fresh native case. FreshBeginR3 has zero failures, errors or skips; all six run-owned PostgreSQL containers are passively identified without ownership gaps or observer errors. Compilation, scoped static analysis, formatting and documentation checks pass. + +Original World source/version registration and APPLIED input remain controlled fixture preparation. Upstream creator, issuer, environment, PKI and other declared source/candidate inputs remain controlled. These components remain unregistered and do not supply accepted through-commit production authority, failed-selection recovery, a reachable publication finalizer or a production entrypoint. Fresh/PENDING publication and runtime authority remain denied. All genuine Gameplay handoffs remain open. The complete boundary is assigned to Gameplay's existing receiving PR, with no additional extraction PR. ### Selected-full owner publication preparation diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 9ae921e238..d8f8d9bb4c 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -36,6 +36,8 @@ Registered mutation ingress remains refused. The existing internal mutation pref ### Selected publication World owner source +FreshBeginR3 freshly passes the six-store selected-publication composition with actual authenticated fresh World begin. The initial World owner is OPEN and no freeze attempt, Account correlation, inventory or canonical frozen capture exists. World independently reads the actual retained Game Design selection, source-qualified current Version and Account HELD through real mTLS handlers. A controlled Account transport outage leaves all five World owner tables and row versions unchanged. The successful request commits the original FROZEN checkpoint, Account correlation and complete inventory, then captures the exact canonical selector. Repeating the same begin with mutable upstream transports denied performs no further owner reads and preserves retained rows. The fixture's former manual freeze/capture is replaced by independent committed readback. The existing actual Game Design reservation, v4 bundle and terminal-to-Account settlement still execute in that one fresh native case, with zero failures, errors or skips. All six run-created PostgreSQL containers are passively owned without gaps or observer errors; affected compilation, static analysis and formatting pass. Upstream original source/APPLIED preparation, creator, issuer, environment and PKI remain controlled. This proves the fresh component path and does not register ingress, supply continuous production authority, implement failed-selection recovery or close any genuine handoff. + The standalone consumer succeeds the shared fence/Common foundation published in [PR #3217](https://github.com/benhook1013/FireMUD/pull/3217) at `8afceb8` on parent `7b2ce634`. Its 66-path scope contains 37 World production files, the existing Common codec and test, 20 World unit/transport files, one current-default PostgreSQL chain, the World Common test-fixtures dependency, four documentation files and an observation. All published migration postimages remain unchanged. Standalone unregistered components cover original Account-order-bound APPLIED application, selected freeze/checkpoint, immutable authored graph, complete artifact inventory, canonical selector/frozen graph, and default-denied terminal completion/readback. The terminal path uses the canonical `GameDesignPublicationTerminalClient` directly and denies UNKNOWN evidence. Existing cumulative V1014 supports exact six-family counts with owner-proved zeros; the selected source explicitly declares all seven inbound families empty. No new migration or generator registry was added, and unsupported nonempty generation rules remain denied. The [World runtime/data manifest](../../architecture/microservices/world-management-service/runtime-and-data.md#digest-input-manifest) owns family/input/digest storage, [procedural generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md#derived-world-artifact-publication) owns derived-artifact/read consequences, and the [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) owns operations. From 2031e0e04e065ac6428b0cead9ca41665b747ef5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 06:25:44 +1300 Subject: [PATCH 19/61] Compose actual Account publication ordering with the GDS selection owner --- ...nerPublicationPostgresIntegrationTest.java | 115 ++++++++++++++++-- 1 file changed, 105 insertions(+), 10 deletions(-) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index d3c8764865..0f4125817f 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -268,16 +268,14 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema draft.target().canonicalTenantId())) { var issuedCreator = accountFixture.issueCreator(); var accountSources = issuedCreator.sources(); + var publicationPki = new ProofPki(temporary.resolve("fresh-world-begin-pki")); var publicationAuthorization = - new AccountPublicationAuthorizationService( - issuedCreator.actors(), - accountSources.fences, - new AccountPublicationAuthorizationRepository(accountSources.dsl)) - .authorize( - issuedCreator.compact(), - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson(), selection.digest()), - issuedCreator.environment()); + authenticatedAccountPublicationOrder( + gds, + issuedCreator, + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + publicationPki); var worldOwners = freshAuthenticatedWorldFreeze( gds, @@ -288,7 +286,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema selection.canonicalJson(), selection.digest()), worldGraph, publicationAuthorization, - new ProofPki(temporary.resolve("fresh-world-begin-pki"))); + publicationPki); assertThat(worldOwners.selectedWorldDigest().digestSchemaVersion()).isEqualTo(4); assertThat(worldOwners.appliedResultBytes()).isNotEmpty(); assertThat(worldOwners.graphBytes()).isNotEmpty(); @@ -821,6 +819,103 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema } } + /** Actual authenticated Account ordering consumes the real GDS immutable selection owner. */ + private static net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding + authenticatedAccountPublicationOrder( + Store gds, + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + AuthoredDraftPublishSelectionBinding selection, + ProofPki pki) + throws Exception { + var reads = new java.util.concurrent.atomic.AtomicInteger(); + var unavailable = new java.util.concurrent.atomic.AtomicBoolean(true); + var selectionOwner = + new net.firedevops.firemud.gamedesign.draft + .GameDesignSelectedDraftPublicationReadGrpcService( + new AuthoredDraftPublishSelectionRepository( + gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())), + NAMESPACE); + Server gdsServer = + ownerServer(pki, "game-design-service", observedRead(selectionOwner, reads, unavailable)); + Server accountServer = null; + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService(loopback(gdsServer)); + var channels = new GrpcChannelFactory(); + var sources = issued.sources(); + try (var selectionClient = + new net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE)) { + selectionClient.init(); + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var owner = + new AccountSelectedDraftPublicationOrderService( + selectionClient, + new AccountPublicationAuthorizationService( + issued.actors(), sources.fences, repository), + NAMESPACE); + accountServer = + ownerServer( + pki, + "account-service", + new AccountSelectedDraftPublicationOrderGrpcService(owner, sources.terms, NAMESPACE)); + endpoints.setAccountService(loopback(accountServer)); + try (var client = + new net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + client.init(); + var request = + net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec + .Request.create(NAMESPACE, selection, issued.compact()); + var before = publicationOrderRows(sources.dsl); + assertThat(before.get("account_selected_publication_authorizations")).isEmpty(); + assertThat(before.get("account_selected_publication_sources")).isEmpty(); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(RuntimeException.class); + assertThat(publicationOrderRows(sources.dsl)).isEqualTo(before); + assertThat(reads.get()).isEqualTo(1); + unavailable.set(false); + var created = client.authorize(request); + assertThat(created.input().selection().canonicalBytes()) + .containsExactly(selection.canonicalBytes()); + var committed = publicationOrderRows(sources.dsl); + assertThat(committed.get("account_selected_publication_authorizations")).hasSize(1); + assertThat(committed.get("account_selected_publication_sources")).isNotEmpty(); + assertThat(client.authorize(request).canonicalBytes()) + .containsExactly(created.canonicalBytes()); + assertThat(publicationOrderRows(sources.dsl)).isEqualTo(committed); + assertThat(reads.get()).isEqualTo(3); + assertThat( + sources + .dsl + .fetchSingle( + "SELECT count(*) FROM account_control_ui_issuance_operations WHERE status = 'COMMITTED'") + .get(0, Long.class)) + .isEqualTo(1L); + return created; + } + } finally { + stop(accountServer); + stop(gdsServer); + } + } + + private static java.util.Map> publicationOrderRows( + org.jooq.DSLContext dsl) { + var result = new java.util.LinkedHashMap>(); + for (String table : + List.of( + "account_selected_publication_authorizations", + "account_selected_publication_sources", + "account_selected_publication_settlements", + "account_control_ui_issuance_operations")) { + result.put( + table, + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM " + table + " r ORDER BY 1") + .getValues(0, String.class)); + } + return result; + } + /** Fresh World begin uses real owner reads before any World freeze attempt exists. */ private static WorldSelectedFullPublicationEvidenceFixture.Result freshAuthenticatedWorldFreeze( Store gds, From 6b322cd45c38e6240f380464bc0c47356030e476 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 06:28:39 +1300 Subject: [PATCH 20/61] Record actual Account publication-order producer composition proof --- .../game-authoring-publishing-and-activation.md | 2 ++ .../implementation-tracking/player-access-and-session.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 01cd16b473..1286581e9d 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -16,6 +16,8 @@ The composed proof exposed Account V94's obsolete inventory profile. Forward V10 FreshBeginR3 freshly passes the same six-store composition with a fresh authenticated World begin, rather than a fixture-created freeze. World starts with its owner OPEN and no attempt, Account correlation, inventory or canonical frozen capture. Actual Game Design selection and source-qualified Version handlers and Account HELD are called over mTLS. A controlled Account transport outage refuses before World effects, preserving all five owner tables including row versions; enabling the real read creates the exact FROZEN checkpoint, Account correlation, complete inventory and selector capture. An exact begin retry succeeds with both mutable upstream transports denied and without repeating any owner reads or changing retained rows. The World fixture now only reads the independently committed result. The later actual reservation, v4 bundle and terminal-to-Account settlement still pass in that same fresh native case. FreshBeginR3 has zero failures, errors or skips; all six run-owned PostgreSQL containers are passively identified without ownership gaps or observer errors. Compilation, scoped static analysis, formatting and documentation checks pass. +ActualOrderR2 freshly passes that same native composition after replacing the directly invoked Account producer with the real selected-order transport. Game Design calls the actual Account receiver with the original creator credential; Account independently authenticates the actual retained Game Design selection through its existing owner client before its local producer transaction. A controlled Game Design transport outage preserves Account authorization, source, settlement and issuer rows including row versions. Successful ordering creates one original held order from the single committed creator issuance; exact retry rereads the real selection, returns identical original binding bytes and preserves retained rows. That returned binding drives the fresh World begin and later actual publication and settlement. The case has zero failures, errors or skips, with all six run-created PostgreSQL containers passively owned without gaps or observer errors. Scoped compilation, static analysis and formatting pass. These are actual component transports with controlled upstream creator, issuer, environment and PKI; the public-finalizer/currentness/recovery holds remain unchanged. + Original World source/version registration and APPLIED input remain controlled fixture preparation. Upstream creator, issuer, environment, PKI and other declared source/candidate inputs remain controlled. These components remain unregistered and do not supply accepted through-commit production authority, failed-selection recovery, a reachable publication finalizer or a production entrypoint. Fresh/PENDING publication and runtime authority remain denied. All genuine Gameplay handoffs remain open. The complete boundary is assigned to Gameplay's existing receiving PR, with no additional extraction PR. ### Selected-full owner publication preparation 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 a58297cb31..2784f6e3c6 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,8 @@ The isolated continuation prepares Account's distinct selected-publication order R16 freshly passes the added V1010-to-current retained-settlement upgrade case for both original terminal outcomes after the test fixture explicitly supports that predecessor. Authorization, source, settlement, issuer and prior Flyway rows retain their exact bytes and row versions through upgrade and replay. The other twelve passing native cases retain R14 attribution; all have zero skips. Account's twenty-five focused units and Common's seven typed-order units retain their preceding pass, and affected generation, static, formatting and documentation checks pass. R14's passive capture owns all eight exact run-created PostgreSQL containers; R16 owns its one, with no ownership gaps or observer errors. Upstream creator, issuer, environment and PKI remain controlled. These owners remain unregistered and grant no publication finalizer, player admission, genuine authority or runtime activation. +ActualOrderR2 freshly passes the six-store owner composition with actual Game Design-to-Account selected-publication ordering and Account-to-Game-Design immutable selection reads over mTLS. Account captures the environment internally and authenticates the original creator through its existing owner. A controlled Game Design transport outage creates no authorization/source/settlement state and preserves the original issuer rows and row versions. Successful ordering and exact retry retain one held order and unchanged binding/source rows from the single committed issuance; the returned actual order then drives fresh World freeze, publication and exact both-owner terminal settlement. One fresh native case passes with zero skips, six exact PostgreSQL containers passively owned and no observer gaps or errors; affected compilation, static analysis and formatting pass. No new production code, migration, registration or runtime authority is added. Upstream creator, issuer, environment and PKI remain controlled, and the local inbound settlement caller context remains a separate controlled component seam. + ### Selected recipient source intake preparation R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. R35 freshly passes the successor disclosure composition at the actual V1008–V1010 repository frontier, including physical source-writer exclusion until exact reservation abort; its static, formatting and documentation checks pass. The earlier V1007-only source proof retains separate R33 attribution. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority. From 8d1f631ceb06eb8dcef473445c9a86e1aef20a49 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 09:16:51 +1300 Subject: [PATCH 21/61] Compose selected publication settlement in passive receiving boundary --- ...ame-authoring-publishing-and-activation.md | 8 + .../player-access-and-session.md | 2 + ...ected_publication_settlement_service.proto | 31 +++ ...ectedPublicationSettlementGrpcService.java | 97 +++++++ ...tionProtectionPostgresIntegrationTest.java | 53 ++++ ...dPublicationSettlementGrpcServiceTest.java | 142 ++++++++++ .../GameDesignPublicationTerminalClient.java | 14 +- ...AccountSelectedPublicationOrderClient.java | 8 +- ...ntSelectedPublicationSettlementClient.java | 159 ++++++++++++ ...electedPublicationSettlementGrpcCodec.java | 244 ++++++++++++++++++ ...electedOwnerIntakeClientLifecycleTest.java | 40 ++- ...tedPublicationSettlementGrpcCodecTest.java | 196 ++++++++++++++ ...licationTerminalClientTransactionTest.java | 93 +++++++ ...nerPublicationPostgresIntegrationTest.java | 173 ++++++++----- 14 files changed, 1183 insertions(+), 77 deletions(-) create mode 100644 protos/account/v1/selected_publication_settlement_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 4ff118f89a..b881313836 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -20,6 +20,14 @@ ActualOrderR2 freshly passes that same native composition after replacing the di Original World source/version registration and APPLIED input remain controlled fixture preparation. Upstream creator, issuer, environment, PKI and other declared source/candidate inputs remain controlled. These components remain unregistered and do not supply accepted through-commit production authority, failed-selection recovery, a reachable publication finalizer or a production entrypoint. Fresh/PENDING publication and runtime authority remain denied. All genuine Gameplay handoffs remain open. The complete boundary is assigned to Gameplay's existing receiving PR, with no additional extraction PR. +### Selected publication settlement transport receiving + +The selected Account order, held-read and settlement clients, Game Design selection and terminal-read clients, and World terminal-read client release their local monitor before the shared certificate watcher drains an in-flight reload callback. Their close flags still deny reuse; the existing selected-owner lifecycle matrix covers callback contention, idempotent shutdown and closed-client initialization denial. + +The canonical Game Design publication terminal client retains the original donor's local transaction exclusion: active owner SQL and synchronization-only contexts fail before transport access. This guard stays on the current closed framed terminal-read API; the alternate donor client, evidence type and service are not reintroduced. + +The current-carrier continuation retains the standalone, unregistered Account selected-publication settlement receiver, explicit file-backed mTLS client and closed request/receipt codec from the preserved #3105 donor. Account still derives settlement from its two independent authenticated Game Design and World owner reads; the caller supplies only the complete original operation and transport correlation. The codec validates the unchanged six-frame receipt, exact operation and owner terminal/outcome agreement within the serialized wire bound. The selected full-owner fixture now invokes this actual Account receiver over loopback mTLS, requires a World workload caller to be denied, retains no settlement before World completion and checks unchanged receipt bytes and row metadata on retry. Original creator/issuer/environment, source provenance, selected inputs and ephemeral PKI remain controlled. No production service registration, migration, activation or genuine Gameplay handoff is established. + ### Selected-full owner publication preparation The source candidate prepares complete selected-owner publication consumption under the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile). It reuses the actual parent World closure producer, adds its full-profile consumer mapping, and composes the selected Game Design digest read/collector with independently retained Entity, Automation and Game Logic receipts. The Game Logic adapter reads the exact retained terminal, selected source and manifest through the existing owner repository and returns both manifest and ability projections; its default Spring composition remains denied. Private selected writer mechanics use the exact canonical selection/request binding and selected gate. Public Game Design fresh/PENDING publication remains denied. Existing Game Design V1020 storage is reused; no Game Design migration is added. 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 20fd7bb757..85e1babaef 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -46,6 +46,8 @@ Focused proof is split by unchanged source attribution: twelve shared validator ### Original StartSession source-protection storage +Preceding isolated receiving qualification at `9f48ef606ffe1f73d99adc17f9f88dbb5677624e` on immutable #2967 input `ec4ca374f95d94c130d3578269744477f20b8085` passes 34 focused physical PostgreSQL cases: 18 admission, nine activation and seven credential-cleanup cases, with zero failures, errors or skips. Affected integration static analysis, formatting and documentation checks pass. This canonical lineage installs complete original-tuple byte equality and the independent nested issuance-operation identity checks directly in V1003; it does not install the historical donor V163-to-V164 scalar-guard replacement. The passing canonical predecessor proof retains the actual 112-script history, row bytes and metadata, relation/function identities and prior guard definitions. The activation suite additionally defines a direct contradictory-owner-issuance regression alongside the existing admission case; upstream rows are deliberately stipulated while current acquisition guards remain enabled. These are controlled Account integrity checks and do not establish genuine creator/issuer/environment continuity, authenticated World production, activation or any Gameplay handoff. + 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). diff --git a/protos/account/v1/selected_publication_settlement_service.proto b/protos/account/v1/selected_publication_settlement_service.proto new file mode 100644 index 0000000000..205166bb73 --- /dev/null +++ b/protos/account/v1/selected_publication_settlement_service.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone authenticated settlement of one exact selected-publication authorization. +service AccountSelectedPublicationSettlementService { + rpc SettleSelectedPublication(SettleSelectedPublicationRequest) + returns (SettleSelectedPublicationResponse); +} + +message SettleSelectedPublicationRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Independent transport correlation; the retained Account order remains the settlement key. + string request_id = 3; + // Complete canonical game-design-publication-operation/v2 bytes. + bytes original_operation = 4; +} + +message SettleSelectedPublicationResponse { + // Exact unchanged request echo. + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + bytes original_operation = 4; + // Existing six-frame account-selected-publication-settlement/v1 receipt. + bytes settlement_receipt = 5; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java new file mode 100644 index 0000000000..56eb571a39 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementGrpcCodec; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementGrpcCodec.Request; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone unregistered authenticated ingress for exact selected-publication settlement. */ +public final class AccountSelectedPublicationSettlementGrpcService + extends AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceImplBase { + private final AccountSelectedDraftPublicationSettlementService owner; + private final String namespace; + + public AccountSelectedPublicationSettlementGrpcService( + AccountSelectedDraftPublicationSettlementService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-publication settlement owner required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void settleSelectedPublication( + SettleSelectedPublicationRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + if (SessionContext.hasAuthenticatedCallerContext() + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + if (wire == null + || wire.getSerializedSize() + > AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + + final Request request; + try { + request = AccountSelectedPublicationSettlementGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + + try { + byte[] receipt = owner.settle(request.originalOperation()); + observer.onNext(AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.INVALID_ARGUMENT + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + deny(observer, Status.fromCode(code)); + } catch (IllegalArgumentException invalidEvidence) { + deny(observer, Status.FAILED_PRECONDITION); + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + } + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError( + status + .withDescription("Account selected-publication settlement denied or unavailable") + .asRuntimeException()); + } +} 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 index 9cb3db2f17..ec6a37938d 100644 --- 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 @@ -1342,6 +1342,59 @@ void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() thro expiredFixture, expired.requestBytes(), expired.operationIdentityBytes()); } + @Test + void fullTupleDoesNotBypassIndependentActivationIssuanceOperationBinding() throws Exception { + Fixture fixture = fixture(); + CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(60)); + Map request = readJson(current.requestBytes()); + byte[] tuple = + Base64.getDecoder() + .decode((String) request.get("originalPostAuthorizationTupleBytesBase64")); + byte[] projection = + Base64.getDecoder().decode((String) request.get("accountRedemptionProjectionBytesBase64")); + assertThat(projection).containsExactly(tuple); + String requestId = (String) readJson(tuple).get("controlPlaneRequestId"); + + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + current.requestBytes(), + current.operationIdentityBytes(), + current.operationIdentityDigest())); + // Stipulate one contradictory retained owner row to isolate the independent SQL conjunct. + // Current activation/acquisition guards stay enabled; this is not authenticated producer proof. + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + assertThat( + fixture + .dsl() + .execute( + "UPDATE account_start_session_operator_authorizations SET issuance_operation_id = ? " + + "WHERE control_plane_request_id = ?", + UUID.randomUUID(), + requestId)) + .isEqualTo(1); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + assertThatThrownBy(() -> acquireProtection(fixture, current)) + .hasMessageContaining( + "Activation protection differs from original Account redemption or capture"); + for (String table : + List.of( + "account_start_session_activation_protections", + "account_start_session_activation_protection_sources")) { + assertThat(fixture.dsl().fetchCount(DSL.table(table))).as(table).isZero(); + } + } + @Test void abortedSettlementPreservesTerminalCodeFenceWithoutRequiringActiveLifecycle() throws Exception { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java new file mode 100644 index 0000000000..285cca35ad --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java @@ -0,0 +1,142 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationSettlementService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedPublicationSettlementGrpcService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Receiver identity/ordering units; synthetic peer context is not authenticated TLS proof. */ +class AccountSelectedPublicationSettlementGrpcServiceTest { + private static final String NAMESPACE = "publication-runtime"; + private static final String GAME_DESIGN_URI = + "spiffe://firemud/ns/publication-runtime/sa/game-design-service"; + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactGameDesignBeforeMalformedRequestOrOwnerAccess() { + var owner = mock(AccountSelectedDraftPublicationSettlementService.class); + var receiver = new AccountSelectedPublicationSettlementGrpcService(owner, NAMESPACE); + var malformed = SettleSelectedPublicationRequest.getDefaultInstance(); + + assertCode(Status.Code.UNAUTHENTICATED, invoke(receiver, null, malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, + identity("spiffe://firemud/ns/other-runtime/sa/game-design-service"), + malformed)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, + identity("spiffe://firemud/ns/publication-runtime/sa/" + workload), + malformed)); + } + SessionContext.setContext("test-user", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, invoke(receiver, identity(GAME_DESIGN_URI), malformed)); + verifyNoInteractions(owner); + } + + @Test + void deniesAmbientSqlAndClosedEnvelopeErrorsBeforeOwnerCall() { + var owner = mock(AccountSelectedDraftPublicationSettlementService.class); + var receiver = new AccountSelectedPublicationSettlementGrpcService(owner, NAMESPACE); + var peer = identity(GAME_DESIGN_URI); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, peer, null)); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, peer, null)); + TransactionSynchronizationManager.clearSynchronization(); + + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, peer, null)); + var unknown = + SettleSelectedPublicationRequest.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, peer, unknown)); + verifyNoInteractions(owner); + } + + private static Invocation invoke( + AccountSelectedPublicationSettlementGrpcService receiver, + GrpcPeerIdentity peer, + SettleSelectedPublicationRequest request) { + var result = new Invocation(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + receiver.settleSelectedPublication(request, result); + } finally { + context.detach(previous); + } + return result; + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, Invocation invocation) { + assertThat(invocation.error).isNotNull(); + assertThat(invocation.error.statusRuntimeException()).isTrue(); + assertThat(invocation.error.code()).isEqualTo(expected); + assertThat(invocation.response).isNull(); + assertThat(invocation.completed).isFalse(); + } + + private record ObservedError(boolean statusRuntimeException, Status.Code code) {} + + private static final class Invocation + implements StreamObserver { + private SettleSelectedPublicationResponse response; + private ObservedError error; + private boolean completed; + + @Override + public void onNext(SettleSelectedPublicationResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = + new ObservedError( + failure instanceof StatusRuntimeException, Status.fromThrowable(failure).getCode()); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java index a562ded108..5f248d7ebc 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Explicit mTLS client for the exact Game Design publication terminal read. */ public final class GameDesignPublicationTerminalClient @@ -64,6 +65,11 @@ public synchronized void init() throws SSLException, IOException { */ public GameDesignPublicationTerminalReadEvidence.ReadResult read( GameDesignPublicationTerminalReadEvidence.ReadRequest request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Game Design publication terminal read requires no owner transaction"); + } Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( @@ -104,9 +110,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java index 79273b345a..0fdcb5c9a2 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java @@ -107,9 +107,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java new file mode 100644 index 0000000000..7ca015d0a2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationSettlementServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for Account-owned selected-publication settlement. */ +public final class AccountSelectedPublicationSettlementClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountSelectedPublicationSettlementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountSelectedPublicationSettlementClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account publication settlement client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account publication settlement stub unavailable"); + } + initialized = true; + } + + /** Returns the exact original six-frame receipt after Account peer and receipt validation. */ + public byte[] settle(AccountSelectedPublicationSettlementGrpcCodec.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account publication settlement requires no owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account publication settlement must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .settleSelectedPublication( + AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); + try { + return AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned an invalid publication settlement receipt", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountSelectedPublicationSettlementServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip") + .withMaxInboundMessageSize(AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES); + } + + @Override + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } + super.close(); + } + + private AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account publication settlement client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Account publication settlement requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account publication settlement requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account publication settlement requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account publication settlement " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account publication settlement " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java new file mode 100644 index 0000000000..a9ccc03f4f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java @@ -0,0 +1,244 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed Account-owned selected-publication settlement transport and receipt validation. */ +public final class AccountSelectedPublicationSettlementGrpcCodec { + /** Shared per-message protobuf budget; oversized complete six-frame receipts fail closed. */ + public static final int MAX_MESSAGE_BYTES = 32 * 1024 * 1024; + + private static final int MESSAGE_ENVELOPE_OVERHEAD_RESERVE = 256; + private static final String RECEIPT_SCHEMA = "account-selected-publication-settlement/v1"; + + private AccountSelectedPublicationSettlementGrpcCodec() {} + + public static SettleSelectedPublicationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var wire = + SettleSelectedPublicationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .build(); + requireWireBudget(wire); + return wire; + } + + /** Receiver authenticates the exact Game Design peer before decoding this request. */ + public static Request fromRequest(SettleSelectedPublicationRequest request) { + Objects.requireNonNull(request, "request"); + requireWireBudget(request); + noUnknownFields(request); + try { + return new Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + canonicalUuid(request.getRequestId()), + request.getOriginalOperation().toByteArray()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Account publication settlement request is invalid", malformed); + } + } + + /** Emits only an exact original receipt whose six canonical frames agree with the request. */ + public static SettleSelectedPublicationResponse toResponse(Request request, byte[] receipt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(receipt, "receipt"); + if ((long) receipt.length + request.originalOperation().length + > MAX_MESSAGE_BYTES - MESSAGE_ENVELOPE_OVERHEAD_RESERVE) { + throw new IllegalArgumentException( + "Account publication settlement response exceeds the 32 MiB wire budget"); + } + var response = + SettleSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setSettlementReceipt(ByteString.copyFrom(receipt)) + .build(); + requireWireBudget(response); + validateReceipt(request, receipt); + return response; + } + + /** Verifies the full echo and returns the exact canonical Account settlement receipt. */ + public static byte[] fromResponse(Request request, SettleSelectedPublicationResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireWireBudget(response); + noUnknownFields(response); + if (response.getSchemaVersion() != request.schemaVersion() + || !request.targetNamespace().equals(response.getTargetNamespace()) + || !request.requestId().toString().equals(response.getRequestId()) + || !Arrays.equals( + request.originalOperation(), response.getOriginalOperation().toByteArray())) { + throw new IllegalArgumentException( + "Account changed the exact publication settlement request"); + } + byte[] receipt = response.getSettlementReceipt().toByteArray(); + validateReceipt(request, receipt); + return receipt.clone(); + } + + private static void validateReceipt(Request request, byte[] receipt) { + if (receipt == null || receipt.length == 0 || receipt.length > MAX_MESSAGE_BYTES) { + throw new IllegalArgumentException( + "Complete bounded Account publication settlement receipt required"); + } + final byte[] accountBinding; + final byte[] originalOperation; + final byte[] gameDesignTerminalBytes; + final String worldOutcome; + final byte[] worldTerminalBytes; + try { + var reader = new DraftAuthorizationFenceBinding.FrameReader(receipt); + reader.expect(RECEIPT_SCHEMA); + accountBinding = reader.bytes(); + originalOperation = reader.bytes(); + gameDesignTerminalBytes = reader.bytes(); + worldOutcome = reader.text(); + worldTerminalBytes = reader.bytes(); + reader.requireEnd(); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Canonical six-frame Account publication settlement receipt required", malformed); + } + + GameDesignPublicationOperationBinding operation; + GameDesignPublicationTerminalEvidence terminal; + try { + operation = GameDesignPublicationOperationBinding.fromStored(request.originalOperation()); + terminal = GameDesignPublicationTerminalEvidence.fromStored(gameDesignTerminalBytes); + GameDesignPublicationTerminalEvidence.fromStored(worldTerminalBytes); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Account receipt lacks complete canonical publication evidence", malformed); + } + String expectedWorldOutcome = + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + if (!Arrays.equals(accountBinding, operation.account().canonicalBytes()) + || !Arrays.equals(originalOperation, request.originalOperation()) + || !Arrays.equals(terminal.operationBytes(), originalOperation) + || !Arrays.equals(gameDesignTerminalBytes, terminal.canonicalBytes()) + || !Arrays.equals(worldTerminalBytes, gameDesignTerminalBytes) + || !expectedWorldOutcome.equals(worldOutcome)) { + throw new IllegalArgumentException( + "Account settlement receipt differs from the exact operation, terminal, or World outcome"); + } + + var canonical = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(canonical, RECEIPT_SCHEMA); + DraftAuthorizationFenceBinding.frame(canonical, accountBinding); + DraftAuthorizationFenceBinding.frame(canonical, originalOperation); + DraftAuthorizationFenceBinding.frame(canonical, gameDesignTerminalBytes); + DraftAuthorizationFenceBinding.frame(canonical, worldOutcome); + DraftAuthorizationFenceBinding.frame(canonical, worldTerminalBytes); + if (!Arrays.equals(receipt, canonical.toByteArray())) { + throw new IllegalArgumentException("Noncanonical Account publication settlement receipt"); + } + } + + private static void requireWireBudget(Message message) { + if (message.getSerializedSize() > MAX_MESSAGE_BYTES) { + throw new IllegalArgumentException( + "Account publication settlement exceeds the 32 MiB wire budget"); + } + } + + private static void noUnknownFields(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Account publication settlement has unsupported fields"); + } + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil request UUID required"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException("Canonical non-nil request UUID required", malformed); + } + } + + /** Request correlation is fresh per transport call and is not the retained settlement key. */ + public record Request( + int schemaVersion, String targetNamespace, UUID requestId, byte[] originalOperation) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported Account publication settlement schema"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + if (requestId == null || requestId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Non-nil canonical request identity required"); + } + if (originalOperation == null || originalOperation.length == 0) { + throw new IllegalArgumentException("Complete original publication operation required"); + } + if (originalOperation.length > GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES) { + throw new IllegalArgumentException("Original publication operation exceeds 4 MiB"); + } + originalOperation = originalOperation.clone(); + GameDesignPublicationOperationBinding operation; + try { + operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Complete canonical original publication operation required", malformed); + } + if (!Arrays.equals(originalOperation, operation.canonicalBytes())) { + throw new IllegalArgumentException( + "Exact canonical original publication operation required"); + } + if (!targetNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException( + "Original publication operation differs from the Account workload namespace"); + } + } + + public static Request create(String targetNamespace, byte[] originalOperation) { + return new Request(SCHEMA_VERSION, targetNamespace, UUID.randomUUID(), originalOperation); + } + + @Override + public byte[] originalOperation() { + return originalOperation.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && requestId.equals(that.requestId) + && Arrays.equals(originalOperation, that.originalOperation); + } + + @Override + public int hashCode() { + return 31 * Objects.hash(schemaVersion, targetNamespace, requestId) + + Arrays.hashCode(originalOperation); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java index 962f6c4262..dba9728d53 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java @@ -23,11 +23,17 @@ import java.util.function.BooleanSupplier; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; import net.firedevops.firemud.common.publication.WorldSelectedOwnerInventoryGrpcClient; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; @@ -178,7 +184,13 @@ private enum ClientKind { SOURCE_READ, AUTOMATION_TERMINAL, GAME_DESIGN_SOURCE, - WORLD_INVENTORY; + WORLD_INVENTORY, + GAME_DESIGN_PUBLICATION_TERMINAL, + ACCOUNT_PUBLICATION_SETTLEMENT, + ACCOUNT_PUBLICATION_HELD_READ, + ACCOUNT_PUBLICATION_ORDER, + GAME_DESIGN_PUBLICATION_SELECTION, + WORLD_PUBLICATION_TERMINAL; ClientHandle create( ServiceEndpointsProperties endpoints, @@ -214,6 +226,32 @@ ClientHandle create( var client = new WorldSelectedOwnerInventoryGrpcClient(endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); } + case GAME_DESIGN_PUBLICATION_TERMINAL -> { + var client = new GameDesignPublicationTerminalClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case ACCOUNT_PUBLICATION_SETTLEMENT -> { + var client = + new AccountSelectedPublicationSettlementClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case ACCOUNT_PUBLICATION_HELD_READ -> { + var client = + new AccountPublicationAuthorizationReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case ACCOUNT_PUBLICATION_ORDER -> { + var client = new AccountSelectedPublicationOrderClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GAME_DESIGN_PUBLICATION_SELECTION -> { + var client = new AuthoredDraftPublishSelectionReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case WORLD_PUBLICATION_TERMINAL -> { + var client = new WorldPublicationTerminalReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } }; } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java new file mode 100644 index 0000000000..7350166ede --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java @@ -0,0 +1,196 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationSettlementGrpcCodecTest { + @Test + void roundTripsBothCanonicalSixFrameReceiptsAndUsesIndependentCorrelation() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + for (Outcome outcome : Outcome.values()) { + var terminal = WorldPublicationTerminalTestFixtures.terminal(operation, outcome); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var decoded = + AccountSelectedPublicationSettlementGrpcCodec.fromRequest( + AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); + assertThat(decoded).isEqualTo(request); + + byte[] receipt = receipt(operation, terminal, null, null, null, null); + var response = AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt); + assertThat(AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, response)) + .containsExactly(receipt); + + var fresh = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat(fresh.originalOperation()).containsExactly(request.originalOperation()); + } + } + + @Test + void rejectsMalformedAndNoncanonicalRequestsAndUnknownFields() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var wire = AccountSelectedPublicationSettlementGrpcCodec.toRequest(request); + for (SettleSelectedPublicationRequest invalid : + List.of( + wire.toBuilder().setUnknownFields(unknown()).build(), + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + wire.toBuilder().setRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA").build(), + wire.toBuilder().setRequestId("1-1-1-1-1").build(), + wire.toBuilder().clearOriginalOperation().build(), + wire.toBuilder() + .setOriginalOperation( + wire.getOriginalOperation().concat(ByteString.copyFrom(new byte[] {0}))) + .build(), + wire.toBuilder().setOriginalOperation(ByteString.copyFrom(new byte[] {1})).build())) { + assertThatThrownBy(() -> AccountSelectedPublicationSettlementGrpcCodec.fromRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", + new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("4 MiB"); + } + + @Test + void rejectsChangedRequestEchoUnknownFieldsAndChangedOrNoncanonicalReceiptFrames() + throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var terminal = WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.NO_PUBLICATION); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var changedOperation = WorldPublicationTerminalTestFixtures.operation(); + var changedTerminal = + WorldPublicationTerminalTestFixtures.terminal(changedOperation, Outcome.PUBLISHED); + var sameOperationOtherOutcome = + WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.PUBLISHED); + byte[] receipt = receipt(operation, terminal, null, null, null, null); + var response = AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt); + var changedBinding = new byte[] {1, 2, 3}; + byte[] wrongOutcome = receipt(operation, terminal, "PUBLISHED", null, null, null); + byte[] wrongBinding = receipt(operation, terminal, null, changedBinding, null, null); + byte[] wrongOperation = + receipt(operation, terminal, null, null, changedOperation.canonicalBytes(), null); + byte[] wrongTerminal = receipt(operation, changedTerminal, null, null, null, null); + byte[] wrongWorldTerminal = + receipt(operation, terminal, null, null, null, sameOperationOtherOutcome.canonicalBytes()); + for (var invalid : + List.of( + response.toBuilder().setUnknownFields(unknown()).build(), + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder() + .setOriginalOperation(ByteString.copyFrom(changedOperation.canonicalBytes())) + .build(), + response.toBuilder().clearSettlementReceipt().build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongOutcome)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongBinding)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongOperation)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongTerminal)).build(), + response.toBuilder() + .setSettlementReceipt(ByteString.copyFrom(wrongWorldTerminal)) + .build(), + response.toBuilder() + .setSettlementReceipt( + response.getSettlementReceipt().concat(ByteString.copyFrom(new byte[] {0}))) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, wrongOutcome)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void enforcesCompleteSerializedMessageBudgetBeforeReceiptDecoding() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + byte[] oversizedReceipt = + new byte[AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES]; + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, oversizedReceipt)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("32 MiB"); + + var oversizedResponse = + SettleSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setSettlementReceipt(ByteString.copyFrom(oversizedReceipt)) + .build(); + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.fromResponse( + request, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("32 MiB"); + } + + private static byte[] receipt( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence terminal, + String outcomeOverride, + byte[] accountBindingOverride, + byte[] operationOverride, + byte[] worldTerminalOverride) { + String outcome = + outcomeOverride == null + ? terminal.outcome() == Outcome.PUBLISHED ? "PUBLISHED" : "ABORTED" + : outcomeOverride; + byte[] accountBinding = + accountBindingOverride == null + ? operation.account().canonicalBytes() + : accountBindingOverride; + byte[] operationBytes = + operationOverride == null ? operation.canonicalBytes() : operationOverride; + byte[] worldTerminal = + worldTerminalOverride == null ? terminal.canonicalBytes() : worldTerminalOverride; + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, accountBinding); + DraftAuthorizationFenceBinding.frame(out, operationBytes); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome); + DraftAuthorizationFenceBinding.frame(out, worldTerminal); + return out.toByteArray(); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java new file mode 100644 index 0000000000..6e66abf4af --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.common.publication; + +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.clearInvocations; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Transaction ordering units; mocked channels do not establish an mTLS handshake. */ +class GameDesignPublicationTerminalClientTransactionTest { + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void excludesActiveAndSynchronizationOnlyTransactionsBeforeAnyRpc(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("design.internal:6565"); + when(factory.buildChannel( + eq("design.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(mock(ManagedChannel.class)); + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private-key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "ca").toString()); + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", operation.canonicalBytes()); + var expected = + new GameDesignPublicationTerminalReadEvidence.ReadResult( + request, GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN, Optional.empty()); + var stub = + mock( + GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.readGameDesignPublicationTerminal(any())) + .thenReturn(GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, expected)); + + try (var client = new GameDesignPublicationTerminalClient(endpoints, tls, factory, "test")) { + client.init(); + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + assertThat(client.read(request).canonicalBytes()).containsExactly(expected.canonicalBytes()); + clearInvocations(stub); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + TransactionSynchronizationManager.clearSynchronization(); + verifyNoInteractions(stub); + + assertThat(client.read(request).canonicalBytes()).containsExactly(expected.canonicalBytes()); + } + } +} diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 0f4125817f..6bfc3db9fb 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -52,7 +52,6 @@ import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; @@ -1128,7 +1127,7 @@ public io.grpc.ServerCall.Listener interceptCall( } /** - * Actual immutable owner terminals; the local Account caller context is explicitly controlled. + * Actual immutable owner terminals and Account ingress over controlled loopback workload mTLS. */ private static void completeActualWorldAndAccountTerminals( Store gds, @@ -1151,6 +1150,7 @@ private static void completeActualWorldAndAccountTerminals( new net.firedevops.firemud.gamedesign.publication .GameDesignPublicationTerminalReadGrpcService(gdsOwner, NAMESPACE)); Server worldTerminalServer = null; + Server accountSettlementServer = null; var endpoints = new ServiceEndpointsProperties(); endpoints.setGameDesignService(loopback(gdsTerminalServer)); var channels = new GrpcChannelFactory(); @@ -1198,76 +1198,109 @@ private static void completeActualWorldAndAccountTerminals( var binding = net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding .fromStored(operation.canonicalBytes()); - var caller = - io.grpc.Context.current() - .withValue( - GrpcPeerIdentity.CONTEXT_KEY, - GrpcPeerIdentity.parseUri( - "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service") - .orElseThrow()); - // No caller transport is asserted here: this is the actual Account owner plus its two mTLS - // reads. - assertThatThrownBy(() -> caller.call(() -> accountOwner.settle(operation.canonicalBytes()))) - .isInstanceOf(RuntimeException.class); - assertThat( - accountDsl - .fetchSingle( - "SELECT count(*) FROM account_selected_publication_settlements WHERE operation_id = ?", - binding.account().operationId()) - .get(0, Long.class)) - .isZero(); - var published = - producer.reconcile( - operation.tenantKey(), - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence - .Outcome.PUBLISHED); - assertThat(published.operationBytes()).containsExactly(operation.canonicalBytes()); - assertThat( - producer - .reconcile( - operation.tenantKey(), - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - published.outcome()) - .canonicalBytes()) - .containsExactly(published.canonicalBytes()); - byte[] receipt = caller.call(() -> accountOwner.settle(operation.canonicalBytes())); - assertThat(receipt).isNotEmpty(); - String retained = - accountDsl - .fetchSingle( - "SELECT to_jsonb(s)::text || ':' || xmin::text FROM account_selected_publication_settlements s WHERE operation_id = ?", - binding.account().operationId()) - .get(0, String.class); - assertThat(caller.call(() -> accountOwner.settle(operation.canonicalBytes()))) - .containsExactly(receipt); - assertThat( - accountDsl - .fetchSingle( - "SELECT to_jsonb(s)::text || ':' || xmin::text FROM account_selected_publication_settlements s WHERE operation_id = ?", - binding.account().operationId()) - .get(0, String.class)) - .isEqualTo(retained); - assertThat( - accountDsl - .fetchSingle( - "SELECT game_design_terminal FROM account_selected_publication_settlements WHERE operation_id = ?", - binding.account().operationId()) - .get(0, byte[].class)) - .containsExactly(published.canonicalBytes()); - assertThat( - accountDsl - .fetchSingle( - "SELECT world_terminal FROM account_selected_publication_settlements WHERE operation_id = ?", - binding.account().operationId()) - .get(0, byte[].class)) - .containsExactly(published.canonicalBytes()); + accountSettlementServer = + ownerServer( + pki, + "account-service", + new AccountSelectedPublicationSettlementGrpcService(accountOwner, NAMESPACE)); + endpoints.setAccountService(loopback(accountSettlementServer)); + try (var settlementClient = + new net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + settlementClient.init(); + var settlementRequest = + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()); + try (var wrongCaller = + new net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + wrongCaller.init(); + assertThatThrownBy(() -> wrongCaller.settle(settlementRequest)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + } + assertThatThrownBy( + () -> + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertThat( + accountDsl + .fetchSingle( + "SELECT count(*) FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, Long.class)) + .isZero(); + var published = + producer.reconcile( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence + .Outcome.PUBLISHED); + assertThat(published.operationBytes()).containsExactly(operation.canonicalBytes()); + assertThat( + producer + .reconcile( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + published.outcome()) + .canonicalBytes()) + .containsExactly(published.canonicalBytes()); + byte[] receipt = + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes())); + assertThat(receipt).isNotEmpty(); + String retained = + accountDsl + .fetchSingle( + "SELECT to_jsonb(s)::text || ':' || xmin::text FROM account_selected_publication_settlements s WHERE operation_id = ?", + binding.account().operationId()) + .get(0, String.class); + assertThat( + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()))) + .containsExactly(receipt); + assertThat( + accountDsl + .fetchSingle( + "SELECT to_jsonb(s)::text || ':' || xmin::text FROM account_selected_publication_settlements s WHERE operation_id = ?", + binding.account().operationId()) + .get(0, String.class)) + .isEqualTo(retained); + assertThat( + accountDsl + .fetchSingle( + "SELECT game_design_terminal FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, byte[].class)) + .containsExactly(published.canonicalBytes()); + assertThat( + accountDsl + .fetchSingle( + "SELECT world_terminal FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, byte[].class)) + .containsExactly(published.canonicalBytes()); + } } } finally { + stop(accountSettlementServer); stop(worldTerminalServer); stop(gdsTerminalServer); } From c5176283f8540eefecea136d99e81d8696ba0aa3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 09:56:53 +1300 Subject: [PATCH 22/61] Converge current publication wire guards and source regressions --- ...ame-authoring-publishing-and-activation.md | 4 + .../player-access-and-session.md | 2 + .../DraftAuthorizationFenceRepository.java | 4 +- ...horizationFenceWorldParticipationTest.java | 27 +- ...electedPublicationSettlementGrpcCodec.java | 3 + ...ublicationTerminalCompletionGrpcCodec.java | 4 + .../common/gamedesign/AssetSourceTest.java | 270 ++++++++++++ .../CommandDefinitionClosedFieldsTest.java | 97 +++++ ...tedPublicationSettlementGrpcCodecTest.java | 27 ++ ...nPublicationTerminalReadGrpcCodecTest.java | 172 ++++++++ ...cationTerminalCompletionGrpcCodecTest.java | 37 ++ .../publication/AssetSnapshotTest.java | 101 +++++ .../RealmPolicySourceRetentionTest.java | 129 ++++++ .../publication/GameplayRuleSourceTest.java | 412 ++++++++++++++++++ 14 files changed, 1279 insertions(+), 10 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandDefinitionClosedFieldsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRetentionTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index b881313836..8d68ab4ada 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -22,6 +22,10 @@ Original World source/version registration and APPLIED input remain controlled f ### Selected publication settlement transport receiving +The canonical source continuation also preserves the donor's unique asset requiredness, identity, canonical payload, command closed-field, gameplay catalog/reference and realm-policy provenance regressions at their current owners. Terminal-read request and response refusal vectors use the current framed grammar, including explicit UNKNOWN, complete request echo, malformed or substituted terminal rejection and defensive original bytes. These structural and owner-local units use controlled values; they do not establish original authority, production activation or genuine physical handoffs. + +Current Account settlement and World terminal-completion requests require the complete v2 operation tag before owner access. The shared decoder preserves historical v1 operation and terminal bytes for history reads; that support does not widen either current transport contract. Both codecs reject the historical profile from direct request construction and protobuf decoding, following the existing rule that retained history does not widen consumers that lack older-profile support. + The selected Account order, held-read and settlement clients, Game Design selection and terminal-read clients, and World terminal-read client release their local monitor before the shared certificate watcher drains an in-flight reload callback. Their close flags still deny reuse; the existing selected-owner lifecycle matrix covers callback contention, idempotent shutdown and closed-client initialization denial. The canonical Game Design publication terminal client retains the original donor's local transaction exclusion: active owner SQL and synchronization-only contexts fail before transport access. This guard stays on the current closed framed terminal-read API; the alternate donor client, evidence type and service are not reintroduced. 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 85e1babaef..fc42eb4701 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected publication owner preparation +The disclosure source-lock adapter preserves complete keys through the canonical 2,048 UTF-8 byte bound already owned by shared source evidence and V76 storage. It no longer applies the obsolete 512-byte Java limit. The focused unit covers legacy and longer keys, ASCII and Unicode at the exact byte boundary, and rejection beyond it without truncation or aliasing; physical source-lock and disclosure behavior retain their separately attributed native proof. + The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. R14 freshly passes eleven focused Account native cases and the real six-store Game Design/World terminal-to-Account settlement composition, including refusal before World completion, exact post-commit receipt replay and nine malformed closure/profile refusals. The latter uses both actual terminal owners and mTLS reads; the local inbound Account caller context remains explicitly controlled. Forward V1011 accepts only the canonical paired legacy and closure inventory profiles, preserving the existing frame, correlation, source and artifact guards. No installed migration is rewritten. R16 freshly passes the added V1010-to-current retained-settlement upgrade case for both original terminal outcomes after the test fixture explicitly supports that predecessor. Authorization, source, settlement, issuer and prior Flyway rows retain their exact bytes and row versions through upgrade and replay. The other twelve passing native cases retain R14 attribution; all have zero skips. Account's twenty-five focused units and Common's seven typed-order units retain their preceding pass, and affected generation, static, formatting and documentation checks pass. R14's passive capture owns all eight exact run-created PostgreSQL containers; R16 owns its one, with no ownership gaps or observer errors. Upstream creator, issuer, environment and PKI remain controlled. These owners remain unregistered and grant no publication finalizer, player admission, genuine authority or runtime activation. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 96fa1d078a..ec905e7362 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -295,9 +295,9 @@ public void lockDisclosureSources(List exactSources) { throw new IllegalArgumentException("Distinct exact disclosure source evidence required"); } for (SourceEvidence source : sources) { - if (source.key().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 512) { + if (source.key().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 2048) { throw new IllegalArgumentException( - "Disclosure source key exceeds the existing Account source-lock bound"); + "Disclosure source key exceeds the Account source-lock bound"); } } lockSources(sources); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java index 110290b1c5..53396c39fb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java @@ -148,19 +148,30 @@ void pendingWorldParticipationBlocksSourceMutationAndAbortWhileSettledKeepsPrior } @Test - void disclosureSourceLockPreservesTheExisting512ByteBoundWithoutAliasing() throws Exception { + void disclosureSourceLocksRetainCompleteCanonicalKeysThrough2048Utf8Bytes() throws Exception { Fixture fixture = new Fixture(false); fixture.begin(); - SourceEvidence boundary = source("x".repeat(499)); - assertThat(boundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(512); + SourceEvidence legacy = source("x".repeat(499)); + SourceEvidence longer = source("x".repeat(500)); + SourceEvidence boundary = source("x".repeat(2035)); + SourceEvidence unicodeBoundary = source("😀".repeat(508) + "xxx"); + assertThat(legacy.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(512); + assertThat(longer.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(513); + assertThat(boundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(2048); + assertThat(unicodeBoundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .hasSize(2048); - fixture.repository.lockDisclosureSources(List.of(boundary)); + // V76 and the shared SourceEvidence already own this exact byte bound; retain the whole key. + for (var source : List.of(legacy, longer, boundary, unicodeBoundary)) { + fixture.repository.lockDisclosureSources(List.of(source)); + } - assertThat(fixture.lockedKeys).containsExactly(boundary.key()); - assertThatThrownBy( - () -> fixture.repository.lockDisclosureSources(List.of(source("x".repeat(500))))) + assertThat(fixture.lockedKeys) + .containsExactly(legacy.key(), longer.key(), boundary.key(), unicodeBoundary.key()); + assertThat(longer.key()).startsWith(legacy.key()).isNotEqualTo(legacy.key()); + assertThatThrownBy(() -> source("x".repeat(2036))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("existing Account source-lock bound"); + .hasMessageContaining("2048 UTF-8 bytes"); } private static SourceChange sourceChange(SourceEvidence source) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java index a9ccc03f4f..b911a2b407 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java @@ -202,6 +202,9 @@ public record Request( originalOperation = originalOperation.clone(); GameDesignPublicationOperationBinding operation; try { + // Shared decoding preserves historical v1; this current wire requires complete v2 input. + new DraftAuthorizationFenceBinding.FrameReader(originalOperation) + .expect(GameDesignPublicationOperationBinding.SCHEMA); operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); } catch (RuntimeException malformed) { throw new IllegalArgumentException( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java index 8e799ce14c..71872ef675 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationRequest; @@ -184,6 +185,9 @@ public record Request( gameDesignTerminalEvidence = gameDesignTerminalEvidence.clone(); GameDesignPublicationTerminalEvidence terminal; try { + // Historical decoding must not widen this complete-v2 completion transport. + new DraftAuthorizationFenceBinding.FrameReader(originalOperation) + .expect(GameDesignPublicationOperationBinding.SCHEMA); terminal = GameDesignPublicationTerminalEvidence.fromStored(gameDesignTerminalEvidence); } catch (RuntimeException malformed) { throw new IllegalArgumentException( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java new file mode 100644 index 0000000000..eb8beecde7 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java @@ -0,0 +1,270 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class AssetSourceTest { + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID VERSION = UUID.randomUUID(); + + @Test + void extractionPreservesExactBindingOrderAndExplicitRequiredness() { + var binding = + binding( + AssetSource.upsertPayload( + "9223372036854775807", " Logo.png ", AssetSource.Requiredness.REQUIRED), + "{\"revisionKind\":\"COMMAND_DEFINITION\"}", + "{\"revisionKind\":\"REALM_ENTRY_POLICY\"}", + AssetSource.upsertPayload("2", "required.png", AssetSource.Requiredness.REQUIRED)); + var mutations = AssetSource.mutations(binding); + + assertThat(mutations).hasSize(2); + assertThat(mutations).extracting(AssetSource.Mutation::revisionOrder).containsExactly("0", "3"); + assertThat(mutations.getFirst().binding()).isSameAs(binding); + assertThat(mutations.getFirst().revisionId()) + .isEqualTo(binding.revisions().getFirst().revisionId()); + assertThat(mutations.getFirst().usageKey()).isEqualTo(" Logo.png "); + assertThat(mutations.getFirst().requiredness()).isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(mutations.getLast().requiredness()).isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(mutations.getFirst().binding()).isSameAs(binding); + assertThatThrownBy(() -> mutations.clear()).isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void replayReplacesOnlyExplicitKeysAndRetainsExactSourceProvenance() { + var original = + binding( + AssetSource.upsertPayload("1", "one.png", AssetSource.Requiredness.REQUIRED), + AssetSource.upsertPayload("2", "two.png", AssetSource.Requiredness.REQUIRED)); + var baseline = AssetSource.replay(List.of(), original); + var changed = + binding( + AssetSource.deletePayload("one.png"), + AssetSource.upsertPayload("3", "one.png", AssetSource.Requiredness.REQUIRED)); + var result = AssetSource.replay(baseline.references(), changed); + + assertThat(result.binding()).isSameAs(changed); + assertThat(result.references()) + .extracting(AssetSource.Reference::usageKey) + .containsExactly("one.png", "two.png"); + assertThat(result.references().getFirst().assetRowId()).isEqualTo("3"); + assertThat(result.references().getFirst().requiredness()) + .isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(result.references().getFirst().family()).isEqualTo("ORDINARY"); + assertThat(result.references().getFirst().role()).isEqualTo("RESOURCE"); + assertThat(result.references().getFirst().sourceBinding()).isSameAs(changed); + assertThat(result.references().getLast().sourceBinding()).isSameAs(original); + assertThat(AssetSource.replay(result.references(), changed)).isEqualTo(result); + assertThat( + AssetSource.replay(result.references(), binding(AssetSource.deletePayload("two.png"))) + .references()) + .extracting(AssetSource.Reference::usageKey) + .containsExactly("one.png"); + } + + @Test + void referenceCannotRewriteItsBoundRequirednessOrRevisionIdentity() { + var binding = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var revision = binding.revisions().getFirst(); + + assertThatThrownBy( + () -> + new AssetSource.Reference( + "logo.png", + "1", + AssetSource.Requiredness.OPTIONAL, + binding, + "0", + revision.revisionId())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AssetSource.Reference( + "logo.png", + "1", + AssetSource.Requiredness.REQUIRED, + binding, + "0", + UUID.randomUUID())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void snapshotRejectsForeignTargetDuplicateKeysAndSourceAliases() { + var original = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var references = AssetSource.replay(List.of(), original).references(); + var foreign = binding(UUID.randomUUID(), AssetSource.deletePayload("logo.png")); + + assertThatThrownBy(() -> AssetSource.replay(references, foreign)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AssetSource.Snapshot( + original, List.of(references.getFirst(), references.getFirst()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AssetSource.replay( + references, + binding( + AssetSource.upsertPayload( + "1", "alias.png", AssetSource.Requiredness.REQUIRED)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void snapshotDefensivelyRetainsItsReferenceList() { + var binding = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var mutable = new ArrayList<>(AssetSource.replay(List.of(), binding).references()); + var snapshot = new AssetSource.Snapshot(binding, mutable); + mutable.clear(); + + assertThat(snapshot.references()).hasSize(1); + assertThatThrownBy(() -> snapshot.references().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "0", + "01", + "-1", + "+1", + "1.0", + "1e2", + " 1", + "9223372036854775808", + "999999999999999999999999" + }) + void deniesNoncanonicalOrOverflowingOwnerRowId(String value) { + assertThatThrownBy( + () -> AssetSource.mutations(binding(upsert("\"" + value + "\"", "\"REQUIRED\"")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"1", "1.0", "1e0", "null", "true", "{}", "[]"}) + void ownerRowIdMustBeTextNotCoercedJson(String value) { + assertThatThrownBy(() -> AssetSource.mutations(binding(upsert(value, "\"REQUIRED\"")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"\"UNKNOWN\"", "\"required\"", "null", "true", "1", "{}"}) + void deniesUnknownOrUntypedRequiredness(String value) { + assertThatThrownBy(() -> AssetSource.mutations(binding(upsert("\"1\"", value)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void deniesMissingRequirednessUnknownMembersDuplicateFieldsAndTrailingJson() { + String valid = upsert("\"1\"", "\"REQUIRED\""); + List invalid = + List.of( + valid.replace(",\"requiredness\":\"REQUIRED\"", ""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1.0"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":\"1\""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":2"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"), + valid.replace("\"usageKey\":\"logo.png\"", "\"usageKey\":\"logo.png\",\"extra\":true"), + valid + " {}", + "{\"revisionKind\":\"UNSUPPORTED\"}", + "{}", + AssetSource.deletePayload("logo.png") + .replace( + "\"operation\":\"DELETE\"", + "\"operation\":\"DELETE\",\"requiredness\":\"OPTIONAL\"")); + for (String payload : invalid) { + assertThatThrownBy(() -> AssetSource.mutations(binding(payload))) + .as(payload) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void usageKeyIsExactBoundedAndCannotReserveManifestName() { + for (String key : List.of("", " ", "manifest.json", "x".repeat(256))) { + assertThatThrownBy( + () -> AssetSource.upsertPayload("1", key, AssetSource.Requiredness.REQUIRED)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat( + AssetSource.mutations( + binding( + AssetSource.upsertPayload( + "1", "x".repeat(255), AssetSource.Requiredness.REQUIRED)))) + .hasSize(1); + } + + @Test + void ordinaryResourceCannotClaimOptionalPresentationOrAnUnknownFamilyOrRole() { + assertThatThrownBy( + () -> AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.OPTIONAL)) + .isInstanceOf(IllegalArgumentException.class); + String required = upsert("\"1\"", "\"REQUIRED\""); + for (String payload : + List.of( + required.replace("REQUIRED", "OPTIONAL"), + required.replace("ORDINARY", "BRANDING"), + required.replace("RESOURCE", "PRESENTATION"), + required.replace(",\"role\":\"RESOURCE\"", ""), + required.replace(",\"family\":\"ORDINARY\"", ""))) { + assertThatThrownBy(() -> AssetSource.mutations(binding(payload))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static String upsert(String rowIdJson, String requirednessJson) { + return "{\"schemaVersion\":1,\"revisionKind\":\"ASSET_REFERENCE\",\"family\":\"ORDINARY\",\"role\":\"RESOURCE\",\"operation\":\"UPSERT\",\"assetRowId\":" + + rowIdJson + + ",\"usageKey\":\"logo.png\",\"requiredness\":" + + requirednessJson + + "}"; + } + + private static DraftCommitBinding binding(String... payloads) { + return binding(VERSION, payloads); + } + + private static DraftCommitBinding binding(UUID versionId, String... payloads) { + List revisions = new ArrayList<>(); + for (int index = 0; index < payloads.length; index++) { + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[index])); + } + return DraftCommitBinding.create( + new TargetProof(TENANT, versionId, 23L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + versionId.toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + "0"))); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandDefinitionClosedFieldsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandDefinitionClosedFieldsTest.java new file mode 100644 index 0000000000..5166f916ff --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandDefinitionClosedFieldsTest.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +class CommandDefinitionClosedFieldsTest { + private static final String VALID_DEFINITION = + """ + { + "schemaVersion": 1, + "commandId": "salute", + "semanticOwner": "GAME_LOGIC", + "executionDiscipline": "DURABLE_GAMEPLAY", + "stageRequirement": "GAMEPLAY", + "promptPolicy": "WHEN_GAMEPLAY", + "actionCategory": "SOCIAL", + "historyRecordable": true, + "aliases": ["salute"], + "actionTags": ["COMMUNICATION"], + "effects": [ + { + "effectKind": "APPLY_ACTION_STATE", + "schemaVersion": 1, + "targeting": "SELF", + "replayPolicy": "EFFECT_IDEMPOTENT", + "payload": { + "conditionKey": "SALUTING", + "durationSeconds": 30, + "effectPayload": { + "modifiers": [ + { + "operation": "ADD", + "target_key": "salute_count", + "value": 1, + "scope_kind": "ACTION_FAMILY", + "scope_key": "social", + "priority": 2 + } + ] + } + } + } + ] + } + """; + + @Test + void acceptsCanonicalDefinitionAndDefinedOptionalModifierFields() { + assertThat(CommandSource.upsertPayload(VALID_DEFINITION)).isNotBlank(); + } + + @Test + void acceptsCanonicalDefinitionWhenAllOptionalModifierFieldsAreAbsent() { + String definitionWithoutOptionalModifierFields = + VALID_DEFINITION.replace( + ",\n \"scope_kind\": \"ACTION_FAMILY\",\n \"scope_key\": \"social\",\n \"priority\": 2", + ""); + + assertThat(definitionWithoutOptionalModifierFields) + .doesNotContain("scope_kind", "scope_key", "priority"); + assertThat(CommandSource.upsertPayload(definitionWithoutOptionalModifierFields)).isNotBlank(); + } + + @Test + void rejectsUnknownDefinitionFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"commandId\": \"salute\",", "\"targetSelectionPolicyKey\": \"self\","); + } + + @Test + void rejectsUnknownEffectFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"effectKind\": \"APPLY_ACTION_STATE\",", "\"targetSetKey\": \"SOURCE\","); + } + + @Test + void rejectsUnknownPayloadFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"conditionKey\": \"SALUTING\",", "\"sourceRuleId\": \"rule-1\","); + } + + @Test + void rejectsUnknownEffectPayloadFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"effectPayload\": {", "\"targetRefs\": [],"); + } + + @Test + void rejectsUnknownModifierFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"operation\": \"ADD\",", "\"targetTemplateId\": \"item-1\","); + } + + private static void assertRejected(String marker, String insertion) { + String unsupported = VALID_DEFINITION.replace(marker, marker + insertion); + assertThat(unsupported).isNotEqualTo(VALID_DEFINITION); + assertThatThrownBy(() -> CommandSource.upsertPayload(unsupported)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java index 7350166ede..f59a9cb65d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java @@ -42,6 +42,33 @@ void roundTripsBothCanonicalSixFrameReceiptsAndUsesIndependentCorrelation() thro } } + @Test + void retainsV1HistoryButRejectsItFromCurrentSettlementRequests() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var history = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(history, "game-design-publication-operation/v1"); + DraftAuthorizationFenceBinding.frame(history, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(history, operation.world().canonicalBytes()); + byte[] original = history.toByteArray(); + assertThat(GameDesignPublicationOperationBinding.fromStored(original).canonicalBytes()) + .containsExactly(original); + + assertThatThrownBy( + () -> AccountSelectedPublicationSettlementGrpcCodec.Request.create("test", original)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Complete canonical original publication operation required"); + var current = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var changed = + AccountSelectedPublicationSettlementGrpcCodec.toRequest(current).toBuilder() + .setOriginalOperation(ByteString.copyFrom(original)) + .build(); + assertThatThrownBy(() -> AccountSelectedPublicationSettlementGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account publication settlement request is invalid"); + } + @Test void rejectsMalformedAndNoncanonicalRequestsAndUnknownFields() throws Exception { var operation = WorldPublicationTerminalTestFixtures.operation(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..bee71c9c09 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java @@ -0,0 +1,172 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import org.junit.jupiter.api.Test; + +/** Preserved donor refusal vectors mapped to the canonical framed read, with controlled inputs. */ +class GameDesignPublicationTerminalReadGrpcCodecTest { + @Test + void retainsExactReadCorrelationAndTerminalBytesForEveryCanonicalStatus() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = ReadRequest.create("test", operation.canonicalBytes()); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request))) + .isEqualTo(request); + for (Status status : Status.values()) { + var terminal = + status == Status.UNKNOWN + ? Optional + . + empty() + : Optional.of( + WorldPublicationTerminalTestFixtures.terminal( + operation, Outcome.valueOf(status.name()))); + var result = new ReadResult(request, status, terminal); + var response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .containsExactly(result.canonicalBytes()); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .containsExactly(result.canonicalBytes()); + } + } + + @Test + void rejectsUnknownMalformedNoncanonicalAndIncompleteFramedRequests() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = ReadRequest.create("test", operation.canonicalBytes()); + var wire = GameDesignPublicationTerminalReadGrpcCodec.toRequest(request); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class); + for (byte[] invalid : + List.of( + new byte[0], + new byte[] {1}, + replaceFrame(request.canonicalBytes(), 1, text("2")), + replaceFrame(request.canonicalBytes(), 2, text("Test")), + replaceFrame(request.canonicalBytes(), 2, text("other")), + replaceFrame(request.canonicalBytes(), 3, text("00000000-0000-0000-0000-000000000000")), + replaceFrame(request.canonicalBytes(), 3, text("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA")), + replaceFrame(request.canonicalBytes(), 3, text("1-1-1-1-1")), + replaceFrame(request.canonicalBytes(), 4, new byte[0]), + replaceFrame(request.canonicalBytes(), 4, new byte[] {1}), + java.util.Arrays.copyOf( + request.canonicalBytes(), request.canonicalBytes().length + 1))) { + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + wire.toBuilder() + .setCanonicalRequestBytes(ByteString.copyFrom(invalid)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsChangedEchoUnknownMalformedMissingAndSubstitutedTerminalResponses() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = ReadRequest.create("test", operation.canonicalBytes()); + var terminal = WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.NO_PUBLICATION); + var result = new ReadResult(request, Status.NO_PUBLICATION, Optional.of(terminal)); + var wire = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result); + var changedRequest = ReadRequest.create("test", operation.canonicalBytes()); + var changedTerminal = + WorldPublicationTerminalTestFixtures.terminal( + WorldPublicationTerminalTestFixtures.operation(), Outcome.NO_PUBLICATION); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, wire.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class); + for (byte[] invalid : + List.of( + new byte[0], + new byte[] {1}, + replaceFrame(result.canonicalBytes(), 1, changedRequest.canonicalBytes()), + replaceFrame(result.canonicalBytes(), 2, text("UNKNOWN")), + replaceFrame(result.canonicalBytes(), 2, text("PUBLISHED")), + replaceFrame(result.canonicalBytes(), 3, new byte[0]), + replaceFrame(result.canonicalBytes(), 3, new byte[] {1}), + replaceFrame(result.canonicalBytes(), 3, changedTerminal.canonicalBytes()), + java.util.Arrays.copyOf(result.canonicalBytes(), result.canonicalBytes().length + 1))) { + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, + wire.toBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(invalid)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + var changedResult = + new ReadResult(changedRequest, Status.NO_PUBLICATION, Optional.of(terminal)); + assertThatThrownBy( + () -> GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, changedResult)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadResult(request, Status.UNKNOWN, Optional.of(terminal))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadResult(request, Status.PUBLISHED, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void retainsDefensiveOperationBytesAndRejectsReusedOriginalIdentity() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + byte[] input = operation.canonicalBytes(); + var request = ReadRequest.create("test", input); + java.util.Arrays.fill(input, (byte) 0); + assertThat(request.operationBytes()).containsExactly(operation.canonicalBytes()); + byte[] returned = request.operationBytes(); + java.util.Arrays.fill(returned, (byte) 0); + assertThat(request.operationBytes()).containsExactly(operation.canonicalBytes()); + assertThatThrownBy( + () -> + new ReadRequest( + 1, "test", operation.account().operationId(), operation.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static byte[] text(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static byte[] replaceFrame(byte[] framed, int target, byte[] replacement) { + var input = ByteBuffer.wrap(framed); + var output = new ByteArrayOutputStream(); + for (int index = 0; input.hasRemaining(); index++) { + int length = input.getInt(); + byte[] value = new byte[length]; + input.get(value); + DraftAuthorizationFenceBinding.frame(output, index == target ? replacement : value); + } + return output.toByteArray(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java index c46c8135fe..af7d66dd4a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java @@ -5,8 +5,10 @@ import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationRequest; @@ -41,6 +43,41 @@ void roundTripsBothTerminalOutcomesAndUsesIndependentTransportCorrelation() thro } } + @Test + void historicalTerminalReadbackCannotEnterCurrentV2CompletionTransport() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var history = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(history, "game-design-publication-operation/v1"); + DraftAuthorizationFenceBinding.frame(history, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(history, operation.world().canonicalBytes()); + byte[] original = history.toByteArray(); + var historicalTerminal = + new GameDesignPublicationTerminalEvidence(original, Outcome.NO_PUBLICATION, null, null); + assertThat( + GameDesignPublicationTerminalEvidence.fromStored(historicalTerminal.canonicalBytes()) + .operationBytes()) + .containsExactly(original); + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", original, historicalTerminal.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Complete canonical publication operation and terminal required"); + + var currentTerminal = + WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.NO_PUBLICATION); + var current = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), currentTerminal.canonicalBytes()); + var changed = + WorldPublicationTerminalCompletionGrpcCodec.toRequest(current).toBuilder() + .setOriginalOperation(ByteString.copyFrom(original)) + .setGameDesignTerminalEvidence(ByteString.copyFrom(historicalTerminal.canonicalBytes())) + .build(); + assertThatThrownBy(() -> WorldPublicationTerminalCompletionGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void rejectsMalformedAndNoncanonicalRequestsAndUnknownFields() throws Exception { var operation = WorldPublicationTerminalTestFixtures.operation(); diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java new file mode 100644 index 0000000000..4f54642590 --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java @@ -0,0 +1,101 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import org.junit.jupiter.api.Test; + +class AssetSnapshotTest { + @Test + void exactTypedSnapshotRoundTripsAndOwnsItsImmutableCollection() { + var binding = binding(); + var reference = AssetSource.replay(List.of(), binding).references().getFirst(); + var item = + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[] {1, 2}), 2); + var mutable = new ArrayList<>(List.of(item)); + var snapshot = new AssetSnapshot(binding, "1", null, UUID.randomUUID(), mutable); + mutable.clear(); + assertThat(AssetSnapshot.fromStored(snapshot.canonicalJson())).isEqualTo(snapshot); + assertThat(snapshot.items()).containsExactly(item); + assertThatThrownBy(() -> snapshot.items().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(snapshot.items().getFirst().reference().family()).isEqualTo("ORDINARY"); + assertThat(snapshot.items().getFirst().reference().role()).isEqualTo("RESOURCE"); + assertThat(new AssetApplication(binding, "0", snapshot).appliedEpoch().resultingEpoch()) + .isEqualTo("1"); + assertThatThrownBy(() -> new AssetApplication(binding, "1", snapshot)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void storedSnapshotCannotChangeBoundRequirednessIdentityOrCanonicalRepresentation() { + var binding = binding(); + var reference = AssetSource.replay(List.of(), binding).references().getFirst(); + var snapshot = + new AssetSnapshot( + binding, + "1", + null, + UUID.randomUUID(), + List.of( + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[0]), 0))); + String json = snapshot.canonicalJson(); + for (String invalid : + List.of( + json.replace("\"requiredness\":\"REQUIRED\"", "\"requiredness\":\"OPTIONAL\""), + json.replace("\"family\":\"ORDINARY\"", "\"family\":\"UNKNOWN\""), + json.replace("\"role\":\"RESOURCE\"", "\"role\":\"PRESENTATION\""), + " " + json)) { + assertThatThrownBy(() -> AssetSnapshot.fromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "", CommandSource.sha256(new byte[0]), 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", "sha256:00", 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[0]), -1)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DraftCommitBinding binding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "tenant", 2, "tenant", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.upsertPayload("3", "logo.png", AssetSource.Requiredness.REQUIRED))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + target.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + "0"))); + } +} diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRetentionTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRetentionTest.java new file mode 100644 index 0000000000..7a614e30f7 --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRetentionTest.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.Test; + +class RealmPolicySourceRetentionTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID GENESIS_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + + @Test + void schema3ActorCoreAndOriginalPolicyProvenanceSurviveOwnerApplication() { + String policyJson = + "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PLAYER_CREATED\"," + + "\"creationDescriptor\":{\"schemaVersion\":1,\"descriptorId\":\"11111111-1111-4111-8111-111111111111\"," + + "\"descriptorRevisionId\":\"22222222-2222-4222-8222-222222222222\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}"; + String payload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmEntryPolicy.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r3", + "policy", + RealmPolicySource.tree(policyJson))); + DraftCommitBinding binding = + DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-commit-0", + List.of( + new RevisionPayload("0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION_ID.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + var policy = RealmPolicySource.revision(binding, binding.revisions().getFirst()); + var snapshot = new RealmPolicySnapshot(binding, "1", List.of(policy)); + var application = new RealmPolicyApplication(freshGenesis(), null, "0", snapshot); + var retained = RealmPolicySnapshot.fromStored(application.snapshot().canonicalJson()); + var retainedPolicy = retained.policies().getFirst(); + + assertThat(retainedPolicy.commitId()).isEqualTo(COMMIT_ID); + assertThat(retainedPolicy.revisionId()).isEqualTo(REVISION_ID); + assertThat(retainedPolicy.logicalRevisionId()).isEqualTo("policy-logical-r3"); + assertThat(retainedPolicy.policy().initialActorCore().displayName()).isEqualTo("Wayfarer"); + assertThat(retainedPolicy.policy().initialActorCore().dispositionKey()).isEqualTo("newcomer"); + assertThat(application.canonicalBytes()).containsSequence(retained.canonicalBytes()); + } + + @Test + void missingBothGenesisAndInheritedCommitAndInvalidRequiredTextAreRejected() { + RealmPolicySnapshot snapshot = snapshot(); + + assertThatThrownBy(() -> new RealmPolicyApplication(null, null, "0", snapshot)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new RealmPolicyApplication(freshGenesis(), null, "invalid", snapshot())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void knownSiblingSourceKindsAreNonPolicyAndUnknownKindsStillDeny() { + assertThat(RealmPolicySource.isPolicyRevision(revision(BrandingSource.REVISION_KIND))) + .isFalse(); + assertThat(RealmPolicySource.isPolicyRevision(revision(TemplateConfigSource.REVISION_KIND))) + .isFalse(); + assertThatThrownBy(() -> RealmPolicySource.isPolicyRevision(revision("UNKNOWN_SOURCE"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported Game Design owner revision kind"); + } + + private static RealmPolicyGenesis freshGenesis() { + return new RealmPolicyGenesis(target(), GENESIS_ID, "17"); + } + + private static RealmPolicySnapshot snapshot() { + DraftCommitBinding binding = + DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-commit-0", + List.of(new RevisionPayload("0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION_ID.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + return new RealmPolicySnapshot(binding, "1", List.of()); + } + + private static TargetProof target() { + return new TargetProof( + TENANT_ID, VERSION_ID, 23L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + } + + private static RevisionPayload revision(String kind) { + return new RevisionPayload( + "0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, "{\"revisionKind\":\"" + kind + "\"}"); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java new file mode 100644 index 0000000000..8dc7c51ca7 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java @@ -0,0 +1,412 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Ability; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Action; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActionCategory; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActionTag; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActorRole; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.AdmissionTag; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CandidateSelector; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CapacityChangePolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cardinality; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Command; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CommitPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Condition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ContinuousOverlay; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cooldown; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cost; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.DefaultBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Definition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.DurationPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Effect; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.EffectBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.EffectOperation; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ExecutionDiscipline; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Lifecycle; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ObservationPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Predicate; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PredicateKind; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PrimitiveKind; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PromptPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Reapplication; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ReplayPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Resource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.SelectionPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.SelectionStrategy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stage; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stat; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.StatField; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetSet; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetingPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import org.junit.jupiter.api.Test; + +class GameplayRuleSourceTest { + private static final TargetProof TARGET = + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + "private-owner-key", + 1L, + "private-owner-key", + "NEW_GAME_ROW"); + + @Test + void realNonemptyCatalogRetainsOrderedDeclarationsAndEveryOriginalRevision() { + var manifest = exampleManifest(); + var binding = + binding( + manifest.families().values().stream() + .flatMap(List::stream) + .map(GameplayRuleSource::upsertPayload) + .toList()); + var entries = GameplayRuleSource.replay(List.of(), binding); + var snapshot = new GameplayRuleSnapshot(binding, "1", null, UUID.randomUUID(), entries); + var read = GameplayRuleSnapshot.fromStored(snapshot.canonicalJson()); + + assertThat(read.canonicalBytes()).containsExactly(snapshot.canonicalBytes()); + assertThat(read.manifest().canonicalBytes()).containsExactly(manifest.canonicalBytes()); + assertThat(read.entries()).hasSize(entries.size()); + assertThat(read.entries()) + .allSatisfy(entry -> assertThat(entry.sourceBinding()).isEqualTo(binding)); + var action = (Action) read.manifest().families().get(Family.ACTIONS).getFirst(); + assertThat(action.admissionTags()).containsExactly("gameplay", "canFocus"); + assertThat(action.effects()) + .extracting(EffectBinding::effectKey) + .containsExactly("restore", "cleanse"); + var command = (Command) read.manifest().families().get(Family.COMMANDS).getFirst(); + assertThat(command.actionTags()).containsExactly(ActionTag.COMBAT); + assertThat(command.admissionTags()).containsExactly("gameplay", "canFocus"); + } + + @Test + void inheritedCatalogPreservesUnchangedProvenanceAndExplicitDelete() { + var initial = + binding( + List.of( + GameplayRuleSource.upsertPayload(new AdmissionTag("first")), + GameplayRuleSource.upsertPayload(new AdmissionTag("second")))); + var original = GameplayRuleSource.replay(List.of(), initial); + var changed = + binding( + List.of( + GameplayRuleSource.deletePayload(Family.ADMISSION_TAGS, "first"), + GameplayRuleSource.upsertPayload(new AdmissionTag("third")))); + var replayed = GameplayRuleSource.replay(original, changed); + assertThat(replayed) + .extracting(entry -> entry.definition().key()) + .containsExactly("second", "third"); + assertThat(replayed.getFirst().sourceBinding()).isEqualTo(initial); + assertThat(replayed.getLast().sourceBinding()).isEqualTo(changed); + assertThatThrownBy( + () -> + GameplayRuleSource.replay( + replayed, + binding( + List.of( + GameplayRuleSource.deletePayload(Family.ADMISSION_TAGS, "missing"))))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void authoredDispositionAndRequiredFeedbackRetainTypedSelectedRevisionProvenance() { + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor.created", + Audience.SOURCE_ACTOR, + "actor.created", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + ReplayPolicy.EFFECT_IDEMPOTENT); + var selected = + binding( + List.of( + GameplayRuleSource.upsertPayload(disposition), + GameplayRuleSource.upsertPayload(feedback))); + var entries = GameplayRuleSource.replay(List.of(), selected); + var manifest = GameplayRuleSource.manifest(entries); + + assertThat(manifest.families().keySet()).containsExactlyInAnyOrder(Family.values()); + for (Family family : Family.values()) { + if (family != Family.DISPOSITIONS && family != Family.FEEDBACK) { + assertThat(manifest.families().get(family)).isEmpty(); + } + } + assertThat(manifest.families().get(Family.DISPOSITIONS)).containsExactly(disposition); + assertThat(manifest.families().get(Family.FEEDBACK)).containsExactly(feedback); + assertThat(entries).extracting(GameplayRuleSource.Entry::sourceBinding).containsOnly(selected); + assertThat(entries) + .extracting(GameplayRuleSource.Entry::revisionOrder) + .containsExactly("0", "1"); + } + + @Test + void incompleteInventoryAndUnresolvedReferencesDenyInsteadOfBecomingEmpty() { + var families = + new EnumMap>(GameplayRuleManifest.explicitEmpty().families()); + families.remove(Family.FEEDBACK); + assertThatThrownBy(() -> new GameplayRuleManifest(families)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleSource.replay( + List.of(), + binding( + List.of( + GameplayRuleSource.upsertPayload( + new Ability("ability", "Ability", "missingAction")))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unresolved ACTIONS"); + assertThatThrownBy( + () -> + GameplayRuleManifest.fromStored( + "{\"schema\":\"gameplay-rule-manifest/v1\",\"families\":{}}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void unknownDefinitionFieldsDuplicateFieldsAndMissingAdmissionTagsDeny() { + String command = + GameplayRuleManifest.canonical( + exampleManifest().families().get(Family.COMMANDS).getFirst()); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.COMMANDS, + command.replace("\"admissionTags\":[\"gameplay\",\"canFocus\"],", ""))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.ADMISSION_TAGS, "{\"tagKey\":\"tag\",\"unknownPolicy\":true}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.ADMISSION_TAGS, "{\"tagKey\":\"first\",\"tagKey\":\"second\"}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition(Family.ADMISSION_TAGS, "{\"tagKey\":\"first\"} {}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleSource.mutations( + binding(List.of("{\"revisionKind\":\"UNKNOWN_RULE_FAMILY\"}")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void continuousEffectsCannotBecomeInstantActionEffectsOrGrantDeniedAdmission() { + var source = exampleManifest(); + var families = new EnumMap>(source.families()); + Action action = (Action) families.get(Family.ACTIONS).getFirst(); + families.put( + Family.ACTIONS, + List.of( + new Action( + action.key(), + action.name(), + action.admissionTags(), + action.targetSets(), + action.costs(), + action.cooldowns(), + List.of(new EffectBinding("capacity", "SOURCE")), + action.feedbackKeys()))); + assertThatThrownBy(() -> new GameplayRuleManifest(families)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.CONTINUOUS_OVERLAYS, + GameplayRuleManifest.canonical( + Map.of( + "overlayKey", + "overlay", + "eligibleWhen", + truth(), + "deniedAdmissionTags", + List.of(), + "effectKeys", + List.of(), + "grantedAdmissionTags", + List.of("gameplay"))))) + .isInstanceOf(IllegalArgumentException.class); + } + + static GameplayRuleManifest exampleManifest() { + List definitions = + List.of( + new Stat( + "focus", + PrimitiveKind.NUMERIC, + BigDecimal.ONE, + null, + BigDecimal.ZERO, + BigDecimal.TEN, + Visibility.PUBLIC, + List.of()), + new Resource( + "energy", + BigDecimal.TEN, + BigDecimal.ZERO, + BigDecimal.TEN, + BigDecimal.valueOf(100), + Visibility.PUBLIC, + List.of()), + new Condition( + "weary", + Reapplication.REFRESH, + DurationPolicy.RESET, + 5L, + null, + Visibility.PUBLIC, + List.of(), + List.of(), + 0), + new Effect( + "restore", + Lifecycle.INSTANT, + EffectOperation.ADJUST_RESOURCE, + "energy", + null, + BigDecimal.ONE, + null, + null), + new Effect( + "cleanse", + Lifecycle.INSTANT, + EffectOperation.REMOVE_CONDITION, + null, + null, + null, + "weary", + null), + new Effect( + "capacity", + Lifecycle.CONTINUOUS, + EffectOperation.ADD, + "energy", + StatField.MAXIMUM, + BigDecimal.ONE, + null, + CapacityChangePolicy.CLAMP_ONLY), + new AdmissionTag("gameplay"), + new AdmissionTag("canFocus"), + new Feedback( + "unavailable", + "ACTION_REJECTED", + Audience.SOURCE_ACTOR, + "action.unavailable", + "Unavailable.", + List.of(), + Visibility.PRIVATE, + ReplayPolicy.EFFECT_IDEMPOTENT), + new Disposition("ready", List.of(), "unavailable"), + new ContinuousOverlay( + "wearyOverlay", + new Predicate( + PredicateKind.CONDITION_PRESENT, + ActorRole.SOURCE, + "weary", + null, + null, + List.of()), + List.of("canFocus"), + List.of("capacity")), + new ObservationPolicy("observable", truth()), + new TargetingPolicy( + "self", CandidateSelector.SELF, "observable", truth(), "unavailable"), + new SelectionPolicy( + "one", + Cardinality.EXACTLY_ONE, + null, + null, + SelectionStrategy.CANONICAL_ORDER, + null, + List.of()), + new DefaultBinding( + "focusDefault", List.of(new TargetSet("subject", "self", "one", true, null, null))), + new Action( + "focusAction", + "Focus", + List.of("gameplay", "canFocus"), + List.of(new TargetSet("subject", "self", "one", true, null, null)), + List.of(new Cost("energy", BigDecimal.ONE, CommitPolicy.ON_EXECUTION)), + List.of(new Cooldown("focusCooldown", 3L, CommitPolicy.ON_EFFECT_SUCCESS)), + List.of( + new EffectBinding("restore", "subject"), + new EffectBinding("cleanse", "SOURCE")), + List.of("unavailable")), + new Ability("focusAbility", "Focus ability", "focusAction"), + new Command( + "focusCommand", + "focusAction", + "GAME_LOGIC", + ExecutionDiscipline.DURABLE_GAMEPLAY, + Stage.GAMEPLAY, + PromptPolicy.WHEN_GAMEPLAY, + ActionCategory.GAMEPLAY, + true, + List.of("focus"), + List.of(ActionTag.COMBAT), + List.of("gameplay", "canFocus"))); + Map> families = new EnumMap<>(Family.class); + for (Family family : Family.values()) families.put(family, new ArrayList<>()); + for (Definition definition : definitions) families.get(definition.family()).add(definition); + return new GameplayRuleManifest(families); + } + + private static Predicate truth() { + return new Predicate(PredicateKind.TRUE, null, null, null, null, List.of()); + } + + private static DraftCommitBinding binding(List payloads) { + List revisions = new ArrayList<>(); + for (int i = 0; i < payloads.size(); i++) + revisions.add( + new RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads.get(i))); + return DraftCommitBinding.create( + TARGET, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + TARGET.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + } +} From 7f01bac64e158ff87047e0b80eb8d05184ddba91 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:18:57 +1300 Subject: [PATCH 23/61] Restore source-first activation settlement locking --- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 2 + ...SessionActivationProtectionRepository.java | 26 ++++ ...tionProtectionPostgresIntegrationTest.java | 138 ++++++++++++++++++ 4 files changed, 171 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index e920c29f63..27642fab27 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -116,3 +116,8 @@ Entry format: - Observation: verifying nonoverlapping blobs and paragraphs unique against the merge base missed receiver status that also appeared in the base. Main later compared the complete receiver document, restored every original receiver paragraph byte-for-byte, and retained the incoming concise status and relocated proof. No production source changed. - Expected pattern: inspect the complete overlap against the receiver's current contract and status, including text shared with the merge base. Proof relocation alone does not authorize replacing unrelated current-status sections with an earlier parent's view. - Reconsideration trigger: a native reconciliation check proves preservation across moved paragraphs and status replacements; ordinary clean merges and nonoverlap comparisons do not establish that property. + +- `2026-10-16`: Keep FireController briefs within the size limit + - Context: FireController job briefs are capped at 200,000 characters. + - Observation: Repeatedly prepending completed and running checkpoints caused a revision to be rejected before the active execution state could be saved. + - Expected pattern: Archive the full previous brief, retain standing instructions and superseding decisions, replace the active execution section, and put milestones in native updates/checkpoints. Consolidation restored guarded updates without losing source history or standing authority. 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 fc42eb4701..425bc70d0c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### Selected publication owner preparation +Activation settlement preserves the canonical source-first lock order: the repository locks exact original source keys in Java canonical order with NOWAIT before locking and rereading the immutable protection row. The focused PostgreSQL refusal fixture controls historical lookup and terminal evidence to exercise only source contention, lock ordering, rollback and absence of settlement effects; it does not prove authenticated terminal production or a complete Java settlement write/readback. + The disclosure source-lock adapter preserves complete keys through the canonical 2,048 UTF-8 byte bound already owned by shared source evidence and V76 storage. It no longer applies the obsolete 512-byte Java limit. The focused unit covers legacy and longer keys, ASCII and Unicode at the exact byte boundary, and rejection beyond it without truncation or aliasing; physical source-lock and disclosure behavior retain their separately attributed native proof. The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. R14 freshly passes eleven focused Account native cases and the real six-store Game Design/World terminal-to-Account settlement composition, including refusal before World completion, exact post-commit receipt replay and nine malformed closure/profile refusals. The latter uses both actual terminal owners and mTLS reads; the local inbound Account caller context remains explicitly controlled. Forward V1011 accepts only the canonical paired legacy and closure inventory profiles, preserving the existing frame, correlation, source and artifact guards. No installed migration is rewritten. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java index ff49f47dc6..439fd2c64e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java @@ -211,6 +211,16 @@ public StoredSettlement settleExact( accountEvidence.accountProtectionId(), accountEvidence.accountProtectionFence()) .orElseThrow(AccountStartSessionActivationProtectionRepository::unavailable); requireSameEvidence(protection.evidence(), accountEvidence); + lockOriginalSourceRows(protection.evidence()); + Record locked = + dsl.fetchOne( + "SELECT * FROM " + + PROTECTIONS + + " WHERE activation_protection_id = ? FOR UPDATE NOWAIT", + accountEvidence.accountProtectionId()); + if (locked == null) throw unavailable(); + protection = decodeProtection(locked, readSources(accountEvidence.accountProtectionId())); + requireSameEvidence(protection.evidence(), accountEvidence); dsl.execute( "INSERT INTO " @@ -240,6 +250,22 @@ public StoredSettlement settleExact( return stored; } + private void lockOriginalSourceRows(AccountStartSessionActivationProtectionEvidence evidence) { + for (SourceEvidence source : + evidence.sourceEvidenceVector().stream() + .sorted(java.util.Comparator.comparing(SourceEvidence::key)) + .toList()) { + Record locked = + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks " + + "WHERE source_key = ? FOR UPDATE NOWAIT", + source.key()); + if (locked == null || !source.key().equals(text(locked, "source_key"))) { + throw unavailable(); + } + } + } + private Record selectProtectionByRequestId(String requestId) { return dsl.fetchOne( "SELECT * FROM " + PROTECTIONS + " WHERE control_plane_request_id = ?", requestId); 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 index ec6a37938d..b73c907fc6 100644 --- 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 @@ -2,6 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -17,17 +21,23 @@ import java.util.Locale; import java.util.Map; import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository.StoredProtection; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; 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.common.world.WorldOriginalStartSessionActivationTerminalEvidence; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; +import org.jooq.ExecuteListener; import org.jooq.Field; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -54,6 +64,134 @@ class AccountStartSessionActivationProtectionPostgresIntegrationTest { private static final JsonMapper JSON = JsonMapper.builder().build(); + @Test + void settlementLocksCanonicalSourceKeysBeforeProtectionRowAccess() throws Exception { + Fixture fixture = fixture(); + var first = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + "activation-\uD800\uDC00", + null, + "1", + null, + null, + bytes("first")); + var last = + new SourceEvidence( + SourceKind.HOSTED_TERMS, "activation-\uE000", null, "1", null, null, bytes("last")); + for (var source : List.of(first, last)) { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + source.key()); + } + UUID protectionId = UUID.randomUUID(); + var evidence = mock(AccountStartSessionActivationProtectionEvidence.class); + when(evidence.accountProtectionId()).thenReturn(protectionId); + when(evidence.accountProtectionFence()).thenReturn(7L); + when(evidence.canonicalBytes()).thenReturn(bytes("controlled protection lookup")); + when(evidence.sourceEvidenceVector()).thenReturn(List.of(last, first)); + var terminal = mock(WorldOriginalStartSessionActivationTerminalEvidence.class); + when(terminal.accountProtectionEvidence()).thenReturn(evidence); + var repository = spy(new AccountStartSessionActivationProtectionRepository(fixture.dsl())); + // Only the lock boundary is physical here; historical lookup and terminal authority are + // controlled. + doReturn(java.util.Optional.of(new StoredProtection(evidence, 1L))) + .when(repository) + .findHistoricalExact(protectionId, 7L); + var sourceLocks = new java.util.ArrayList(); + var protectionLocks = new java.util.ArrayList(); + fixture + .dsl() + .configuration() + .setAppending( + new DefaultExecuteListenerProvider( + ExecuteListener.onExecuteStart( + context -> { + String sql = context.sql(); + var query = context.query(); + if (sql == null || query == null || !sql.contains("FOR UPDATE NOWAIT")) + return; + if (sql.contains("account_draft_authorization_source_locks")) { + sourceLocks.add((String) query.getBindValues().getFirst()); + } else if (sql.contains("account_start_session_activation_protections")) { + protectionLocks.add(query.getBindValues().getFirst()); + } + }))); + for (var contended : List.of(first, last)) { + sourceLocks.clear(); + protectionLocks.clear(); + try (var holder = fixture.dataSource().getConnection()) { + holder.setAutoCommit(false); + try (var statement = + holder.prepareStatement( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE")) { + statement.setString(1, contended.key()); + try (var rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + } + } + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult(ignored -> repository.settleExact(terminal))) + .hasRootCauseInstanceOf(org.postgresql.util.PSQLException.class) + .satisfies( + failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(((org.postgresql.util.PSQLException) root).getSQLState()) + .isEqualTo("55P03"); + }); + assertThat(protectionLocks).isEmpty(); + assertThat(sourceLocks) + .containsExactlyElementsOf( + contended == first ? List.of(first.key()) : List.of(first.key(), last.key())); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + holder.rollback(); + } + } + sourceLocks.clear(); + protectionLocks.clear(); + // Once both sources are available, row lookup follows them; no parent is manufactured by this + // test. + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult(ignored -> repository.settleExact(terminal))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact original StartSession activation protection unavailable"); + assertThat(sourceLocks).containsExactly(first.key(), last.key()); + assertThat(protectionLocks).containsExactly(protectionId); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + try (var verifier = fixture.dataSource().getConnection()) { + verifier.setAutoCommit(false); + try (var statement = + verifier.prepareStatement( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE NOWAIT")) { + for (var source : List.of(first, last)) { + statement.setString(1, source.key()); + try (var rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + } + } + } + verifier.rollback(); + } + } + @Test void digestAlignmentUpgradePreservesRetainedParentAndRequiresCanonicalWorldPrefix() throws Exception { From 1c4139f75204d8a8dce54f4b0bf4579bb860446a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:16:38 +1300 Subject: [PATCH 24/61] Qualify owner tuple retention and wide fences on published parent --- .../player-access-and-session.md | 6 + ...ratorAttemptRepositoryIntegrationTest.java | 123 ++++++++++++++++++ ...ationOwnerCompositionCrossServiceTest.java | 28 +++- 3 files changed, 150 insertions(+), 7 deletions(-) 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 425bc70d0c..67596e0e14 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Retained StartSession owner tuples + +The focused Game Session owner fixture retains original unsafe numeric v1 fence carriers through current-execution rejection, including exactly representable values above the safe JSON integer range. It checks the original stored bytes and row version after decoder refusal, conflicting current-spelling replay, Account-projection attachment, evidence continuation and current-attempt reads; the original attempt remains the only row and runtime/admission pointers stay absent. This is controlled PostgreSQL integrity proof, without issuer or deployment provenance. The focused case passes once with two unsafe numeric vectors at source `c6bf1b202b55d0b2616a26d72e4af50c543793fb`; affected integration static analysis, formatting and documentation checks pass. The strict passive observer owns its single PostgreSQL container, with an inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container after completion. Account source-protection and six-store publication cases retain their separate proof boundaries. + +The existing [World original-owner composition](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java) now passes its positive operation at fence values 9,007,199,254,740,992, 9,007,199,254,740,993 and 9,223,372,036,854,775,807. Actual Account issuance/redemption, native Game Session storage and the authenticated Account-to-Game Session current-attempt mTLS read preserve each exact fence, original tuple and redemption projection; the authenticated read leaves the complete stored row and row version unchanged. All three fresh parameterized cases pass with zero failures, errors or skips at source `f1ba70374fab5c7d7a4b733c0bea2bd842a2cd7b`, together with affected cross-service static analysis, formatting and documentation checks. The strict passive observer owns all three run-created PostgreSQL containers, with an inherited resource-session descriptor, no ownership gaps or observer errors, and all three absent after completion. This closes the two focused owner-tuple proof gaps within these controlled fixtures. Creator, Logging claims, publication/launch evidence and PKI remain controlled; the existing World preparation/activation and Account settlement composition uses unregistered owners and a test-local World transport wrapper. It does not establish genuine issuer/environment authority, deployed composition, gameplay admission, Entity placement or completion of any genuine handoff. + ### Selected publication owner preparation Activation settlement preserves the canonical source-first lock order: the repository locks exact original source keys in Java canonical order with NOWAIT before locking and rereading the immutable protection row. The focused PostgreSQL refusal fixture controls historical lookup and terminal evidence to exercise only source contention, lock ordering, rollback and absence of settlement effects; it does not prove authenticated terminal production or a complete Java settlement write/readback. diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java index 9695e472f7..cc18765806 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.time.Duration; import java.time.Instant; @@ -678,6 +679,128 @@ void oneConcurrentClaimWinsAndExactReplayReturnsOnlyTheOriginalSnapshot() throws } } + @Test + void unsafeLegacyNumericTuplesDenyExecutionWithoutChangingStoredRows() throws Exception { + for (long fence : new long[] {9_007_199_254_740_992L, 9_007_199_254_740_994L}) { + Fixture fixture = fixture(Duration.ofMinutes(5)); + // These numeric values were exactly representable in historical JSON, but are unsafe v1 + // fences. + StartSessionPostAuthorizationExecutionTuple current = + tuple( + "operator-attempt-unsafe-legacy-" + fence, + "unsafe retained tuple denial", + RESERVATION_OWNER, + fence); + String canonical = new String(current.canonicalBytes(), StandardCharsets.UTF_8); + String currentFence = "\"reservationClaimFence\":\"" + fence + "\""; + assertThat(canonical).contains(currentFence); + assertThat(canonical.indexOf(currentFence)).isEqualTo(canonical.lastIndexOf(currentFence)); + byte[] original = + canonical + .replace(currentFence, "\"reservationClaimFence\":" + fence) + .getBytes(StandardCharsets.UTF_8); + assertThat( + Rfc8785CanonicalJson.canonicalizeUtf8(new String(original, StandardCharsets.UTF_8))) + .containsExactly(original); + + UUID attemptId = UUID.randomUUID(); + UUID mutationId = UUID.randomUUID(); + UUID claimOwner = UUID.randomUUID(); + long ownerFence = + Objects.requireNonNull( + fixture + .dsl + .fetchSingle( + "SELECT nextval('game_session_start_session_operator_owner_fence_seq')") + .get(0, Long.class)); + // Seed the original opaque carrier through the existing storage guards, without changing SQL, + // disabling immutability, or inferring a replacement value from historical bytes. + fixture.dsl.execute( + "INSERT INTO game_session_start_session_operator_attempt " + + "(target_namespace, control_plane_request_id, canonical_tenant_id, owner_attempt_id, " + + "owner_mutation_id, claim_owner_id, owner_fence, post_authorization_execution_tuple, " + + "mutation_digest, authorization_reference_fingerprint, lease_expires_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, clock_timestamp() + interval '5 minutes')", + NAMESPACE, + current.controlPlaneRequestId(), + TENANT, + attemptId, + mutationId, + claimOwner, + ownerFence, + original, + current.mutationDigest(), + current.authorizationReferenceFingerprint()); + var claim = + new AttemptClaim( + NAMESPACE, + current.controlPlaneRequestId(), + attemptId, + mutationId, + claimOwner, + ownerFence); + java.util.function.Supplier retained = + () -> + fixture + .dsl + .fetchSingle( + "SELECT to_jsonb(attempt)::text || ':' || attempt.xmin::text " + + "FROM game_session_start_session_operator_attempt attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + current.controlPlaneRequestId()) + .get(0, String.class); + String before = Objects.requireNonNull(retained.get()); + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT post_authorization_execution_tuple FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + current.controlPlaneRequestId()) + .get(0, byte[].class)) + .containsExactly(original); + assertThatThrownBy(() -> StartSessionPostAuthorizationExecutionTuple.decode(original)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "reservationClaimFence numeric value exceeds the safe JSON integer range"); + assertThat(retained.get()).isEqualTo(before); + + // An independently constructed current spelling cannot adopt or rewrite the original row. + assertThatThrownBy(() -> fixture.reserve(current)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class) + .hasMessageContaining("different complete post-authorization tuple"); + assertThat(retained.get()).isEqualTo(before); + assertThatThrownBy(() -> fixture.attach(claim, projection(current))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "reservationClaimFence numeric value exceeds the safe JSON integer range"); + assertThat(retained.get()).isEqualTo(before); + assertThatThrownBy(() -> fixture.continueEvidence(current)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class) + .hasMessageContaining( + "Evidence continuation tuple differs from the original complete StartSession attempt"); + assertThat(retained.get()).isEqualTo(before); + assertThatThrownBy( + () -> fixture.currentOriginalAttempt(currentAttemptRequest(current, claim))) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class) + .hasMessageContaining( + "Current original-attempt read differs from the complete StartSession tuple"); + assertThat(retained.get()).isEqualTo(before); + assertThat(fixture.attemptCount()).isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isZero(); + } + } + @Test void exactLargeReservationFencesSurviveOwnerReservationAndProjectionReplay() { for (long fence : diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index 8b87d3b498..6375ab804f 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -149,6 +149,8 @@ import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -231,9 +233,11 @@ class WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest { @TempDir Path temporary; - @Test - void actualOwnersPrepareAndReplayOneExactOriginalOperation() throws Exception { - compose(Refusal.NONE); + @ParameterizedTest + @ValueSource(longs = {9_007_199_254_740_992L, 9_007_199_254_740_993L, Long.MAX_VALUE}) + void actualOwnersPrepareAndReplayOneExactOriginalOperation( + long reservationClaimFence, @TempDir Path proofDirectory) throws Exception { + compose(Refusal.NONE, reservationClaimFence, proofDirectory); } @Test @@ -259,6 +263,11 @@ private enum Refusal { } private void compose(Refusal refusal) throws Exception { + compose(refusal, 9_007_199_254_740_993L, temporary); + } + + private void compose(Refusal refusal, long reservationClaimFence, Path proofDirectory) + throws Exception { UUID tenant = UUID.randomUUID(); try (var account = new AccountControlUiOriginalOrderFixture( @@ -267,13 +276,13 @@ private void compose(Refusal refusal) throws Exception { ACCOUNT.getPassword(), REDIS.getHost(), REDIS.getMappedPort(6379), - temporary.resolve("account"), + proofDirectory.resolve("account"), tenant); var world = database(WORLD, "world-management-service", true); var gs = database(GS, "game-session-service", false)) { var issuer = new AccountOriginalStartSessionAuthorizationProofFixture( - account, temporary.resolve("issuer"), NAMESPACE); + account, proofDirectory.resolve("issuer"), NAMESPACE); Duration lease = refusal == Refusal.EXPIRED_ATTEMPT ? Duration.ofSeconds(30) : Duration.ofMinutes(5); var attempts = new GameSessionStartSessionOperatorAttemptRepository(gs.dsl(), lease); @@ -289,7 +298,6 @@ private void compose(Refusal refusal) throws Exception { new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), "TEST_ONLY owner composition"); String requestId = "controlled-original-prepare-" + UUID.randomUUID(); - long reservationClaimFence = 9_007_199_254_740_993L; var original = issuer.issueAndRedeemOriginal( requestId, @@ -369,7 +377,7 @@ public void attachAccountRedemptionProjection( claim.get().ownerMutationId(), input.gameSessionOwnerAttemptId(), claim.get().ownerFence()); - var pki = new WorldOriginalStartSessionPreparationProofPki(temporary.resolve("pki")); + var pki = new WorldOriginalStartSessionPreparationProofPki(proofDirectory.resolve("pki")); var factory = new GrpcChannelFactory(); Server gsServer = server( @@ -394,6 +402,8 @@ public void attachAccountRedemptionProjection( currentAttempt.init(); launchAssociation.init(); if (refusal == Refusal.NONE) { + var beforeAuthenticatedRead = + rows(gs.dsl(), "game_session_start_session_operator_attempt"); var authenticatedCurrent = currentAttempt.read( new net.firedevops.firemud.common.gamesession @@ -406,8 +416,12 @@ public void attachAccountRedemptionProjection( claim.get().ownerFence())); assertThat(authenticatedCurrent.request().originalTuple().reservationClaimFence()) .isEqualTo(reservationClaimFence); + assertThat(authenticatedCurrent.request().canonicalPostAuthorizationTuple()) + .containsExactly(tuple.canonicalBytes()); assertThat(authenticatedCurrent.accountRedemptionProjection()) .containsExactly(tuple.canonicalBytes()); + assertThat(rows(gs.dsl(), "game_session_start_session_operator_attempt")) + .isEqualTo(beforeAuthenticatedRead); } int accountPort = availablePort(); From 710ebb0f6fb9731f6d2088cf075fe346c13f150e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:55:34 +1300 Subject: [PATCH 25/61] Secure original Logging claim reads and qualify bounded PKI fixture --- design/project-management/ai-observations.md | 9 + .../player-access-and-session.md | 6 + ...StartSessionReservationEvidenceClient.java | 76 +++- ...iPositiveOwnerPostgresIntegrationTest.java | 130 +++---- ...tSessionReservationEvidenceClientTest.java | 310 +++++++++++----- ...ntStartSessionReservationProofPkiTest.java | 85 +++++ ...ccountStartSessionReservationProofPki.java | 346 ++++++++++++++++++ 7 files changed, 775 insertions(+), 187 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 27642fab27..f9519df4cb 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -121,3 +121,12 @@ Entry format: - Context: FireController job briefs are capped at 200,000 characters. - Observation: Repeatedly prepending completed and running checkpoints caused a revision to be rejected before the active execution state could be saved. - Expected pattern: Archive the full previous brief, retain standing instructions and superseding decisions, replace the active execution section, and put milestones in native updates/checkpoints. Consolidation restored guarded updates without losing source history or standing authority. + +- `2026-10-16`: Keep the original Logging claim-read client workload-only + - Context: A generic gRPC channel and stub customizer did not establish the original Logging claim-read client's workload-only boundary: the common customizer attaches bearer metadata, and a trusted TLS channel alone does not pin the expected SPIFFE workload. + - Observation: The corrected client uses the existing Common peer credentials and response verifier, preserves default-off composition, and rejects ambient SQL, synchronization and caller context before RPC. Controlled loopback mTLS and the existing native owner consumer now prove this bounded behavior; they do not establish genuine upstream authority. + - Expected pattern: Keep the configured server identity separate from mutation target data, and follow canonical usable TLS-material policy rather than copying a donor's regular-file predicate. +- `2026-10-16`: Bound subprocess output and waits in the original claim-read test PKI fixture + - Context: Reading subprocess output to EOF before a timed wait leaves the supposed deadline unbounded. + - Observation: The original claim-read test PKI helper now redirects output to an owned temporary file, waits before reading it, and terminates/reaps a timed-out or interrupted child with interrupt preservation. Actual stalled-keytool timeout and interruption cases pass alongside the affected TLS and native owner proofs. + - Expected pattern: Keep this correction in the purpose-specific fixture; it does not require a general command framework or change production TLS material policy. 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 67596e0e14..b9b7be005f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,12 @@ The focused Game Session owner fixture retains original unsafe numeric v1 fence The existing [World original-owner composition](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java) now passes its positive operation at fence values 9,007,199,254,740,992, 9,007,199,254,740,993 and 9,223,372,036,854,775,807. Actual Account issuance/redemption, native Game Session storage and the authenticated Account-to-Game Session current-attempt mTLS read preserve each exact fence, original tuple and redemption projection; the authenticated read leaves the complete stored row and row version unchanged. All three fresh parameterized cases pass with zero failures, errors or skips at source `f1ba70374fab5c7d7a4b733c0bea2bd842a2cd7b`, together with affected cross-service static analysis, formatting and documentation checks. The strict passive observer owns all three run-created PostgreSQL containers, with an inherited resource-session descriptor, no ownership gaps or observer errors, and all three absent after completion. This closes the two focused owner-tuple proof gaps within these controlled fixtures. Creator, Logging claims, publication/launch evidence and PKI remain controlled; the existing World preparation/activation and Account settlement composition uses unregistered owners and a test-local World transport wrapper. It does not establish genuine issuer/environment authority, deployed composition, gameplay admission, Entity placement or completion of any genuine handoff. +### Original Logging claim-read client + +The existing Account StartSession reservation-evidence client pins the configured Logging & Admin workload URI with the shared pre-request credentials and response verifier. It uses workload-only mTLS without the generic bearer-token stub customizer, rejects caller context and ambient SQL transactions or synchronization before RPC, and preserves the original tuple, purpose, deadline and exact response binding checks. The server identity comes from the existing configured workload namespace, independently of the mutation target namespace. Usable configured certificate, key and CA resources are required without adding a universal regular-file storage restriction; the existing default-off registration stays unchanged. + +The focused source `3357125badc6ad36f6d2e77ea1105685960e86c4` passes ten secured-client cases, two fixture child-process cases, the default-off bean-definition case and the existing Account original-owner PostgreSQL case: fourteen fresh cases with zero failures, errors or skips. Actual loopback mTLS rejects wrong workload, wrong namespace or missing server URI before request delivery; plaintext, missing client credentials, caller context and ambient SQL/synchronization are denied separately. The native owner case uses the actual Logging socket and certificate-derived approved Account leaf; remaining inbound Account and upstream authority contexts stay controlled. Its strict passive observer owns the single run-created PostgreSQL container with the inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container after completion. Affected main, unit, integration and test-fixture static analysis, formatting and documentation checks pass. The test PKI helper now waits within its deadline before reading child output, then terminates and reaps on timeout or interruption while preserving interrupt status; the two new cases prove those paths with actual stalled JDK children. Earlier client/owner passes did not establish this child-process deadline. These controlled component results do not establish genuine creator, issuer, environment or PKI authority, deployed registration, gameplay admission, Entity placement or any genuine handoff. + ### Selected publication owner preparation Activation settlement preserves the canonical source-first lock order: the repository locks exact original source keys in Java canonical order with NOWAIT before locking and rereading the immutable protection row. The focused PostgreSQL refusal fixture controls historical lookup and terminal evidence to exercise only source contention, lock ordering, rollback and absence of settlement effects; it does not prove authenticated terminal production or a complete Java settlement write/readback. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java index ff072c2bf7..08fc966d17 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java @@ -12,17 +12,23 @@ import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.grpc.GrpcTlsMaterialResolver; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Reads and validates Logging/Admin's current StartSession reservation claim snapshot. @@ -43,30 +49,30 @@ public final class StartSessionReservationEvidenceClient private static final long CALL_DEADLINE_SECONDS = 5L; private static final UUID NIL_UUID = new UUID(0L, 0L); + private final String expectedLoggingPeerUri; private final Clock clock; + private final CommonGrpcClientProperties transportTlsProperties; @Autowired public StartSessionReservationEvidenceClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, - BlockingGrpcStubCustomizer stubCustomizer) { - this(endpoints, tlsProperties, channelFactory, stubCustomizer, Clock.systemUTC()); + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this(endpoints, tlsProperties, channelFactory, workloadNamespace, Clock.systemUTC()); } StartSessionReservationEvidenceClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, - BlockingGrpcStubCustomizer stubCustomizer, + String workloadNamespace, Clock clock) { - super( - endpoints, - tlsProperties, - channelFactory, - stubCustomizer, - StartSessionReservationEvidenceClient.class); + super(endpoints, tlsProperties, channelFactory, StartSessionReservationEvidenceClient.class); + this.expectedLoggingPeerUri = loggingAdminServerUri(workloadNamespace); this.clock = Objects.requireNonNull(clock, "clock is required"); + this.transportTlsProperties = + Objects.requireNonNull(tlsProperties, "TLS properties are required").copy(); } @PostConstruct @@ -88,9 +94,10 @@ protected String defaultTarget() { protected StartSessionReservationEvidenceServiceGrpc .StartSessionReservationEvidenceServiceBlockingStub buildStub(io.grpc.ManagedChannel channel) { - return applyStubCustomizer( - StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) - .withCompression("gzip")); + return StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedLoggingPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedLoggingPeerUri)) + .withCompression("gzip"); } /** Reads the exact active claim for ISSUE or RECOVER and validates every returned binding. */ @@ -101,6 +108,7 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( UUID currentClaimOwnerId, long currentClaimFence, Purpose purpose) { + requireWorkloadOnlyContext(); Objects.requireNonNull(tuple, "reservation tuple is required"); requireNonNilUuid(reservationOwnerId, "reservationOwnerId"); requireNonNilUuid(currentClaimOwnerId, "currentClaimOwnerId"); @@ -123,6 +131,7 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( .setPurpose(toWirePurpose(purpose)) .build(); + requireWorkloadMtls(); var currentStub = stub(); if (currentStub == null) { throw new IllegalStateException("Logging/Admin reservation evidence client is unavailable"); @@ -143,6 +152,47 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( return response; } + static String loggingAdminServerUri(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("StartSession target namespace is invalid"); + } + return "spiffe://firemud/ns/" + targetNamespace + "/sa/logging-admin-service"; + } + + private void requireWorkloadMtls() { + if (transportTlsProperties.isPlaintext()) { + throw new IllegalStateException("Logging/Admin reservation evidence requires workload mTLS"); + } + try { + var material = new GrpcTlsMaterialResolver().resolve(transportTlsProperties); + if (material == null) { + throw new IllegalStateException("Missing workload TLS material"); + } + try (var certificate = material.certChain().openStream(); + var privateKey = material.privateKey().openStream(); + var ca = material.caCert().openStream()) { + if (certificate.read() < 0 || privateKey.read() < 0 || ca.read() < 0) { + throw new IllegalStateException("Empty workload TLS material"); + } + } + } catch (IOException | RuntimeException unavailable) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires usable workload mTLS", unavailable); + } + } + + private static void requireWorkloadOnlyContext() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires no ambient SQL or synchronization"); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires a workload-only caller context"); + } + } + private void validateResponse( ReadCurrentClaimEvidenceResponse response, StartSessionPreAuthorizationReservationTuple tuple, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java index 56dca09c66..d6d8eea0b4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -2,8 +2,6 @@ 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.when; import com.google.protobuf.ByteString; import io.grpc.Context; @@ -19,15 +17,18 @@ import io.grpc.StatusRuntimeException; import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.codec.ByteArrayCodec; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; @@ -49,14 +50,15 @@ import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; @@ -150,7 +152,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest { @TempDir Path temporary; - private InProcessLoggingTransport loggingTransport; + private MtlsLoggingTransport loggingTransport; @AfterEach void clearLoggingTransport() throws Exception { @@ -414,21 +416,25 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() var reservationFixture = StartSessionReservationMutationTestFixtures.forRunOwnedPostgres(postgres, loggingSchema); var reservationService = reservationFixture.service(); - var approvedAccountLeaf = testAccountLeafEvidence(); + var loggingPki = + AccountStartSessionReservationProofPki.create( + temporary.resolve("logging-claim-pki"), "control-ui-owner-proof"); + String approvedAccountLeaf = + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(loggingPki.accountIdentity().certificate().getEncoded())); Path approvedLeafFile = temporary.resolve("account-reservation-evidence-approved-test-leaf.txt"); Files.writeString( - approvedLeafFile, - "active=" + approvedAccountLeaf.leafSha256() + "\n", - StandardCharsets.US_ASCII); + approvedLeafFile, "active=" + approvedAccountLeaf + "\n", StandardCharsets.US_ASCII); loggingTransport = - inProcessLoggingTransport( + mtlsLoggingTransport( new StartSessionReservationEvidenceGrpcService( reservationService, new StartSessionReservationEvidenceLeafApproval(approvedLeafFile.toString()), "control-ui-owner-proof"), - "spiffe://firemud/ns/control-ui-owner-proof/sa/account-service", - approvedAccountLeaf); + loggingPki); var acquisition = reservationService.acquire(loggingTuple); assertThat(acquisition.newlyAcquired()).isTrue(); @@ -862,69 +868,43 @@ private static Path loggingMigrations() { } /** - * Test-only in-process composition supplies the Account URI and a run-owned approved leaf; it - * exercises receiver authorization, not a TLS handshake or mTLS certificate binding. + * Controlled Logging socket uses certificate-derived Account identity and actual approved leaf. */ - private static InProcessLoggingTransport inProcessLoggingTransport( + private static MtlsLoggingTransport mtlsLoggingTransport( StartSessionReservationEvidenceGrpcService receiver, - String accountPeerUri, - GrpcPeerCertificateEvidence accountLeafEvidence) + AccountStartSessionReservationProofPki pki) throws Exception { - String serverName = InProcessServerBuilder.generateName(); - var peer = GrpcPeerIdentity.parseUri(accountPeerUri).orElseThrow(); + var identity = pki.server("logging"); Server server = - InProcessServerBuilder.forName(serverName) - .directExecutor() - .addService( - ServerInterceptors.intercept( - receiver, - new ServerInterceptor() { - @Override - public ServerCall.Listener interceptCall( - ServerCall call, - Metadata headers, - ServerCallHandler next) { - Context peerContext = - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .withValue( - GrpcPeerCertificateEvidence.CONTEXT_KEY, accountLeafEvidence); - return Contexts.interceptCall(peerContext, call, headers, next); - } - })) + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) .build() .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService("localhost:" + server.getPort()); + var tls = pki.clientProperties(); + var factory = new GrpcChannelFactory(); ManagedChannel receiverChannel = - InProcessChannelBuilder.forName(serverName).directExecutor().build(); - ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); - endpoints.setLoggingAdminService(serverName); - CommonGrpcClientProperties testTransport = new CommonGrpcClientProperties(); - testTransport.setPlaintext(true); - GrpcChannelFactory channelFactory = - new GrpcChannelFactory() { - @Override - public ManagedChannel buildChannel( - String target, - int defaultPort, - CommonGrpcClientProperties properties, - boolean keepAlive) { - if (!serverName.equals(target) || !properties.isPlaintext()) { - throw new IllegalArgumentException( - "Only the named in-process test transport is valid"); - } - return InProcessChannelBuilder.forName(serverName).directExecutor().build(); - } - }; - StartSessionReservationEvidenceClient accountClient = + factory.buildChannel(endpoints.getLoggingAdminService(), 6565, tls, true); + var accountClient = new StartSessionReservationEvidenceClient( - endpoints, testTransport, channelFactory, BlockingGrpcStubCustomizer.noop()); + endpoints, tls, factory, "control-ui-owner-proof"); try { ReflectionTestUtils.invokeMethod(accountClient, "init"); - return new InProcessLoggingTransport( + String loggingUri = "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; + return new MtlsLoggingTransport( server, receiverChannel, accountClient, - StartSessionReservationEvidenceServiceGrpc.newBlockingStub(receiverChannel)); + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(receiverChannel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(loggingUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(loggingUri))); } catch (RuntimeException | Error failure) { accountClient.close(); receiverChannel.shutdownNow(); @@ -933,18 +913,6 @@ public ManagedChannel buildChannel( } } - private static GrpcPeerCertificateEvidence testAccountLeafEvidence() { - X509Certificate leaf = mock(X509Certificate.class); - try { - when(leaf.getEncoded()) - .thenReturn( - "run-owned Account test leaf certificate".getBytes(StandardCharsets.US_ASCII)); - } catch (CertificateEncodingException exception) { - throw new AssertionError(exception); - } - return GrpcPeerCertificateEvidence.fromCertificate(leaf).orElseThrow(); - } - private static InProcessAccountTransport inProcessAccountTransport( StartSessionOperatorAuthorizationGrpcService receiver, String namespace) throws Exception { return new InProcessAccountTransport( @@ -1060,10 +1028,10 @@ public void close() { } /** - * Test-only in-process composition. Its injected peer context exercises receiver authorization; - * it is deliberately not a TLS or mTLS proof. + * Controlled Logging socket composition with actual workload certificates and leaf approval. + * Account's separate inbound owner transport remains explicitly controlled. */ - private static final class InProcessLoggingTransport implements AutoCloseable { + private static final class MtlsLoggingTransport implements AutoCloseable { private final Server server; private final ManagedChannel receiverChannel; private final StartSessionReservationEvidenceClient accountClient; @@ -1071,7 +1039,7 @@ private static final class InProcessLoggingTransport implements AutoCloseable { .StartSessionReservationEvidenceServiceBlockingStub receiverStub; - private InProcessLoggingTransport( + private MtlsLoggingTransport( Server server, ManagedChannel receiverChannel, StartSessionReservationEvidenceClient accountClient, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java index b674202308..e9f6ee1030 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java @@ -10,14 +10,17 @@ import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; -import io.grpc.ManagedChannel; import io.grpc.Server; +import io.grpc.ServerInterceptors; import io.grpc.Status; import io.grpc.StatusRuntimeException; -import io.grpc.inprocess.InProcessChannelBuilder; -import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.stub.StreamObserver; import java.io.InputStream; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -26,23 +29,29 @@ import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; class StartSessionReservationEvidenceClientTest { private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; @@ -59,18 +68,34 @@ class StartSessionReservationEvidenceClientTest { Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC); private static final String LOGGING_ADMIN_TARGET = "logging-admin.internal:6565"; + @TempDir static Path pkiDirectory; + private static AccountStartSessionReservationProofPki pki; + private static CommonGrpcClientProperties accountTls; + + @BeforeAll + static void createControlledPki() throws Exception { + pki = AccountStartSessionReservationProofPki.create(pkiDirectory, "world-runtime"); + accountTls = pki.clientProperties(); + } + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + @Test - void repeatedInProcessReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exception { + void repeatedMtlsReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); List requests = new ArrayList<>(); - try (InProcessFixture fixture = - inProcessFixture( + try (MtlsFixture fixture = + mtlsFixture( request -> { requests.add(request); assertThat(io.grpc.Context.current().getDeadline()).isNotNull(); return validResponse(request, tuple.mutationDigest()); })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + StartSessionReservationEvidenceClient client = fixture.client(); ReadCurrentClaimEvidenceResponse issueFirst = client.readCurrentClaimEvidence( @@ -137,8 +162,8 @@ void repeatedInProcessReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exc void rejectsEveryResponseIdentityFieldUnknownFieldsAndStaleTimes() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicReference response = new AtomicReference<>(); - try (InProcessFixture fixture = inProcessFixture(request -> response.get())) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + try (MtlsFixture fixture = mtlsFixture(request -> response.get())) { + StartSessionReservationEvidenceClient client = fixture.client(); ReadCurrentClaimEvidenceResponse valid = validResponse( request(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE), @@ -193,8 +218,8 @@ void acceptsProducerObservationAfterLocalNowWhenClaimRemainsOrderedAndUnexpired( throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicReference response = new AtomicReference<>(); - try (InProcessFixture fixture = inProcessFixture(request -> response.get())) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + try (MtlsFixture fixture = mtlsFixture(request -> response.get())) { + StartSessionReservationEvidenceClient client = fixture.client(); ReadCurrentClaimEvidenceResponse futureObservation = validResponse( request(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE), @@ -221,13 +246,13 @@ void acceptsProducerObservationAfterLocalNowWhenClaimRemainsOrderedAndUnexpired( void invalidInputIsRejectedBeforeAnyRpc() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicInteger calls = new AtomicInteger(); - try (InProcessFixture fixture = - inProcessFixture( + try (MtlsFixture fixture = + mtlsFixture( request -> { calls.incrementAndGet(); return validResponse(request, tuple.mutationDigest()); })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + StartSessionReservationEvidenceClient client = fixture.client(); assertThatThrownBy( () -> @@ -278,12 +303,12 @@ void propagatesUnavailableAndStaleOwnerStatusesWithoutInterpretingThemAsEvidence throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicReference status = new AtomicReference<>(Status.UNAVAILABLE); - try (InProcessFixture fixture = - inProcessFixture( + try (MtlsFixture fixture = + mtlsFixture( request -> { throw status.get().asRuntimeException(); })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + StartSessionReservationEvidenceClient client = fixture.client(); assertThatThrownBy( () -> @@ -315,24 +340,14 @@ void propagatesUnavailableAndStaleOwnerStatusesWithoutInterpretingThemAsEvidence } @Test - void usesConfiguredLoggingEndpointTlsChannelAndStubCustomizer(@TempDir Path directory) - throws Exception { + void usesConfiguredLoggingEndpointAndTlsChannel(@TempDir Path directory) throws Exception { ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); endpoints.setLoggingAdminService(LOGGING_ADMIN_TARGET); CommonGrpcClientProperties tls = tlsProperties(directory); GrpcChannelFactory channelFactory = spy(new GrpcChannelFactory()); - AtomicInteger customizerCalls = new AtomicInteger(); - BlockingGrpcStubCustomizer customizer = - new BlockingGrpcStubCustomizer() { - @Override - public > T customize(T stub) { - customizerCalls.incrementAndGet(); - return stub; - } - }; StartSessionReservationEvidenceClient client = new StartSessionReservationEvidenceClient( - endpoints, tls, channelFactory, customizer, CLOCK); + endpoints, tls, channelFactory, "world-runtime", CLOCK); try { client.init(); @@ -340,59 +355,182 @@ public > T customize(T stub) { verify(channelFactory) .buildChannel( eq(LOGGING_ADMIN_TARGET), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); - assertThat(customizerCalls).hasValue(1); } finally { client.close(); } } - private static StartSessionReservationEvidenceClient client( - StartSessionReservationEvidenceServiceGrpc.StartSessionReservationEvidenceServiceBlockingStub - stub) - throws Exception { - StartSessionReservationClientTestAccess client = newClient(); - client.installStub(stub); - return client.client(); + @Test + void pinsConfiguredLoggingServerIndependentlyOfMutationTargetNamespace() throws Exception { + var targetTuple = tuple("other-target-runtime"); + try (var fixture = + mtlsFixture(request -> validResponse(request, targetTuple.mutationDigest()))) { + var evidence = + fixture + .client() + .readCurrentClaimEvidence( + targetTuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE); + assertThat(evidence.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(targetTuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + } } - private static StartSessionReservationClientTestAccess newClient() { - ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); - CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); - tls.setPlaintext(true); - StartSessionReservationEvidenceClient client = - new StartSessionReservationEvidenceClient( - endpoints, - tls, - mock(GrpcChannelFactory.class), - BlockingGrpcStubCustomizer.noop(), - CLOCK); - return new StartSessionReservationClientTestAccess(client); + @Test + void rejectsWrongAndMissingAuthenticatedServerIdentityBeforeRequestDelivery() throws Exception { + var calls = new AtomicInteger(); + for (String identity : List.of("wrong-workload", "wrong-namespace", "missing-identity")) { + try (var fixture = + mtlsFixture( + identity, + request -> { + calls.incrementAndGet(); + return validResponse(request, tuple().mutationDigest()); + })) { + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)) + .hasMessageContaining("exact authenticated server workload identity"); + } + } + assertThat(calls).hasValue(0); + } + + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeAnyRpc() throws Exception { + var calls = new AtomicInteger(); + try (var fixture = + mtlsFixture( + request -> { + calls.incrementAndGet(); + return validResponse(request, tuple().mutationDigest()); + })) { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + SessionContext.setContext("caller", List.of(), Map.of()); + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only caller"); + SessionContext.clear(); + assertThat(calls).hasValue(0); + assertThat(readIssue(fixture.client()).getControlPlaneRequestId()).isEqualTo(REQUEST_ID); + assertThat(calls).hasValue(1); + } + } + + @Test + void requiresUsableMutualTlsBeforeAnyTransportUse() throws Exception { + var plaintext = accountTls.copy(); + plaintext.setPlaintext(true); + var missing = accountTls.copy(); + missing.setCertChain(pkiDirectory.resolve("missing-certificate.pem").toString()); + var absentClientKey = accountTls.copy(); + absentClientKey.setPrivateKey(null); + var absentClientCertificate = accountTls.copy(); + absentClientCertificate.setCertChain(null); + for (var tls : List.of(plaintext, missing, absentClientKey, absentClientCertificate)) { + var factory = mock(GrpcChannelFactory.class); + try (var client = + new StartSessionReservationEvidenceClient( + new ServiceEndpointsProperties(), tls, factory, "world-runtime", CLOCK)) { + assertThatThrownBy(() -> readIssue(client)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mTLS"); + org.mockito.Mockito.verifyNoInteractions(factory); + } + } } - private static InProcessFixture inProcessFixture(EvidenceHandler handler) throws Exception { - String serverName = InProcessServerBuilder.generateName(); + private static ReadCurrentClaimEvidenceResponse readIssue( + StartSessionReservationEvidenceClient client) { + return client.readCurrentClaimEvidence( + tuple(), + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE); + } + + private static MtlsFixture mtlsFixture(EvidenceHandler handler) throws Exception { + return mtlsFixture("logging", handler); + } + + private static MtlsFixture mtlsFixture(String identity, EvidenceHandler handler) + throws Exception { + var serverIdentity = pki.server(identity); Server server = - InProcessServerBuilder.forName(serverName) - .directExecutor() + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) .addService( - new StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceImplBase() { - @Override - public void readCurrentClaimEvidence( - ReadCurrentClaimEvidenceRequest request, - StreamObserver responseObserver) { - try { - responseObserver.onNext(handler.read(request)); - responseObserver.onCompleted(); - } catch (StatusRuntimeException exception) { - responseObserver.onError(exception); - } - } - }) + ServerInterceptors.intercept( + new StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceImplBase() { + @Override + public void readCurrentClaimEvidence( + ReadCurrentClaimEvidenceRequest request, + StreamObserver responseObserver) { + assertThat(GrpcPeerIdentity.current().uri()) + .isEqualTo("spiffe://firemud/ns/world-runtime/sa/account-service"); + try { + responseObserver.onNext(handler.read(request)); + responseObserver.onCompleted(); + } catch (StatusRuntimeException exception) { + responseObserver.onError(exception); + } + } + }, + new GrpcPeerIdentityInterceptor(), + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + assertThat( + headers.get( + io.grpc.Metadata.Key.of( + "authorization", io.grpc.Metadata.ASCII_STRING_MARSHALLER))) + .isNull(); + return next.startCall(call, headers); + } + })) .build() .start(); - ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); - return new InProcessFixture(server, channel); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService("localhost:" + server.getPort()); + var client = + new StartSessionReservationEvidenceClient( + endpoints, accountTls, new GrpcChannelFactory(), "world-runtime", CLOCK); + try { + client.init(); + return new MtlsFixture(server, client); + } catch (Exception failure) { + client.close(); + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + throw failure; + } } private static ReadCurrentClaimEvidenceRequest request( @@ -440,11 +578,15 @@ private static StartSessionReservationEvidencePurpose toWirePurpose( } private static StartSessionPreAuthorizationReservationTuple tuple() { + return tuple("world-runtime"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String targetNamespace) { StartSessionOperatorAction action = new StartSessionOperatorAction( StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Scope(TENANT_ID, targetNamespace), new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), StartSessionOperatorAction.ExpectedVersion.ABSENT, new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), @@ -477,30 +619,12 @@ private interface EvidenceHandler { ReadCurrentClaimEvidenceResponse read(ReadCurrentClaimEvidenceRequest request); } - private record InProcessFixture(Server server, ManagedChannel channel) implements AutoCloseable { - private StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceBlockingStub - stub() { - return StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel); - } - + private record MtlsFixture(Server server, StartSessionReservationEvidenceClient client) + implements AutoCloseable { @Override public void close() throws Exception { - channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + client.close(); server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } } - - private record StartSessionReservationClientTestAccess( - StartSessionReservationEvidenceClient client) { - private void installStub( - StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceBlockingStub - stub) - throws Exception { - var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); - field.setAccessible(true); - field.set(client, stub); - } - } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java new file mode 100644 index 0000000000..e738bd42f4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.accountservice.testsupport; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +/** Actual stalled JDK children exercise only this fixture's process deadline and cleanup. */ +class AccountStartSessionReservationProofPkiTest { + @TempDir Path directory; + + @Test + @Timeout(15) + void timeoutTerminatesAndReapsTheStalledChild() throws Exception { + Process process = awaitingPassword(); + try { + assertThatThrownBy( + () -> + AccountStartSessionReservationProofPki.awaitKeytoolExit( + process, 1, TimeUnit.SECONDS)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("execution deadline"); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + cleanup(process); + } + } + + @Test + @Timeout(15) + void interruptionTerminatesAndReapsTheChildAndRestoresTheInterruptFlag() throws Exception { + Process process = awaitingPassword(); + try { + Thread.currentThread().interrupt(); + assertThatThrownBy( + () -> + AccountStartSessionReservationProofPki.awaitKeytoolExit( + process, 30, TimeUnit.SECONDS)) + .isInstanceOf(InterruptedException.class); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + Thread.interrupted(); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + Thread.interrupted(); + cleanup(process); + } + } + + private Process awaitingPassword() throws Exception { + var keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + return new ProcessBuilder( + keytool.toString(), + "-genkeypair", + "-alias", + "controlled-timeout", + "-keyalg", + "RSA", + "-keystore", + directory.resolve("pending-password.p12").toString(), + "-storetype", + "PKCS12") + .redirectErrorStream(true) + .start(); + } + + private static void cleanup(Process process) throws Exception { + if (process.isAlive()) process.destroyForcibly(); + assertThat(process.waitFor(5, TimeUnit.SECONDS)).isTrue(); + process.getOutputStream().close(); + process.getInputStream().close(); + process.getErrorStream().close(); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java new file mode 100644 index 0000000000..9cf669c274 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java @@ -0,0 +1,346 @@ +package net.firedevops.firemud.accountservice.testsupport; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; + +/** Controlled loopback PKI for the original Logging claim-read client; no production authority. */ +public final class AccountStartSessionReservationProofPki { + private static final String PASSWORD = "test-only-reservation-pki-password"; + private final Path directory; + private final X509Certificate ca; + private final Map servers; + private final Identity account; + + private AccountStartSessionReservationProofPki( + Path directory, X509Certificate ca, Map servers, Identity account) { + this.directory = directory; + this.ca = ca; + this.servers = servers; + this.account = account; + } + + public static AccountStartSessionReservationProofPki create(Path directory, String namespace) + throws Exception { + Files.createDirectories(directory); + Path caStore = directory.resolve("reservation-test-ca.p12"); + Path caFile = directory.resolve("reservation-test-ca.crt"); + runKeytool( + directory, + "-genkeypair", + "-alias", + "reservation-test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=Controlled Logging claim-read test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + runKeytool( + directory, + "-exportcert", + "-alias", + "reservation-test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + Map servers = + Map.of( + "logging", + issue( + directory, + caStore, + caFile, + "logging-server", + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + true), + "wrong-workload", + issue( + directory, + caStore, + caFile, + "wrong-workload-server", + "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", + true), + "missing-identity", + issue( + directory, + caStore, + caFile, + "missing-identity-server", + "https://localhost/controlled-test", + true), + "wrong-namespace", + issue( + directory, + caStore, + caFile, + "wrong-namespace-server", + "spiffe://firemud/ns/other-runtime/sa/logging-admin-service", + true)); + Identity account = + issue( + directory, + caStore, + caFile, + "account-client", + "spiffe://firemud/ns/" + namespace + "/sa/account-service", + false); + return new AccountStartSessionReservationProofPki( + directory, readCertificate(caFile), servers, account); + } + + public Identity accountIdentity() { + return account; + } + + public X509Certificate caCertificate() { + return ca; + } + + public Identity server(String name) { + return java.util.Objects.requireNonNull(servers.get(name)); + } + + public CommonGrpcClientProperties clientProperties() throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain( + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + account.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + account.privateKey().getEncoded()) + .toString()); + tls.setCaCert( + writePem(directory.resolve("account-client-trust.crt"), "CERTIFICATE", ca.getEncoded()) + .toString()); + return tls; + } + + private static Identity issue( + Path directory, Path caStore, Path caFile, String alias, String uri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path csr = directory.resolve(alias + ".csr"); + Path cert = directory.resolve(alias + "-signed.crt"); + String san = server ? "URI:" + uri + ",DNS:localhost,IP:127.0.0.1" : "URI:" + uri; + String usage = server ? "serverAuth" : "clientAuth"; + runKeytool( + directory, + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + runKeytool( + directory, + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + csr.toString(), + "-ext", + "SAN=" + san); + runKeytool( + directory, + "-gencert", + "-alias", + "reservation-test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-infile", + csr.toString(), + "-outfile", + cert.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san); + runKeytool( + directory, + "-importcert", + "-alias", + "reservation-test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + directory, + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + cert.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, PASSWORD.toCharArray()); + } + return new Identity( + alias, + (PrivateKey) keyStore.getKey(alias, PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(Path directory, String... args) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + ArrayList command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(args)); + Path output = Files.createTempFile(directory, "keytool-output-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(output.toFile()) + .start(); + awaitKeytoolExit(process, 30, TimeUnit.SECONDS); + if (process.exitValue() != 0) { + throw new IllegalStateException("test keytool failed: " + Files.readString(output)); + } + } finally { + Files.deleteIfExists(output); + } + } + + /** Waits before reading child output, then terminates and reaps on timeout or interruption. */ + static void awaitKeytoolExit(Process process, long timeout, TimeUnit unit) + throws InterruptedException { + try { + if (!process.waitFor(timeout, unit)) { + throw new IllegalStateException("test keytool exceeded its execution deadline"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } finally { + boolean restoreInterrupt = Thread.interrupted(); + try { + if (process.isAlive()) process.destroyForcibly(); + long cleanupDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + boolean reaped = false; + while (!reaped) { + long remaining = cleanupDeadline - System.nanoTime(); + if (remaining <= 0) { + throw new IllegalStateException("test keytool could not be reaped after termination"); + } + try { + reaped = process.waitFor(remaining, TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + restoreInterrupt = true; + } + } + } finally { + if (restoreInterrupt) Thread.currentThread().interrupt(); + } + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + public record Identity(String alias, PrivateKey privateKey, X509Certificate certificate) {} +} From 99444dd9d181a3493b3f9aded007c7170604d68e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:13:50 +1300 Subject: [PATCH 26/61] Recheck original creator expiry at current callback boundary --- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 6 + .../session/AccountControlUiActorService.java | 8 ++ ...inalDraftOrderPostgresIntegrationTest.java | 113 ++++++++++++++++++ 4 files changed, 132 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index f9519df4cb..98104a0eca 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -130,3 +130,8 @@ Entry format: - Context: Reading subprocess output to EOF before a timed wait leaves the supposed deadline unbounded. - Observation: The original claim-read test PKI helper now redirects output to an owned temporary file, waits before reading it, and terminates/reaps a timed-out or interrupted child with interrupt preservation. Actual stalled-keytool timeout and interruption cases pass alongside the affected TLS and native owner proofs. - Expected pattern: Keep this correction in the purpose-specific fixture; it does not require a general command framework or change production TLS material policy. + +- `2026-10-16`: Recheck original ControlUI expiry after owner locks + - Context: An initial ControlUI token expiry check became stale across later owner locks in both current-actor paths. Registry cleanup retention and authorization-reference expiry did not replace the original token's validity boundary. + - Observation: The focused native fixture advances the existing actor clock at the real locking read: the old code entered both callbacks after expiry; the correction rejects them without changing the original row while preserving exact held-order recovery. + - Expected pattern: Keep current authorization and historical recovery distinct when reconciling displaced guards. 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 b9b7be005f..f775d306f0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,12 @@ The focused Game Session owner fixture retains original unsafe numeric v1 fence The existing [World original-owner composition](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java) now passes its positive operation at fence values 9,007,199,254,740,992, 9,007,199,254,740,993 and 9,223,372,036,854,775,807. Actual Account issuance/redemption, native Game Session storage and the authenticated Account-to-Game Session current-attempt mTLS read preserve each exact fence, original tuple and redemption projection; the authenticated read leaves the complete stored row and row version unchanged. All three fresh parameterized cases pass with zero failures, errors or skips at source `f1ba70374fab5c7d7a4b733c0bea2bd842a2cd7b`, together with affected cross-service static analysis, formatting and documentation checks. The strict passive observer owns all three run-created PostgreSQL containers, with an inherited resource-session descriptor, no ownership gaps or observer errors, and all three absent after completion. This closes the two focused owner-tuple proof gaps within these controlled fixtures. Creator, Logging claims, publication/launch evidence and PKI remain controlled; the existing World preparation/activation and Account settlement composition uses unregistered owners and a test-local World transport wrapper. It does not establish genuine issuer/environment authority, deployed composition, gameplay admission, Entity placement or completion of any genuine handoff. +### Original creator expiry at the callback boundary + +Both current-actor methods recheck the original ControlUI token expiry after their final blocking owner operations, immediately before invoking a fresh authorization callback. They reuse the existing clock and original immutable expiry; no token, registry deadline, source evidence or retained order is rewritten. Exact historical recovery of an already-held original order remains permitted after creator expiry. + +The existing Account original-order PostgreSQL fixture advances its injected actor clock when the actual final owner locking read completes. Both old methods entered the callback despite expiry; the corrected fixture proves denial in the signed-credential and committed-token paths, no callback, and unchanged original row JSON and row version. Those two cases and the existing expired-creator exact-recovery case pass at `43731b6a4a754375aad43e0d71932350bf5aa7f7`, with zero failures, errors or skips, affected integration static analysis and formatting. Main static checks and the unchanged healthy secured Account owner case retain their passing attribution at `d7609c6ed5f42c75475733ede30a727fb4f9947f`, with the identical production blob. The earlier aggregate failure was only the fixture's nullable lookup; exact-cardinality lookups correct it without weakening the proof. Strict passive capture owns the final run's one PostgreSQL container with inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container afterward; the preceding four-case run owned two, also absent afterward. This establishes a controlled temporal boundary at a real locking read, not measured lock-wait duration, continuous production protection, genuine upstream authority, activation, admission or Entity delivery. + ### Original Logging claim-read client The existing Account StartSession reservation-evidence client pins the configured Logging & Admin workload URI with the shared pre-request credentials and response verifier. It uses workload-only mTLS without the generic bearer-token stub customizer, rejects caller context and ambient SQL transactions or synchronization before RPC, and preserves the original tuple, purpose, deadline and exact response binding checks. The server identity comes from the existing configured workload namespace, independently of the mutation target namespace. Usable configured certificate, key and CA resources are required without adding a universal regular-file storage restriction; the existing default-off registration stays unchanged. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java index 2c42841b14..e2ac9f59a2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -168,6 +168,7 @@ T withCurrent( if (!committed.tokenHash().equals(tokenHash)) { throw denied(); } + requireUnexpiredOriginalToken(stored); return action.apply(new Current(stored, current)); }); } @@ -223,10 +224,17 @@ T withCurrentCommitted( || !Arrays.equals(committed.activeRegistry, exactRegistry)) { throw denied(); } + requireUnexpiredOriginalToken(committed); return action.apply(new Current(committed, current)); }); } + private void requireUnexpiredOriginalToken(AccountControlUiIssuanceRepository.Stored original) { + if (original.expiresAt == null || !clock.instant().isBefore(original.expiresAt)) { + throw denied(); + } + } + /** Production asymmetric/profile verification, also used before any candidate is persisted. */ SignedObservation verifySigned(String compactJwt) { outsideSql(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java index b5baf98e77..2714de293b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import io.grpc.Context; import java.nio.file.Path; @@ -12,6 +13,7 @@ import java.time.ZoneOffset; import java.util.List; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; @@ -19,8 +21,13 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.ExecuteContext; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.PostgreSQLContainer; @@ -78,6 +85,112 @@ class AccountOriginalDraftOrderPostgresIntegrationTest { @TempDir Path temporary; + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void originalCreatorExpiryAtFinalOwnerLockDeniesCurrentCallback( + boolean signedCredential, @TempDir Path proofDirectory) throws Exception { + var clock = new ActorClock(); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + proofDirectory, + UUID.randomUUID(), + clock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + String tokenHash = + AccountControlUiCoordination.digest( + "SHA-256", issued.compact().getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + var jti = + f.tx( + () -> + f.dsl + .fetchSingle( + "SELECT token_jti FROM account_control_ui_issuance_operations " + + "WHERE token_hash=? AND status='COMMITTED'", + tokenHash) + .get("token_jti", UUID.class)); + var before = + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_jti=?", + jti)); + var callback = new AtomicBoolean(); + var clockAdvanced = new AtomicBoolean(); + var originalListeners = f.dsl.configuration().executeListenerProviders(); + var expiryAtOwnerLock = + new DefaultExecuteListenerProvider( + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && sql.contains("account_control_ui_issuance_operations") + && sql.contains("FOR UPDATE") + && clockAdvanced.compareAndSet(false, true)) { + // The real locking read has completed; simulate elapsed time at this precise + // boundary. + // This is deterministic temporal-boundary proof, not physical lock-contention + // proof. + clock.advance(Duration.ofMinutes(10)); + } + } + }); + var listeners = java.util.Arrays.copyOf(originalListeners, originalListeners.length + 1); + listeners[originalListeners.length] = expiryAtOwnerLock; + f.dsl.configuration().set(listeners); + try { + Throwable failure = + catchThrowable( + () -> { + if (signedCredential) { + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + callback.set(true); + return "must not authorize"; + }); + } else { + issued + .actors() + .withCurrentCommitted( + f.account.getAccountUuid(), + f.tenant, + jti, + issued.environment(), + current -> { + callback.set(true); + return "must not authorize"; + }); + } + }); + assertThat(clockAdvanced).isTrue(); + assertThat(callback).isFalse(); + assertThat(failure).isInstanceOf(IllegalStateException.class); + assertThat( + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_jti=?", + jti))) + .isEqualTo(before); + } finally { + f.dsl.configuration().set(originalListeners); + } + } + } + @Test void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrSubstitute() throws Exception { From 9c11695252c34a536d797ed9c00975873e650586 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:34:18 +1300 Subject: [PATCH 27/61] Align retained inventory migration fixture with digest schema three --- ...ceCurrentnessForwardMigrationsPostgresIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java index 627d60ce9d..012428b62e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java @@ -915,7 +915,7 @@ private static void exerciseSelectedPublicationV2Settlement( "publishWorkflowId", jsonString(workflowId.toString()), "appliedCommitId", jsonString(selectedCommit.commitId().toString()), "contentDigest", jsonString(contentDigest), - "digestSchemaVersion", "1", + "digestSchemaVersion", "3", "worldAffectedTuples", expectedTuples); String selectorJson = jsonObject( @@ -1021,7 +1021,7 @@ private static void exerciseSelectedPublicationV2Settlement( jsonObject( "appliedCommitId", jsonString(selectedCommit.commitId().toString()), "contentDigest", jsonString(contentDigest), - "digestSchemaVersion", "1"), + "digestSchemaVersion", "3"), "sourceModel", modelJson, "artifactDecisions", "[{\"artifactKind\":\"NAVMESH\",\"state\":\"NOT_REQUIRED\"," From e088daf69f842142a76bed461fd325c80e041fbe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 13:24:18 +1300 Subject: [PATCH 28/61] Enforce complete original actor validity at fresh callback --- design/project-management/ai-observations.md | 5 ++ .../player-access-and-session.md | 6 +- .../session/AccountControlUiActorService.java | 12 ++-- ...inalDraftOrderPostgresIntegrationTest.java | 72 +++++++++++++++---- 4 files changed, 76 insertions(+), 19 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 98104a0eca..b786baba35 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -135,3 +135,8 @@ Entry format: - Context: An initial ControlUI token expiry check became stale across later owner locks in both current-actor paths. Registry cleanup retention and authorization-reference expiry did not replace the original token's validity boundary. - Observation: The focused native fixture advances the existing actor clock at the real locking read: the old code entered both callbacks after expiry; the correction rejects them without changing the original row while preserving exact held-order recovery. - Expected pattern: Keep current authorization and historical recovery distinct when reconciling displaced guards. + +- `2026-10-16`: Compare the complete original validity interval at one owner boundary + - Context: original creator callbacks can wait for Account owner locks after initial token verification. + - Observation: an expiry-only final check misses a clock observation before the original not-before bound; registry cleanup retention and authorization-reference expiry do not define the original token's full interval. + - Expected pattern: use one existing-clock observation for the canonical original `issuedAt <= now < expiresAt` interval, test both denial bounds and exact lower-bound equality, preserve immutable evidence, and keep historical exact-order recovery separate from fresh authorization. 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 f775d306f0..90a972fd10 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,11 +12,11 @@ The focused Game Session owner fixture retains original unsafe numeric v1 fence The existing [World original-owner composition](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java) now passes its positive operation at fence values 9,007,199,254,740,992, 9,007,199,254,740,993 and 9,223,372,036,854,775,807. Actual Account issuance/redemption, native Game Session storage and the authenticated Account-to-Game Session current-attempt mTLS read preserve each exact fence, original tuple and redemption projection; the authenticated read leaves the complete stored row and row version unchanged. All three fresh parameterized cases pass with zero failures, errors or skips at source `f1ba70374fab5c7d7a4b733c0bea2bd842a2cd7b`, together with affected cross-service static analysis, formatting and documentation checks. The strict passive observer owns all three run-created PostgreSQL containers, with an inherited resource-session descriptor, no ownership gaps or observer errors, and all three absent after completion. This closes the two focused owner-tuple proof gaps within these controlled fixtures. Creator, Logging claims, publication/launch evidence and PKI remain controlled; the existing World preparation/activation and Account settlement composition uses unregistered owners and a test-local World transport wrapper. It does not establish genuine issuer/environment authority, deployed composition, gameplay admission, Entity placement or completion of any genuine handoff. -### Original creator expiry at the callback boundary +### Original creator validity at the callback boundary -Both current-actor methods recheck the original ControlUI token expiry after their final blocking owner operations, immediately before invoking a fresh authorization callback. They reuse the existing clock and original immutable expiry; no token, registry deadline, source evidence or retained order is rewritten. Exact historical recovery of an already-held original order remains permitted after creator expiry. +Both current-actor methods compare the original ControlUI token's complete validity interval after their final blocking owner operations, immediately before invoking a fresh authorization callback. One observation of the existing clock must satisfy `issuedAt <= now < expiresAt`; the canonical original issuance has whole-second `issuedAt = iat = nbf` and zero skew. The original token, registry cleanup deadline, source evidence and retained order remain unchanged. Exact historical recovery of an already-held original order remains permitted after creator expiry. -The existing Account original-order PostgreSQL fixture advances its injected actor clock when the actual final owner locking read completes. Both old methods entered the callback despite expiry; the corrected fixture proves denial in the signed-credential and committed-token paths, no callback, and unchanged original row JSON and row version. Those two cases and the existing expired-creator exact-recovery case pass at `43731b6a4a754375aad43e0d71932350bf5aa7f7`, with zero failures, errors or skips, affected integration static analysis and formatting. Main static checks and the unchanged healthy secured Account owner case retain their passing attribution at `d7609c6ed5f42c75475733ede30a727fb4f9947f`, with the identical production blob. The earlier aggregate failure was only the fixture's nullable lookup; exact-cardinality lookups correct it without weakening the proof. Strict passive capture owns the final run's one PostgreSQL container with inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container afterward; the preceding four-case run owned two, also absent afterward. This establishes a controlled temporal boundary at a real locking read, not measured lock-wait duration, continuous production protection, genuine upstream authority, activation, admission or Entity delivery. +The existing Account original-order PostgreSQL fixture changes its injected actor clock when the real final owner locking read completes. The earlier expiry-only code enters both callbacks when that clock moves before the original not-before boundary. The corrected fixture denies both early and expired callbacks without changing the original row JSON or row version, permits both callbacks at exact original `issuedAt` equality, and preserves the existing expired-creator exact-recovery case. These seven native cases plus the unchanged healthy secured Account owner case pass at `cefccc984d6154b9d1b8c3e439541584d2844fc8` with zero failures, errors or skips and affected integration static analysis and formatting. Seven existing Actor unit cases and Main/unit static analysis retain their passing attribution at `774864935ba9783dab410507689ad2848c00fe15`, with the identical production blob. That earlier aggregate failed only because the fixture used an unavailable assertion overload; the test-only correction retains its exact Boolean predicate. Strict passive capture owns the final run's two PostgreSQL containers with inherited resource-session descriptor, no ownership gaps or observer errors, and neither container remaining afterward. This establishes a controlled temporal boundary at a real locking read, not measured physical contention, continuous production protection, genuine upstream authority, activation, admission or Entity delivery. ### Original Logging claim-read client diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java index e2ac9f59a2..20ba8c08b6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -168,7 +168,7 @@ T withCurrent( if (!committed.tokenHash().equals(tokenHash)) { throw denied(); } - requireUnexpiredOriginalToken(stored); + requireCurrentOriginalToken(stored); return action.apply(new Current(stored, current)); }); } @@ -224,13 +224,17 @@ T withCurrentCommitted( || !Arrays.equals(committed.activeRegistry, exactRegistry)) { throw denied(); } - requireUnexpiredOriginalToken(committed); + requireCurrentOriginalToken(committed); return action.apply(new Current(committed, current)); }); } - private void requireUnexpiredOriginalToken(AccountControlUiIssuanceRepository.Stored original) { - if (original.expiresAt == null || !clock.instant().isBefore(original.expiresAt)) { + private void requireCurrentOriginalToken(AccountControlUiIssuanceRepository.Stored original) { + var now = clock.instant(); + if (original.issuedAt == null + || original.expiresAt == null + || now.isBefore(original.issuedAt) + || !now.isBefore(original.expiresAt)) { throw denied(); } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java index 2714de293b..dbec8781d5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java @@ -89,6 +89,28 @@ class AccountOriginalDraftOrderPostgresIntegrationTest { @ValueSource(booleans = {true, false}) void originalCreatorExpiryAtFinalOwnerLockDeniesCurrentCallback( boolean signedCredential, @TempDir Path proofDirectory) throws Exception { + assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( + signedCredential, proofDirectory, Duration.ofMinutes(10)); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void originalCreatorNotBeforeAtFinalOwnerLockDeniesCurrentCallback( + boolean signedCredential, @TempDir Path proofDirectory) throws Exception { + assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( + signedCredential, proofDirectory, Duration.ofMinutes(-10)); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void originalCreatorIssuedAtEqualityAtFinalOwnerLockAllowsCurrentCallback( + boolean signedCredential, @TempDir Path proofDirectory) throws Exception { + assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( + signedCredential, proofDirectory, Duration.ZERO); + } + + private void assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( + boolean signedCredential, Path proofDirectory, Duration clockChange) throws Exception { var clock = new ActorClock(); try (var fixture = new AccountControlUiOriginalOrderFixture( @@ -114,6 +136,16 @@ void originalCreatorExpiryAtFinalOwnerLockDeniesCurrentCallback( + "WHERE token_hash=? AND status='COMMITTED'", tokenHash) .get("token_jti", UUID.class)); + long issuedAt = + java.util.Objects.requireNonNull( + f.tx( + () -> + f.dsl + .fetchSingle( + "SELECT issued_at_epoch_second FROM account_control_ui_issuance_operations " + + "WHERE token_jti=?", + jti) + .get("issued_at_epoch_second", Long.class))); var before = f.tx( () -> @@ -122,9 +154,9 @@ void originalCreatorExpiryAtFinalOwnerLockDeniesCurrentCallback( + "FROM account_control_ui_issuance_operations a WHERE token_jti=?", jti)); var callback = new AtomicBoolean(); - var clockAdvanced = new AtomicBoolean(); + var clockChanged = new AtomicBoolean(); var originalListeners = f.dsl.configuration().executeListenerProviders(); - var expiryAtOwnerLock = + var timeChangeAtOwnerLock = new DefaultExecuteListenerProvider( new DefaultExecuteListener() { @Override @@ -133,17 +165,21 @@ public void executeEnd(ExecuteContext context) { if (sql != null && sql.contains("account_control_ui_issuance_operations") && sql.contains("FOR UPDATE") - && clockAdvanced.compareAndSet(false, true)) { + && clockChanged.compareAndSet(false, true)) { // The real locking read has completed; simulate elapsed time at this precise // boundary. // This is deterministic temporal-boundary proof, not physical lock-contention // proof. - clock.advance(Duration.ofMinutes(10)); + if (clockChange.isZero()) { + clock.freezeAt(Instant.ofEpochSecond(issuedAt)); + } else { + clock.advance(clockChange); + } } } }); var listeners = java.util.Arrays.copyOf(originalListeners, originalListeners.length + 1); - listeners[originalListeners.length] = expiryAtOwnerLock; + listeners[originalListeners.length] = timeChangeAtOwnerLock; f.dsl.configuration().set(listeners); try { Throwable failure = @@ -158,7 +194,7 @@ public void executeEnd(ExecuteContext context) { issued.environment(), current -> { callback.set(true); - return "must not authorize"; + return "callback invoked"; }); } else { issued @@ -170,13 +206,20 @@ public void executeEnd(ExecuteContext context) { issued.environment(), current -> { callback.set(true); - return "must not authorize"; + return "callback invoked"; }); } }); - assertThat(clockAdvanced).isTrue(); - assertThat(callback).isFalse(); - assertThat(failure).isInstanceOf(IllegalStateException.class); + assertThat(clockChanged).isTrue(); + assertThat(clock.instant().isBefore(Instant.ofEpochSecond(issuedAt))) + .isEqualTo(clockChange.isNegative()); + assertThat(callback.get()).isEqualTo(clockChange.isZero()); + if (clockChange.isZero()) { + assertThat(clock.instant()).isEqualTo(Instant.ofEpochSecond(issuedAt)); + assertThat(failure).isNull(); + } else { + assertThat(failure).isInstanceOf(IllegalStateException.class); + } assertThat( f.tx( () -> @@ -468,6 +511,11 @@ private static void asPeer(String namespace, String workload, Runnable action) { private static final class ActorClock extends Clock { private Duration offset = Duration.ZERO; + private Instant frozen; + + void freezeAt(Instant value) { + frozen = value; + } void advance(Duration amount) { offset = offset.plus(amount); @@ -478,11 +526,11 @@ public ZoneId getZone() { } public Clock withZone(ZoneId zone) { - return Clock.offset(Clock.system(zone), offset); + return frozen == null ? Clock.offset(Clock.system(zone), offset) : Clock.fixed(frozen, zone); } public Instant instant() { - return Instant.now().plus(offset); + return frozen == null ? Instant.now().plus(offset) : frozen; } } } From 442a4592664b48fba493d8a70bf220fba367a735 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 13:32:32 +1300 Subject: [PATCH 29/61] Expose selected settlement test stage and container timing --- ...nerPublicationPostgresIntegrationTest.java | 282 +++++++++++++++--- 1 file changed, 244 insertions(+), 38 deletions(-) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 6bfc3db9fb..26db7185dd 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -22,10 +22,13 @@ import java.util.ArrayList; import java.util.Date; import java.util.HexFormat; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Supplier; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestGrpcReceiver; import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestService; @@ -124,7 +127,9 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -211,6 +216,13 @@ class SelectedFullOwnerPublicationPostgresIntegrationTest { @Test void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchemaFourBundle() throws Exception { + var diagnostics = new SettlementDiagnostics(); + diagnostics.logPostgres("game-design", GDS_POSTGRES); + diagnostics.logPostgres("world-management", WORLD_POSTGRES); + diagnostics.logPostgres("entity-management", ENTITY_POSTGRES); + diagnostics.logPostgres("automation-scripting", AUTOMATION_POSTGRES); + diagnostics.logPostgres("game-logic", GAME_LOGIC_POSTGRES); + diagnostics.logPostgres("account", ACCOUNT_POSTGRES); Store gds = store("game-design", "selected_full_gds", GDS_POSTGRES, false); Store world = store("world-management", "selected_full_world", WORLD_POSTGRES, false); Store entity = store("entity-management", "selected_full_entity", ENTITY_POSTGRES, true); @@ -805,7 +817,8 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema accountSources.dsl, accountSources.manager, pki, - selectedOwnerReservation.operation()); + selectedOwnerReservation.operation(), + diagnostics); assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); } } finally { @@ -1135,7 +1148,8 @@ private static void completeActualWorldAndAccountTerminals( org.jooq.DSLContext accountDsl, org.springframework.transaction.PlatformTransactionManager accountTransactions, ProofPki pki, - net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation) + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation, + SettlementDiagnostics diagnostics) throws Exception { requireAccountClosureInventoryRefusals(accountDsl, operation); var gdsOwner = @@ -1147,8 +1161,10 @@ private static void completeActualWorldAndAccountTerminals( ownerServer( pki, "game-design-service", - new net.firedevops.firemud.gamedesign.publication - .GameDesignPublicationTerminalReadGrpcService(gdsOwner, NAMESPACE)); + diagnostics.timedGrpc( + "gds-terminal-read", + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationTerminalReadGrpcService(gdsOwner, NAMESPACE))); Server worldTerminalServer = null; Server accountSettlementServer = null; var endpoints = new ServiceEndpointsProperties(); @@ -1170,11 +1186,13 @@ private static void completeActualWorldAndAccountTerminals( "world-management-service", new net.firedevops.firemud.worldmanagement.tenant .WorldPublicationTerminalCompletionGrpcService(worldOwner, NAMESPACE), - new net.firedevops.firemud.worldmanagement.tenant - .WorldPublicationTerminalReadGrpcService( + diagnostics.timedGrpc( + "world-terminal-read", new net.firedevops.firemud.worldmanagement.tenant - .WorldPublicationTerminalReadService(worldRepository, NAMESPACE), - NAMESPACE)); + .WorldPublicationTerminalReadGrpcService( + new net.firedevops.firemud.worldmanagement.tenant + .WorldPublicationTerminalReadService(worldRepository, NAMESPACE), + NAMESPACE))); endpoints.setWorldManagementService(loopback(worldTerminalServer)); try (var accountGdsRead = new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient( @@ -1193,7 +1211,7 @@ private static void completeActualWorldAndAccountTerminals( new AccountPublicationAuthorizationRepository(accountDsl), accountGdsRead, accountWorldRead, - accountTransactions, + diagnostics.timeTransactions(accountTransactions), NAMESPACE); var binding = net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding @@ -1202,7 +1220,9 @@ private static void completeActualWorldAndAccountTerminals( ownerServer( pki, "account-service", - new AccountSelectedPublicationSettlementGrpcService(accountOwner, NAMESPACE)); + diagnostics.timedGrpc( + "account-settlement", + new AccountSelectedPublicationSettlementGrpcService(accountOwner, NAMESPACE))); endpoints.setAccountService(loopback(accountSettlementServer)); try (var settlementClient = new net.firedevops.firemud.common.publication @@ -1225,13 +1245,18 @@ private static void completeActualWorldAndAccountTerminals( assertThat(io.grpc.Status.fromThrowable(error).getCode()) .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); } - assertThatThrownBy( - () -> - settlementClient.settle( - net.firedevops.firemud.common.publication - .AccountSelectedPublicationSettlementGrpcCodec.Request.create( - NAMESPACE, operation.canonicalBytes()))) - .isInstanceOf(RuntimeException.class); + diagnostics.phase( + "account-settlement-before-world-terminal", + () -> { + assertThatThrownBy( + () -> + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + return null; + }); assertThat( accountDsl .fetchSingle( @@ -1240,29 +1265,38 @@ private static void completeActualWorldAndAccountTerminals( .get(0, Long.class)) .isZero(); var published = - producer.reconcile( - operation.tenantKey(), - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence - .Outcome.PUBLISHED); - assertThat(published.operationBytes()).containsExactly(operation.canonicalBytes()); - assertThat( - producer - .reconcile( + diagnostics.phase( + "world-producer-reconcile", + () -> + producer.reconcile( operation.tenantKey(), operation.workflowId(), operation.versionId(), operation.selectionDigest(), - published.outcome()) - .canonicalBytes()) + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)); + assertThat(published.operationBytes()).containsExactly(operation.canonicalBytes()); + assertThat( + diagnostics.phase( + "world-producer-exact-retry", + () -> + producer + .reconcile( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + published.outcome()) + .canonicalBytes())) .containsExactly(published.canonicalBytes()); byte[] receipt = - settlementClient.settle( - net.firedevops.firemud.common.publication - .AccountSelectedPublicationSettlementGrpcCodec.Request.create( - NAMESPACE, operation.canonicalBytes())); + diagnostics.phase( + "account-settlement-positive", + () -> + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()))); assertThat(receipt).isNotEmpty(); String retained = accountDsl @@ -1271,10 +1305,13 @@ private static void completeActualWorldAndAccountTerminals( binding.account().operationId()) .get(0, String.class); assertThat( - settlementClient.settle( - net.firedevops.firemud.common.publication - .AccountSelectedPublicationSettlementGrpcCodec.Request.create( - NAMESPACE, operation.canonicalBytes()))) + diagnostics.phase( + "account-settlement-exact-retry", + () -> + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes())))) .containsExactly(receipt); assertThat( accountDsl @@ -1815,6 +1852,175 @@ private static String loopback(Server server) { return "127.0.0.1:" + server.getPort(); } + private static final class SettlementDiagnostics { + private final AtomicLong sequence = new AtomicLong(); + + void logPostgres(String role, PostgreSQLContainer postgres) { + try { + System.out.printf( + "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s container=%s host=%s mapped_port=%d running=%s%n", + role, + postgres.getContainerId(), + postgres.getHost(), + postgres.getMappedPort(5432), + postgres.isRunning()); + } catch (RuntimeException unavailable) { + System.out.printf( + "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s status=unavailable error=%s%n", + role, unavailable.getClass().getSimpleName()); + } + } + + T phase(String stage, Supplier action) { + long call = sequence.incrementAndGet(); + long started = System.nanoTime(); + event(call, stage, "start", 0L, "none"); + try { + T result = action.get(); + event(call, stage, "complete", System.nanoTime() - started, "OK"); + return result; + } catch (RuntimeException | Error failure) { + event( + call, + stage, + "failed", + System.nanoTime() - started, + failure.getClass().getSimpleName()); + throw failure; + } + } + + io.grpc.BindableService timedGrpc(String stage, io.grpc.BindableService owner) { + return () -> + ServerInterceptors.intercept( + owner, + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + long callSequence = sequence.incrementAndGet(); + long started = System.nanoTime(); + String method = call.getMethodDescriptor().getFullMethodName(); + var recorded = new java.util.concurrent.atomic.AtomicBoolean(); + var timedCall = + new io.grpc.ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void close(io.grpc.Status status, io.grpc.Metadata trailers) { + if (recorded.compareAndSet(false, true)) { + event( + callSequence, + stage + "/" + method, + "closed", + System.nanoTime() - started, + status.getCode().name()); + } + super.close(status, trailers); + } + }; + event(callSequence, stage + "/" + method, "start", 0L, "STARTED"); + var listener = next.startCall(timedCall, headers); + return new io.grpc.ForwardingServerCallListener + .SimpleForwardingServerCallListener<>(listener) { + @Override + public void onCancel() { + if (recorded.compareAndSet(false, true)) { + event( + callSequence, + stage + "/" + method, + "cancelled", + System.nanoTime() - started, + "CANCELLED"); + } + super.onCancel(); + } + }; + } + }); + } + + PlatformTransactionManager timeTransactions(PlatformTransactionManager delegate) { + return new PlatformTransactionManager() { + private final Map active = new IdentityHashMap<>(); + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + long call = sequence.incrementAndGet(); + long started = System.nanoTime(); + event(call, "account-transaction", "acquire-start", 0L, "STARTED"); + try { + TransactionStatus status = delegate.getTransaction(definition); + synchronized (active) { + active.put(status, new TransactionTiming(call, started)); + } + event(call, "account-transaction", "acquired", System.nanoTime() - started, "OK"); + return status; + } catch (RuntimeException | Error failure) { + event( + call, + "account-transaction", + "acquire-failed", + System.nanoTime() - started, + failure.getClass().getSimpleName()); + throw failure; + } + } + + @Override + public void commit(TransactionStatus status) { + finish(status, true); + } + + @Override + public void rollback(TransactionStatus status) { + finish(status, false); + } + + private void finish(TransactionStatus status, boolean commit) { + TransactionTiming timing; + synchronized (active) { + timing = active.remove(status); + } + long completionStarted = System.nanoTime(); + try { + if (commit) { + delegate.commit(status); + } else { + delegate.rollback(status); + } + if (timing != null) { + event( + timing.sequence(), + "account-transaction", + commit ? "committed" : "rolled-back", + System.nanoTime() - timing.startedNanos(), + "completion_ns=" + (System.nanoTime() - completionStarted)); + } + } catch (RuntimeException | Error failure) { + if (timing != null) { + event( + timing.sequence(), + "account-transaction", + commit ? "commit-failed" : "rollback-failed", + System.nanoTime() - timing.startedNanos(), + failure.getClass().getSimpleName()); + } + throw failure; + } + } + }; + } + + private void event(long call, String stage, String event, long elapsedNanos, String result) { + System.out.printf( + "SETTLEMENT_DIAGNOSTIC call=%d stage=%s event=%s elapsed_nanos=%d result=%s%n", + call, stage, event, elapsedNanos, result); + } + + private record TransactionTiming(long sequence, long startedNanos) {} + } + private static Server ownerServer( ProofPki pki, String service, io.grpc.BindableService... handlers) throws Exception { var identity = pki.server(service); From f01c3aa543c5fe7de97f7f28d349860ea2045473 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 13:40:02 +1300 Subject: [PATCH 30/61] Apply canonical formatting to settlement diagnostics --- ...SelectedFullOwnerPublicationPostgresIntegrationTest.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 26db7185dd..530e5001a8 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -1881,11 +1881,7 @@ T phase(String stage, Supplier action) { return result; } catch (RuntimeException | Error failure) { event( - call, - stage, - "failed", - System.nanoTime() - started, - failure.getClass().getSimpleName()); + call, stage, "failed", System.nanoTime() - started, failure.getClass().getSimpleName()); throw failure; } } From 33390a0f702ef4139b11b8d10d1725d5ae8e3373 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 13:43:01 +1300 Subject: [PATCH 31/61] Require original actor key acceptance in protected public snapshot --- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 6 + .../session/AccountControlUiActorService.java | 37 +++- ...inalDraftOrderPostgresIntegrationTest.java | 198 ++++++++++++++++++ .../AccountControlUiSigningAndActorTest.java | 7 + .../AccountControlUiOriginalOrderFixture.java | 16 +- .../AccountControlUiSignerFixture.java | 4 +- 7 files changed, 265 insertions(+), 8 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index b786baba35..783265cf66 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -140,3 +140,8 @@ Entry format: - Context: original creator callbacks can wait for Account owner locks after initial token verification. - Observation: an expiry-only final check misses a clock observation before the original not-before bound; registry cleanup retention and authorization-reference expiry do not define the original token's full interval. - Expected pattern: use one existing-clock observation for the canonical original `issuedAt <= now < expiresAt` interval, test both denial bounds and exact lower-bound equality, preserve immutable evidence, and keep historical exact-order recovery separate from fresh authorization. + +- `2026-10-16`: Separate original signer provenance from present public-key acceptance + - Context: fresh signed and committed-JTI creator callbacks must retain their original key identity. + - Observation: an immutable source pin, historical committed-signer receipt and still-fresh signature cache do not independently establish that the original key remains in the current protected public snapshot. + - Expected pattern: load the existing trusted source outside SQL and synchronization, compare the original key ID and RFC 7638 fingerprint, preserve accepted retiring-key membership and historical exact recovery, and state the per-invocation snapshot limit beside the proof. 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 90a972fd10..ba71416f8b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -18,6 +18,12 @@ Both current-actor methods compare the original ControlUI token's complete valid The existing Account original-order PostgreSQL fixture changes its injected actor clock when the real final owner locking read completes. The earlier expiry-only code enters both callbacks when that clock moves before the original not-before boundary. The corrected fixture denies both early and expired callbacks without changing the original row JSON or row version, permits both callbacks at exact original `issuedAt` equality, and preserves the existing expired-creator exact-recovery case. These seven native cases plus the unchanged healthy secured Account owner case pass at `cefccc984d6154b9d1b8c3e439541584d2844fc8` with zero failures, errors or skips and affected integration static analysis and formatting. Seven existing Actor unit cases and Main/unit static analysis retain their passing attribution at `774864935ba9783dab410507689ad2848c00fe15`, with the identical production blob. That earlier aggregate failed only because the fixture used an unavailable assertion overload; the test-only correction retains its exact Boolean predicate. Strict passive capture owns the final run's two PostgreSQL containers with inherited resource-session descriptor, no ownership gaps or observer errors, and neither container remaining afterward. This establishes a controlled temporal boundary at a real locking read, not measured physical contention, continuous production protection, genuine upstream authority, activation, admission or Entity delivery. +### Original creator key acceptance + +Both fresh current-actor paths load the existing trusted public JWKS source outside SQL transactions and synchronization. They require the immutable original signer receipt’s exact key ID and RFC 7638 fingerprint in that protected snapshot, alongside the existing signature/profile, active registry, historical signer provenance, current Account source and final token validity checks. Accepted original keys may coexist with other current public keys; acceptance does not require selecting the newest active signer. The snapshot belongs to one invocation and supplies no guarantee that acceptance continues through later locks, callback or commit. Exact historical held-order recovery remains separate from fresh authentication. + +The existing native original-order fixture proves missing-key and same-key-ID replacement refusal in both paths, accepted-original membership alongside another key, untrusted-source and protected-read failure refusal, and rejection before protected reads under ambient SQL or synchronization. Each parameter compares complete original row JSON and row version. Current snapshot membership is explicitly stipulated through the same concrete source fixture; the source-failure cases execute its real protected observation failure. This models accepted retiring-key membership and does not prove actual signer rotation, publication, withdrawal or compromise authority. At source `5c5363a5ba7caf3af5e6ca9dd93ea212ce3b0c5f`, all fourteen parameters, seven existing native time/equality/recovery cases, the healthy secured Account owner case and seven existing Actor unit cases pass: twenty-nine fresh cases with zero failures, errors or skips. Affected main, unit, integration and test-fixture static analysis, formatting and documentation checks pass. The test-only old-code source `fff5a48653bbcf6e0cd04610dd264c9e1b65c243` first preserves the original row, then fails all four missing/replaced-key callback-denial assertions. The successful run’s strict passive observer owns two PostgreSQL containers with an inherited resource-session descriptor, no ownership gaps or observer errors, and both containers absent afterward. These are bounded component proofs, without genuine upstream authority, runtime registration, gameplay admission or Entity delivery. + ### Original Logging claim-read client The existing Account StartSession reservation-evidence client pins the configured Logging & Admin workload URI with the shared pre-request credentials and response verifier. It uses workload-only mTLS without the generic bearer-token stub customizer, rejects caller context and ambient SQL transactions or synchronization before RPC, and preserves the original tuple, purpose, deadline and exact response binding checks. The server identity comes from the existing configured workload namespace, independently of the mutation target namespace. Usable configured certificate, key and CA resources are required without adding a universal regular-file storage restriction; the existing default-off registration stays unchanged. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java index 20ba8c08b6..c441393805 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -144,6 +144,7 @@ T withCurrent( Function action) { outsideSql(); var signed = verifySigned(compactJwt); + var acceptedKey = readAcceptedSignerKey(signed.claims.keyId()); String tokenHash = AccountControlUiIssuanceRepository.hash(compactJwt.getBytes(StandardCharsets.US_ASCII)); byte[] exactRegistry = registry.readActive(tokenHash); @@ -159,6 +160,7 @@ T withCurrent( throw denied(); } requireSignerIdentity(stored, signed); + requireAcceptedSignerKey(stored, acceptedKey); signers.requireOriginal(stored.signerReceipt); var current = authority.capture(stored.accountId, selectedTenant, environment); if (!Arrays.equals(current.evidence(), stored.sources)) { @@ -203,6 +205,13 @@ T withCurrentCommitted( throw denied(); } + Object receiptKeyId = + AccountControlUiIssuanceRepository.object(original.signerReceipt).get("kid"); + if (!(receiptKeyId instanceof String keyId)) { + throw denied(); + } + var acceptedKey = readAcceptedSignerKey(keyId); + requireAcceptedSignerKey(original, acceptedKey); byte[] exactRegistry = registry.readActive(original.tokenHash); return transaction.execute( ignored -> { @@ -229,6 +238,29 @@ T withCurrentCommitted( }); } + /** + * One protected snapshot per fresh call; this does not promise acceptance through later locks. + */ + private AcceptedSignerKey readAcceptedSignerKey(String keyId) { + outsideSql(); + String fingerprint = + AccountJwtJwksTrustedSource.publicKeyFingerprint( + publicSource.load(), publicSourcePin, keyId) + .orElseThrow(AccountControlUiActorService::denied); + return new AcceptedSignerKey(keyId, fingerprint); + } + + private static void requireAcceptedSignerKey( + AccountControlUiIssuanceRepository.Stored original, AcceptedSignerKey accepted) { + var receipt = AccountControlUiIssuanceRepository.object(original.signerReceipt); + if (!accepted.keyId().equals(receipt.get("kid")) + || !accepted.fingerprint().equals(receipt.get("publicKeyFingerprint"))) { + throw denied(); + } + } + + private record AcceptedSignerKey(String keyId, String fingerprint) {} + private void requireCurrentOriginalToken(AccountControlUiIssuanceRepository.Stored original) { var now = clock.instant(); if (original.issuedAt == null @@ -377,8 +409,9 @@ public String toString() { } private static void outsideSql() { - if (TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException("Signature/registry reads must precede owner SQL locks"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Signature/registry/JWKS reads must precede owner SQL locks"); } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java index dbec8781d5..437d5cb329 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java @@ -15,6 +15,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; @@ -27,6 +28,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; @@ -234,6 +236,202 @@ public void executeEnd(ExecuteContext context) { } } + @ParameterizedTest + @CsvSource({ + "true, ABSENT", "false, ABSENT", "true, REPLACED", "false, REPLACED", + "true, RETAINED", "false, RETAINED", "true, UNTRUSTED", "false, UNTRUSTED", + "true, SOURCE_FAILURE", "false, SOURCE_FAILURE", "true, SQL", "false, SQL", + "true, SYNCHRONIZATION", "false, SYNCHRONIZATION" + }) + void originalCreatorRequiresExactKeyInCurrentProtectedSnapshot( + boolean signedCredential, String keyState, @TempDir Path proofDirectory) throws Exception { + var clock = new ActorClock(); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + proofDirectory, + UUID.randomUUID(), + clock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + clock.freezeAt(clock.instant()); + var originalSnapshot = fixture.publicSource.load(); + var pin = fixture.publicSource.sourceIdentity(); + String tokenHash = + AccountControlUiCoordination.digest( + "SHA-256", issued.compact().getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + var original = + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT token_jti, signer_receipt, row_to_json(a)::TEXT AS payload, " + + "a.xmin::TEXT AS row_version FROM account_control_ui_issuance_operations a " + + "WHERE token_hash=? AND status='COMMITTED'", + tokenHash)); + UUID jti = original.get("token_jti", UUID.class); + var receipt = + AccountControlUiIssuanceRepository.object(original.get("signer_receipt", byte[].class)); + String originalKid = (String) receipt.get("kid"); + assertThat( + AccountJwtJwksTrustedSource.publicKeyFingerprint(originalSnapshot, pin, originalKid)) + .contains((String) receipt.get("publicKeyFingerprint")); + byte[] changed = originalSnapshot.jwksBytes(); + if (java.util.Set.of("ABSENT", "REPLACED", "RETAINED").contains(keyState)) { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + var replacement = + AccountControlUiSignerFixture.publicJwk( + "REPLACED".equals(keyState) ? originalKid : "other-accepted-key", + (java.security.interfaces.RSAPublicKey) generator.generateKeyPair().getPublic()); + var keys = new java.util.ArrayList(); + keys.add( + AccountControlUiIssuanceRepository.object( + replacement.json().getBytes(java.nio.charset.StandardCharsets.UTF_8))); + if ("RETAINED".equals(keyState)) { + // Controlled retiring-key membership: another current key precedes the accepted original. + // This is not a real signer-rotation or publication proof. + var originalKeys = + (List) + AccountControlUiIssuanceRepository.object(originalSnapshot.jwksBytes()) + .get("keys"); + keys.addAll(originalKeys); + } + changed = AccountControlUiAuthority.canonical(java.util.Map.of("keys", keys)); + } + var observedPin = + "UNTRUSTED".equals(keyState) + ? new net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity( + pin.environmentId(), + pin.clusterId(), + pin.clusterIncarnationUid(), + pin.namespace(), + pin.namespaceUid(), + UUID.randomUUID().toString(), + pin.bindingRevision(), + pin.apiServerOrigin(), + pin.servingCaSha256()) + : pin; + var controlledCurrent = + new net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot( + observedPin, changed); + var protectedFailures = new java.util.concurrent.atomic.AtomicInteger(); + if ("SOURCE_FAILURE".equals(keyState)) { + org.mockito.Mockito.doAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + protectedFailures.incrementAndGet(); + throw new IllegalStateException("controlled protected-source transport failure"); + }) + .when(fixture.signerFixture.client) + .observe(); + } + var reads = new java.util.concurrent.atomic.AtomicInteger(); + // Current snapshot membership is an explicit upstream stipulation here; this does not prove + // a production key withdrawal or publication. Original issuance, SQL and Redis remain real. + org.mockito.Mockito.doAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + reads.incrementAndGet(); + if ("SOURCE_FAILURE".equals(keyState) + || "SQL".equals(keyState) + || "SYNCHRONIZATION".equals(keyState)) { + return invocation.callRealMethod(); + } + return controlledCurrent; + }) + .when(fixture.publicSource) + .load(); + var callback = new AtomicBoolean(); + java.util.function.Supplier action = + () -> { + if (signedCredential) { + return issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + } + return issued + .actors() + .withCurrentCommitted( + f.account.getAccountUuid(), + f.tenant, + jti, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + }; + Throwable failure = + catchThrowable( + () -> { + if ("SQL".equals(keyState)) { + f.tx(action::get); + } else if ("SYNCHRONIZATION".equals(keyState)) { + org.springframework.transaction.support.TransactionSynchronizationManager + .initSynchronization(); + try { + action.get(); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager + .clearSynchronization(); + } + } else { + action.get(); + } + }); + var after = + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_hash=?", + tokenHash)); + assertThat(after.get("payload", String.class)) + .isEqualTo(original.get("payload", String.class)); + assertThat(after.get("row_version", String.class)) + .isEqualTo(original.get("row_version", String.class)); + assertThat(callback.get()).isEqualTo("RETAINED".equals(keyState)); + if ("RETAINED".equals(keyState)) { + assertThat(failure).isNull(); + } else { + assertThat(failure).isInstanceOf(RuntimeException.class); + } + if ("SQL".equals(keyState) || "SYNCHRONIZATION".equals(keyState)) { + assertThat(reads.get()).isZero(); + } else { + assertThat(reads.get()).isGreaterThanOrEqualTo(1); + } + if ("SOURCE_FAILURE".equals(keyState)) { + assertThat(protectedFailures.get()).isGreaterThanOrEqualTo(1); + } + } + } + @Test void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrSubstitute() throws Exception { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java index 196f0f5945..19826e2a31 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java @@ -421,6 +421,13 @@ void owner(String compact) { AccountControlUiAuthority.canonical( Map.ofEntries( Map.entry("kid", "test-only-control"), + Map.entry( + "publicKeyFingerprint", + AccountJwtJwksTrustedSource.publicKeyFingerprint( + new AccountPublicJwksCache.PublicJwksSnapshot(pin, jwks), + pin, + "test-only-control") + .orElseThrow()), Map.entry("environmentId", pin.environmentId()), Map.entry("clusterId", pin.clusterId()), Map.entry("clusterIncarnationUid", pin.clusterIncarnationUid()), diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index a9bdc9d9ff..bd43e21388 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -35,6 +35,8 @@ public final class AccountControlUiOriginalOrderFixture implements AutoCloseable { private final AccountControlUiOwnerSourcesFixture f; private final AccountControlUiActorService actors; + final AccountJwtJwksTrustedSource publicSource; + final AccountControlUiSignerFixture signerFixture; private final AccountControlUiIssuanceService issuance; private final AccountControlUiCoordination coordination; private final RedisClient accountClient; @@ -113,7 +115,8 @@ public AccountControlUiOriginalOrderFixture( f = new AccountControlUiOwnerSourcesFixture( jdbcUrl, username, password, temporary, false, gameDesignTenant, migrationTarget); - var lifecycle = new AccountControlUiSignerFixture(f, temporary); + signerFixture = new AccountControlUiSignerFixture(f, temporary); + var lifecycle = signerFixture; lifecycle.commit(); var originalSigner = f.tx(lifecycle.signer::captureCurrent); assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) @@ -174,9 +177,14 @@ public AccountControlUiOriginalOrderFixture( new AcknowledgementRequirements(1, 1, 5000), testCatalog()); var operations = new AccountControlUiIssuanceRepository(f.dsl); - var publicSource = - new AccountJwtJwksTrustedSource( - lifecycle.client, lifecycle.trust, lifecycle.desired, lifecycle.publication, f.manager); + publicSource = + org.mockito.Mockito.spy( + new AccountJwtJwksTrustedSource( + lifecycle.client, + lifecycle.trust, + lifecycle.desired, + lifecycle.publication, + f.manager)); actors = new AccountControlUiActorService( operations, diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java index d296be3853..6f4c7637b8 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java @@ -478,7 +478,7 @@ public void onCompleted() { return java.util.Objects.requireNonNull(result.get()); } - private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} private static Instant now() { return Instant.ofEpochSecond(Instant.now().getEpochSecond()); @@ -519,7 +519,7 @@ private static String privateBundleJson( return JSON.writeValueAsString(bundle); } - private static PublicJwk publicJwk(String kid, RSAPublicKey key) throws Exception { + static PublicJwk publicJwk(String kid, RSAPublicKey key) throws Exception { String modulus = encodeUnsigned(key.getModulus()); String exponent = encodeUnsigned(key.getPublicExponent()); Map jwk = new LinkedHashMap<>(); From 58a580c44c9aa58d9ff133683681922a983ce714 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:00:29 +1300 Subject: [PATCH 32/61] Bind selected publication mechanics fixtures to the selected digest collector --- ...emptServiceTransactionIntegrationTest.java | 45 ++++++++++++++++--- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index b6e370c341..20a879edd7 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -558,9 +558,20 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { AtomicInteger artifactReadbackCount = new AtomicInteger(); Mockito.when( - publishGateService.collectFullVersionParticipantDigests( + publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq(publishRequestId), + Mockito.eq( + PublicationDigestRequestBinding.full( + fixture + .operation() + .account() + .input() + .selection() + .intent() + .canonicalTenantId() + .toString(), + String.valueOf(fixture.version().getId()), + publishRequestId)), Mockito.eq(publishWorkflowId))) .thenAnswer( invocation -> { @@ -682,9 +693,20 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate AtomicBoolean finalizationFailureInjected = new AtomicBoolean(); Mockito.when( - publishGateService.collectFullVersionParticipantDigests( + publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq(publishRequestId), + Mockito.eq( + PublicationDigestRequestBinding.full( + fixture + .operation() + .account() + .input() + .selection() + .intent() + .canonicalTenantId() + .toString(), + String.valueOf(fixture.version().getId()), + publishRequestId)), Mockito.eq(publishWorkflowId))) .thenAnswer( invocation -> { @@ -851,9 +873,20 @@ void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() { AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); Mockito.when( - publishGateService.collectFullVersionParticipantDigests( + publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq(publishRequestId), + Mockito.eq( + PublicationDigestRequestBinding.full( + fixture + .operation() + .account() + .input() + .selection() + .intent() + .canonicalTenantId() + .toString(), + String.valueOf(fixture.version().getId()), + publishRequestId)), Mockito.eq(publishWorkflowId))) .thenAnswer( invocation -> { From 04a4d8ae605137123ca0acb3b712dcf38b89612e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:08:46 +1300 Subject: [PATCH 33/61] Match canonical digest binding values and selected-full fixture schemas --- ...emptServiceTransactionIntegrationTest.java | 108 +++++++++++------- 1 file changed, 69 insertions(+), 39 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 20a879edd7..c47a08e41b 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -553,6 +553,18 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { String publishRequestId = fixture.operation().account().input().selection().intent().publishRequestId(); String publishWorkflowId = fixture.operation().workflowId(); + PublicationDigestRequestBinding expectedBinding = + PublicationDigestRequestBinding.full( + fixture + .operation() + .account() + .input() + .selection() + .intent() + .canonicalTenantId() + .toString(), + String.valueOf(fixture.version().getId()), + publishRequestId); ExportedAssetManifest candidate = recordFixtureCandidate(fixture); AtomicReference recordedDigestFailure = new AtomicReference<>(); AtomicInteger artifactReadbackCount = new AtomicInteger(); @@ -560,18 +572,16 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { Mockito.when( publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq( - PublicationDigestRequestBinding.full( - fixture - .operation() - .account() - .input() - .selection() - .intent() - .canonicalTenantId() - .toString(), - String.valueOf(fixture.version().getId()), - publishRequestId)), + Mockito.argThat( + binding -> + binding != null + && binding + .canonicalPreimageHex() + .equals(expectedBinding.canonicalPreimageHex()) + && binding.requestDigest().equals(expectedBinding.requestDigest()) + && binding + .derivedWorkflowIdentity() + .equals(expectedBinding.derivedWorkflowIdentity())), Mockito.eq(publishWorkflowId))) .thenAnswer( invocation -> { @@ -579,7 +589,7 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { return PublishedWorldSelectorFixtures.participants( selectedVersion.id(), fixture.operation().world(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); }); Mockito.doAnswer( invocation -> { @@ -678,6 +688,18 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate String publishRequestId = fixture.operation().account().input().selection().intent().publishRequestId(); String publishWorkflowId = fixture.operation().workflowId(); + PublicationDigestRequestBinding expectedBinding = + PublicationDigestRequestBinding.full( + fixture + .operation() + .account() + .input() + .selection() + .intent() + .canonicalTenantId() + .toString(), + String.valueOf(fixture.version().getId()), + publishRequestId); Version sourceVersion = versionRepository.findByTenantIdAndVersionNumber(tenantId, 1).orElseThrow(); long sourceVersionId = sourceVersion.getId(); @@ -695,18 +717,16 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate Mockito.when( publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq( - PublicationDigestRequestBinding.full( - fixture - .operation() - .account() - .input() - .selection() - .intent() - .canonicalTenantId() - .toString(), - String.valueOf(fixture.version().getId()), - publishRequestId)), + Mockito.argThat( + binding -> + binding != null + && binding + .canonicalPreimageHex() + .equals(expectedBinding.canonicalPreimageHex()) + && binding.requestDigest().equals(expectedBinding.requestDigest()) + && binding + .derivedWorkflowIdentity() + .equals(expectedBinding.derivedWorkflowIdentity())), Mockito.eq(publishWorkflowId))) .thenAnswer( invocation -> { @@ -716,7 +736,7 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate return PublishedWorldSelectorFixtures.participants( candidate.id(), fixture.operation().world(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); }); Mockito.doAnswer( invocation -> { @@ -870,23 +890,33 @@ void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() { String publishRequestId = fixture.operation().account().input().selection().intent().publishRequestId(); String publishWorkflowId = fixture.operation().workflowId(); + PublicationDigestRequestBinding expectedBinding = + PublicationDigestRequestBinding.full( + fixture + .operation() + .account() + .input() + .selection() + .intent() + .canonicalTenantId() + .toString(), + String.valueOf(fixture.version().getId()), + publishRequestId); AtomicReference controlPlaneDigestFailure = captureControlPlaneDigestFailure(); Mockito.when( publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq( - PublicationDigestRequestBinding.full( - fixture - .operation() - .account() - .input() - .selection() - .intent() - .canonicalTenantId() - .toString(), - String.valueOf(fixture.version().getId()), - publishRequestId)), + Mockito.argThat( + binding -> + binding != null + && binding + .canonicalPreimageHex() + .equals(expectedBinding.canonicalPreimageHex()) + && binding.requestDigest().equals(expectedBinding.requestDigest()) + && binding + .derivedWorkflowIdentity() + .equals(expectedBinding.derivedWorkflowIdentity())), Mockito.eq(publishWorkflowId))) .thenAnswer( invocation -> { @@ -894,7 +924,7 @@ void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() { return PublishedWorldSelectorFixtures.participants( version.id(), fixture.operation().world(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); }); Mockito.when(assetExportService.exportAssets(tenantId, fixture.version().getVersionNumber())) .thenAnswer(invocation -> recordFixtureCandidate(fixture)); From 0b84543bc63ca3154bef08efa9f4fa26b259d39d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:19:53 +1300 Subject: [PATCH 34/61] Bound activation receiver PKI fixture child waits --- design/project-management/ai-observations.md | 5 + .../player-access-and-session.md | 6 + ...tionProtectionAcquisitionGrpcMtlsTest.java | 132 ++++++++++++++++-- ...ldParticipationSettlementGrpcMtlsTest.java | 130 +++++++++++++++-- 4 files changed, 255 insertions(+), 18 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 783265cf66..c4bd6807e4 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -145,3 +145,8 @@ Entry format: - Context: fresh signed and committed-JTI creator callbacks must retain their original key identity. - Observation: an immutable source pin, historical committed-signer receipt and still-fresh signature cache do not independently establish that the original key remains in the current protected public snapshot. - Expected pattern: load the existing trusted source outside SQL and synchronization, compare the original key ID and RFC 7638 fingerprint, preserve accepted retiring-key membership and historical exact recovery, and state the per-invocation snapshot limit beside the proof. + +- `2026-10-16`: Bound child waits in standalone receiver PKI fixtures + - Context: The standalone activation and World participation receiver PKI fixtures had the same output-before-wait pattern, leaving child execution unbounded. + - Observation: Both use the existing purpose-specific bounded-child pattern; four actual stalled-JDK-child timeout/interruption cases and all eight consuming receiver cases pass. + - Expected pattern: Compare each remaining fixture owner independently; an earlier Logging fixture pass does not prove these locations, and controlled socket proof does not establish real Account settlement or genuine PKI. 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 ba71416f8b..fb10137756 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -30,6 +30,12 @@ The existing Account StartSession reservation-evidence client pins the configure The focused source `3357125badc6ad36f6d2e77ea1105685960e86c4` passes ten secured-client cases, two fixture child-process cases, the default-off bean-definition case and the existing Account original-owner PostgreSQL case: fourteen fresh cases with zero failures, errors or skips. Actual loopback mTLS rejects wrong workload, wrong namespace or missing server URI before request delivery; plaintext, missing client credentials, caller context and ambient SQL/synchronization are denied separately. The native owner case uses the actual Logging socket and certificate-derived approved Account leaf; remaining inbound Account and upstream authority contexts stay controlled. Its strict passive observer owns the single run-created PostgreSQL container with the inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container after completion. Affected main, unit, integration and test-fixture static analysis, formatting and documentation checks pass. The test PKI helper now waits within its deadline before reading child output, then terminates and reaps on timeout or interruption while preserving interrupt status; the two new cases prove those paths with actual stalled JDK children. Earlier client/owner passes did not establish this child-process deadline. These controlled component results do not establish genuine creator, issuer, environment or PKI authority, deployed registration, gameplay admission, Entity placement or any genuine handoff. +### Standalone activation receiver test PKI + +The purpose-specific PKI fixtures in the [activation acquisition receiver test](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java) and [World participation settlement receiver test](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java) now redirect child output to an owned temporary file and wait within the execution deadline before reading it. Timeout or interruption terminates and reaps the child within the bounded cleanup wait and preserves interrupt status. The existing activation settlement receiver test consumes the corrected acquisition fixture; the World participation fixture retains its separate ownership. + +At source `7bc64728ded6619058c926e93ee58f693ae440a5`, all twelve selected cases pass freshly with zero failures, errors or skips: four actual stalled-JDK-child timeout/interruption cases and eight controlled-PKI loopback receiver cases across those three suites. Affected unit static analysis and formatting pass. The receivers use mocked Account owners; acquisition and activation settlement exercise authenticated caller access to malformed-request decoding, while World participation reaches its controlled owner lookup or rejects invalid callers. These results do not establish successful real settlement, owner SQL, genuine PKI or upstream authority, runtime registration or a genuine Gameplay handoff. The prior Logging client and native owner proofs retain their separate source attribution. + ### Selected publication owner preparation Activation settlement preserves the canonical source-first lock order: the repository locks exact original source keys in Java canonical order with NOWAIT before locking and rereading the immutable protection row. The focused PostgreSQL refusal fixture controls historical lookup and terminal evidence to exercise only source contention, lock ordering, rollback and absence of settlement effects; it does not prove authenticated terminal production or a complete Java settlement write/readback. diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java index ca82712955..958983eb68 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java @@ -42,6 +42,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.test.TlsTestSupport; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; /** Controlled loopback PKI proves only the standalone receiver's mTLS caller boundary. */ @@ -49,6 +50,76 @@ class AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest { private static final String NAMESPACE = "world-runtime"; @TempDir Path temporaryDirectory; + @Test + @Timeout(15) + void keytoolTimeoutTerminatesAndReapsTheStalledChild() throws Exception { + Process process = keytoolAwaitingPassword(); + try { + assertThatThrownBy( + () -> + ActivationProtectionGrpcMtlsTestSupport.TestPki.awaitKeytoolExit( + process, 1, TimeUnit.SECONDS)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("execution deadline"); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + cleanupKeytool(process); + } + } + + @Test + @Timeout(15) + void keytoolInterruptionReapsTheChildAndPreservesTheInterruptFlag() throws Exception { + Process process = keytoolAwaitingPassword(); + try { + Thread.currentThread().interrupt(); + assertThatThrownBy( + () -> + ActivationProtectionGrpcMtlsTestSupport.TestPki.awaitKeytoolExit( + process, 30, TimeUnit.SECONDS)) + .isInstanceOf(InterruptedException.class); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + Thread.interrupted(); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + Thread.interrupted(); + cleanupKeytool(process); + } + } + + private Process keytoolAwaitingPassword() throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + return new ProcessBuilder( + keytool.toString(), + "-genkeypair", + "-alias", + "controlled-timeout", + "-keyalg", + "RSA", + "-keystore", + temporaryDirectory.resolve("pending-password.p12").toString(), + "-storetype", + "PKCS12") + .redirectErrorStream(true) + .start(); + } + + private static void cleanupKeytool(Process process) throws Exception { + if (process.isAlive()) process.destroyForcibly(); + assertThat(process.waitFor(5, TimeUnit.SECONDS)).isTrue(); + process.getOutputStream().close(); + process.getInputStream().close(); + process.getErrorStream().close(); + } + @Test void onlyExactSameNamespaceWorldCertificateReachesMalformedRequestDecoder() throws Exception { var pki = ActivationProtectionGrpcMtlsTestSupport.TestPki.create(temporaryDirectory); @@ -203,6 +274,7 @@ private TestPki( static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("activation-test-ca.p12"); runKeytool( + directory, "-genkeypair", "-alias", "activation-test-ca", @@ -228,6 +300,7 @@ static TestPki create(Path directory) throws Exception { PASSWORD); Path caFile = directory.resolve("activation-test-ca.crt"); runKeytool( + directory, "-exportcert", "-alias", "activation-test-ca", @@ -321,6 +394,7 @@ private static Identity issue( String san = server ? "URI:" + uri + ",DNS:localhost,IP:127.0.0.1" : "URI:" + uri; String usage = server ? "serverAuth" : "clientAuth"; runKeytool( + directory, "-genkeypair", "-alias", alias, @@ -347,6 +421,7 @@ private static Identity issue( "-keypass", PASSWORD); runKeytool( + directory, "-certreq", "-alias", alias, @@ -361,6 +436,7 @@ private static Identity issue( "-ext", "SAN=" + san); runKeytool( + directory, "-gencert", "-alias", "activation-test-ca", @@ -386,6 +462,7 @@ private static Identity issue( "-ext", "SAN=" + san); runKeytool( + directory, "-importcert", "-alias", "activation-test-ca", @@ -399,6 +476,7 @@ private static Identity issue( caFile.toString(), "-noprompt"); runKeytool( + directory, "-importcert", "-alias", alias, @@ -421,7 +499,7 @@ private static Identity issue( (X509Certificate) keyStore.getCertificate(alias)); } - private static void runKeytool(String... args) throws Exception { + private static void runKeytool(Path directory, String... args) throws Exception { Path keytool = Path.of( System.getProperty("java.home"), @@ -432,14 +510,52 @@ private static void runKeytool(String... args) throws Exception { ArrayList command = new ArrayList<>(); command.add(keytool.toString()); command.addAll(List.of(args)); - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); - String output; - try (var stream = process.getInputStream()) { - output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + Path output = Files.createTempFile(directory, "keytool-output-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(output.toFile()) + .start(); + awaitKeytoolExit(process, 30, TimeUnit.SECONDS); + if (process.exitValue() != 0) { + throw new IllegalStateException("test keytool failed: " + Files.readString(output)); + } + } finally { + Files.deleteIfExists(output); } - if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { - process.destroyForcibly(); - throw new IllegalStateException("test keytool failed: " + output); + } + + /** Waits before reading child output, then terminates and reaps on timeout or interruption. */ + static void awaitKeytoolExit(Process process, long timeout, TimeUnit unit) + throws InterruptedException { + try { + if (!process.waitFor(timeout, unit)) { + throw new IllegalStateException("test keytool exceeded its execution deadline"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } finally { + boolean restoreInterrupt = Thread.interrupted(); + try { + if (process.isAlive()) process.destroyForcibly(); + long cleanupDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + boolean reaped = false; + while (!reaped) { + long remaining = cleanupDeadline - System.nanoTime(); + if (remaining <= 0) { + throw new IllegalStateException("test keytool could not be reaped after termination"); + } + try { + reaped = process.waitFor(remaining, TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + restoreInterrupt = true; + } + } + } finally { + if (restoreInterrupt) Thread.currentThread().interrupt(); + } } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java index a1cca68f6d..9b2d8c5a80 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java @@ -50,6 +50,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -78,6 +79,70 @@ void clearThreadState() { TransactionSynchronizationManager.clear(); } + @Test + @Timeout(15) + void keytoolTimeoutTerminatesAndReapsTheStalledChild() throws Exception { + Process process = keytoolAwaitingPassword(); + try { + assertThatThrownBy(() -> TestPki.awaitKeytoolExit(process, 1, TimeUnit.SECONDS)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("execution deadline"); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + cleanupKeytool(process); + } + } + + @Test + @Timeout(15) + void keytoolInterruptionReapsTheChildAndPreservesTheInterruptFlag() throws Exception { + Process process = keytoolAwaitingPassword(); + try { + Thread.currentThread().interrupt(); + assertThatThrownBy(() -> TestPki.awaitKeytoolExit(process, 30, TimeUnit.SECONDS)) + .isInstanceOf(InterruptedException.class); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + Thread.interrupted(); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + Thread.interrupted(); + cleanupKeytool(process); + } + } + + private Process keytoolAwaitingPassword() throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + return new ProcessBuilder( + keytool.toString(), + "-genkeypair", + "-alias", + "controlled-timeout", + "-keyalg", + "RSA", + "-keystore", + temporaryDirectory.resolve("pending-password.p12").toString(), + "-storetype", + "PKCS12") + .redirectErrorStream(true) + .start(); + } + + private static void cleanupKeytool(Process process) throws Exception { + if (process.isAlive()) process.destroyForcibly(); + assertThat(process.waitFor(5, TimeUnit.SECONDS)).isTrue(); + process.getOutputStream().close(); + process.getInputStream().close(); + process.getErrorStream().close(); + } + @Test void exactWorldClientReachesReceiverAndPassesOnlyTheRetainedLookupToOwner() throws Exception { var owner = mock(AccountStartSessionWorldParticipationSettlementService.class); @@ -294,6 +359,7 @@ private record TestPki( private static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("world-participation-settlement-test-ca.p12"); runKeytool( + directory, "-genkeypair", "-alias", "world-participation-settlement-ca", @@ -319,6 +385,7 @@ private static TestPki create(Path directory) throws Exception { STORE_PASSWORD); Path caFile = directory.resolve("world-participation-settlement-test-ca.crt"); runKeytool( + directory, "-exportcert", "-alias", "world-participation-settlement-ca", @@ -394,6 +461,7 @@ private static TestIdentity issueIdentity( String san = "URI:" + workloadUri + (server ? ",DNS:localhost,IP:127.0.0.1" : ""); String usage = server ? "serverAuth" : "clientAuth"; runKeytool( + directory, "-genkeypair", "-alias", alias, @@ -420,6 +488,7 @@ private static TestIdentity issueIdentity( "-keypass", STORE_PASSWORD); runKeytool( + directory, "-certreq", "-alias", alias, @@ -434,6 +503,7 @@ private static TestIdentity issueIdentity( "-ext", "SAN=" + san); runKeytool( + directory, "-gencert", "-alias", "world-participation-settlement-ca", @@ -459,6 +529,7 @@ private static TestIdentity issueIdentity( "-ext", "SAN=" + san); runKeytool( + directory, "-importcert", "-alias", "world-participation-settlement-ca", @@ -472,6 +543,7 @@ private static TestIdentity issueIdentity( caFile.toString(), "-noprompt"); runKeytool( + directory, "-importcert", "-alias", alias, @@ -494,7 +566,7 @@ private static TestIdentity issueIdentity( (X509Certificate) keyStore.getCertificate(alias)); } - private static void runKeytool(String... arguments) throws Exception { + private static void runKeytool(Path directory, String... args) throws Exception { Path keytool = Path.of( System.getProperty("java.home"), @@ -502,17 +574,55 @@ private static void runKeytool(String... arguments) throws Exception { System.getProperty("os.name").toLowerCase().contains("windows") ? "keytool.exe" : "keytool"); - var command = new ArrayList(); + ArrayList command = new ArrayList<>(); command.add(keytool.toString()); - command.addAll(List.of(arguments)); - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); - String output; - try (var stream = process.getInputStream()) { - output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + command.addAll(List.of(args)); + Path output = Files.createTempFile(directory, "keytool-output-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(output.toFile()) + .start(); + awaitKeytoolExit(process, 30, TimeUnit.SECONDS); + if (process.exitValue() != 0) { + throw new IllegalStateException("test keytool failed: " + Files.readString(output)); + } + } finally { + Files.deleteIfExists(output); } - if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { - process.destroyForcibly(); - throw new IllegalStateException("test keytool failed: " + output); + } + + /** Waits before reading child output, then terminates and reaps on timeout or interruption. */ + static void awaitKeytoolExit(Process process, long timeout, TimeUnit unit) + throws InterruptedException { + try { + if (!process.waitFor(timeout, unit)) { + throw new IllegalStateException("test keytool exceeded its execution deadline"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } finally { + boolean restoreInterrupt = Thread.interrupted(); + try { + if (process.isAlive()) process.destroyForcibly(); + long cleanupDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + boolean reaped = false; + while (!reaped) { + long remaining = cleanupDeadline - System.nanoTime(); + if (remaining <= 0) { + throw new IllegalStateException("test keytool could not be reaped after termination"); + } + try { + reaped = process.waitFor(remaining, TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + restoreInterrupt = true; + } + } + } finally { + if (restoreInterrupt) Thread.currentThread().interrupt(); + } } } From fa4c3ab3ab6bea8a6645371327321b08bf61bafe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:24:58 +1300 Subject: [PATCH 35/61] Converge selected-full mechanics fixtures and time settlement response stages --- .../draft/IsolatedPublicationOwnerSetup.java | 51 ++++++++- .../IsolatedPublicationOperationFixtures.java | 41 ++++++- .../impl/PublishedWorldSelectorFixtures.java | 20 +++- ...nerPublicationPostgresIntegrationTest.java | 105 +++++++++++++++++- ...emptServiceTransactionIntegrationTest.java | 10 +- 5 files changed, 205 insertions(+), 22 deletions(-) diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index b135d2b0bd..f564110d45 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -137,6 +137,24 @@ public static GameDesignPublicationOperation retainFrozenSourceBacked( return operation; } + /** + * Isolated GDS transaction fixture with a fresh stipulated selected-full World schema-4 input. + * The World evidence remains stipulated and is not native producer or freeze proof. + */ + public static GameDesignPublicationOperation retainFrozenSourceBackedSelectedFull( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + List ordinaryAssets) + throws Exception { + String authoredPolicyCommit = retainPublicProductionPolicy(dsl, target, ordinaryAssets); + GameDesignPublicationOperation operation = + retain(dsl, target, draftEpoch, notes, true, authoredPolicyCommit, false, true); + new GameDesignPublicationOperationRepository(dsl).reserveSourceBacked(operation); + return operation; + } + /** Fixture input from an actual same-tenant game_assets row, not publication authority. */ public record OrdinaryAsset(long assetRowId, String usageKey) { public OrdinaryAsset { @@ -176,6 +194,20 @@ private static GameDesignPublicationOperation retain( String sourceBaseReference, boolean historicalV1) throws Exception { + return retain( + dsl, target, draftEpoch, notes, captureSources, sourceBaseReference, historicalV1, false); + } + + private static GameDesignPublicationOperation retain( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + boolean captureSources, + String sourceBaseReference, + boolean historicalV1, + boolean selectedFullWorld) + throws Exception { var sources = new GameDesignSourceRepository(dsl); var reviewed = new GameDesignReviewedBaseRepository(dsl); var evidence = @@ -189,10 +221,14 @@ private static GameDesignPublicationOperation retain( : sourceBaseReference)) : null; var seed = - captureSources - ? IsolatedPublicationOperationFixtures.fresh( + selectedFullWorld + ? IsolatedPublicationOperationFixtures.freshSelectedFull( target, evidence.reference().canonicalValue()) - : IsolatedPublicationOperationFixtures.fresh(target); + : captureSources + ? IsolatedPublicationOperationFixtures.fresh( + target, evidence.reference().canonicalValue()) + : IsolatedPublicationOperationFixtures.fresh(target); + var seedWorld = seed.world(); var draft = seed.account().input().selection().selectedCommit(); var coordinator = new DraftCommitCoordinatorRepository(dsl); // The original Draft Account/World result is stipulated upstream fixture evidence, not a new @@ -222,7 +258,7 @@ private static GameDesignPublicationOperation retain( draft.commitId(), draft.digest(), "ISOLATED-world-applied", - seed.world().appliedResultBytes(), + seedWorld.appliedResultBytes(), epochs); coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.WORLD_MANAGEMENT); coordinator.recordOwnerOutcome(draft, outcome); @@ -253,8 +289,11 @@ private static GameDesignPublicationOperation retain( var operation = historicalV1 ? IsolatedPublicationOperationFixtures.historicalV1ForSelection( - selectedBinding, seed.world()) - : IsolatedPublicationOperationFixtures.forSelection(selectedBinding, seed.world()); + selectedBinding, seedWorld) + : selectedFullWorld + ? IsolatedPublicationOperationFixtures.forSelectedFullSelection( + selectedBinding, seedWorld) + : IsolatedPublicationOperationFixtures.forSelection(selectedBinding, seedWorld); var attempt = new PublishAttempt(); attempt.setTenantId(target.gameDesignVersionTenantKey()); attempt.setPublishWorkflowId(operation.workflowId()); diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java index 0554126103..fbd0bc7c0f 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -10,6 +10,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; @@ -39,9 +40,26 @@ public static GameDesignPublicationOperation fresh( return fresh(target, PublishedWorldSelectorFixtures.evidence(target, baseReference)); } + /** Fresh stipulated selected-full fixture; schema 4 is constructed before operation retention. */ + public static GameDesignPublicationOperation freshSelectedFull( + DraftCommitBinding.TargetProof target, String baseReference) throws Exception { + return fresh( + target, + PublishedWorldSelectorFixtures.selectedFullSeed(target, baseReference), + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + } + private static GameDesignPublicationOperation fresh( DraftCommitBinding.TargetProof target, WorldPublishedStartLocationEvidence seed) throws Exception { + return fresh(target, seed, 3); + } + + private static GameDesignPublicationOperation fresh( + DraftCommitBinding.TargetProof target, + WorldPublishedStartLocationEvidence seed, + int worldDigestSchemaVersion) + throws Exception { var originalDraftAccount = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); var draft = @@ -110,12 +128,23 @@ private static GameDesignPublicationOperation fresh( draft.digest(), vector, OffsetDateTime.parse("2026-10-07T00:00:00Z"))); - return forSelection(selected, seed); + return selection(selected, seed, false, worldDigestSchemaVersion); } public static GameDesignPublicationOperation forSelection( AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { - return selection(selected, seed, false); + return selection( + selected, seed, false, 3); + } + + /** Builds a fresh selected-full operation without reinterpreting retained schema-3 history. */ + public static GameDesignPublicationOperation forSelectedFullSelection( + AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { + return selection( + selected, + seed, + false, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); } /** @@ -124,13 +153,15 @@ public static GameDesignPublicationOperation forSelection( */ public static GameDesignPublicationOperation historicalV1ForSelection( AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { - return selection(selected, seed, true); + return selection( + selected, seed, true, 3); } private static GameDesignPublicationOperation selection( AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed, - boolean historicalV1) { + boolean historicalV1, + int worldDigestSchemaVersion) { var originalDraftAccount = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); var target = selected.target(); @@ -181,7 +212,7 @@ private static GameDesignPublicationOperation selection( intent.publishRequestId()), draft.commitId().toString(), seed.request().contentDigest(), - 3, + worldDigestSchemaVersion, seed.request().worldAffectedTuples()), seed.selectorReceiptBytes(), seed.originalAccountBindingBytes(), diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java index 277640b137..84c1cd3b26 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -43,6 +43,19 @@ public static WorldPublishedStartLocationEvidence evidence(TargetProof target) t return new PublishedWorldSelectorFixtures(target).build(); } + /** + * Stipulated fresh selected-full World input; schema 4 is present from its first construction. + * This fixture does not claim that a live World producer computed or authorized the evidence. + */ + public static WorldPublishedStartLocationEvidence selectedFullSeed( + TargetProof target, String baseReference) throws Exception { + net.firedevops.firemud.common.authoring.DraftBaseReference.parse(baseReference); + var fixture = new PublishedWorldSelectorFixtures(target, baseReference); + return fixture.build( + fixture.freshGraphBinding(), + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + } + public static WorldPublishedStartLocationEvidence evidence( TargetProof target, String baseReference) throws Exception { net.firedevops.firemud.common.authoring.DraftBaseReference.parse(baseReference); @@ -117,6 +130,11 @@ private WorldPublishedStartLocationEvidence build() throws Exception { } private WorldPublishedStartLocationEvidence build(DraftCommitBinding draft) throws Exception { + return build(draft, 3); + } + + private WorldPublishedStartLocationEvidence build( + DraftCommitBinding draft, int attestationSchemaVersion) throws Exception { var terminal = WorldDraftTerminalReadEvidence.Request.create("test", accountBinding(draft)); var result = committedReadback(terminal, true); var applied = JSON.readTree(result.result()); @@ -152,7 +170,7 @@ private WorldPublishedStartLocationEvidence build(DraftCommitBinding draft) thro "publish-workflow", draft.commitId().toString(), "b".repeat(64), - 3, + attestationSchemaVersion, tuples); return new WorldPublishedStartLocationEvidence( request, diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 530e5001a8..c0ee5af5ce 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -1854,20 +1854,22 @@ private static String loopback(Server server) { private static final class SettlementDiagnostics { private final AtomicLong sequence = new AtomicLong(); + private final long diagnosticOriginNanos = System.nanoTime(); void logPostgres(String role, PostgreSQLContainer postgres) { try { System.out.printf( - "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s container=%s host=%s mapped_port=%d running=%s%n", + "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s elapsed_since_diagnostic_start_nanos=%d container=%s host=%s mapped_port=%d running=%s%n", role, + System.nanoTime() - diagnosticOriginNanos, postgres.getContainerId(), postgres.getHost(), postgres.getMappedPort(5432), postgres.isRunning()); } catch (RuntimeException unavailable) { System.out.printf( - "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s status=unavailable error=%s%n", - role, unavailable.getClass().getSimpleName()); + "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s elapsed_since_diagnostic_start_nanos=%d status=unavailable error=%s%n", + role, System.nanoTime() - diagnosticOriginNanos, unavailable.getClass().getSimpleName()); } } @@ -1902,6 +1904,43 @@ public io.grpc.ServerCall.Listener interceptCall var recorded = new java.util.concurrent.atomic.AtomicBoolean(); var timedCall = new io.grpc.ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(ResponseT message) { + long sendStarted = System.nanoTime(); + String serializedSize = serializedSize(message); + event( + callSequence, + stage + "/" + method, + "send-message-before", + sendStarted - started, + serializedSize); + try { + super.sendMessage(message); + long sendFinished = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "send-message-after", + sendFinished - started, + serializedSize + + ",delegate_elapsed_nanos=" + + (sendFinished - sendStarted)); + } catch (RuntimeException | Error failure) { + long sendFailed = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "send-message-failed", + sendFailed - started, + serializedSize + + ",delegate_elapsed_nanos=" + + (sendFailed - sendStarted) + + ",failure=" + + failure.getClass().getSimpleName()); + throw failure; + } + } + @Override public void close(io.grpc.Status status, io.grpc.Metadata trailers) { if (recorded.compareAndSet(false, true)) { @@ -1919,6 +1958,50 @@ public void close(io.grpc.Status status, io.grpc.Metadata trailers) { var listener = next.startCall(timedCall, headers); return new io.grpc.ForwardingServerCallListener .SimpleForwardingServerCallListener<>(listener) { + @Override + public void onMessage(RequestT message) { + event( + callSequence, + stage + "/" + method, + "request-message", + System.nanoTime() - started, + serializedSize(message)); + super.onMessage(message); + } + + @Override + public void onHalfClose() { + long handlerStarted = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "handler-enter", + handlerStarted - started, + "ENTERED"); + try { + super.onHalfClose(); + long handlerFinished = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "handler-return", + handlerFinished - started, + "handler_elapsed_nanos=" + (handlerFinished - handlerStarted)); + } catch (RuntimeException | Error failure) { + long handlerFailed = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "handler-failed", + handlerFailed - started, + "handler_elapsed_nanos=" + + (handlerFailed - handlerStarted) + + ",failure=" + + failure.getClass().getSimpleName()); + throw failure; + } + } + @Override public void onCancel() { if (recorded.compareAndSet(false, true)) { @@ -2008,10 +2091,22 @@ private void finish(TransactionStatus status, boolean commit) { }; } + private String serializedSize(Object message) { + if (message instanceof com.google.protobuf.MessageLite protobufMessage) { + try { + return "serialized_size_bytes=" + protobufMessage.getSerializedSize(); + } catch (RuntimeException unavailable) { + return "serialized_size_bytes=unavailable"; + } + } + return "serialized_size_bytes=unavailable"; + } + private void event(long call, String stage, String event, long elapsedNanos, String result) { + long elapsedSinceDiagnosticStartNanos = System.nanoTime() - diagnosticOriginNanos; System.out.printf( - "SETTLEMENT_DIAGNOSTIC call=%d stage=%s event=%s elapsed_nanos=%d result=%s%n", - call, stage, event, elapsedNanos, result); + "SETTLEMENT_DIAGNOSTIC call=%d stage=%s event=%s elapsed_nanos=%d elapsed_since_diagnostic_start_nanos=%d result=%s%n", + call, stage, event, elapsedNanos, elapsedSinceDiagnosticStartNanos, result); } private record TransactionTiming(long sequence, long startedNanos) {} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index c47a08e41b..da406ce34f 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -549,7 +549,7 @@ void scriptPatchFinalizationFailureRollsBackToRetainedDraftAndMarksAttemptFailed void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { String tenantId = isolatedTenantId(); SelectedPublicationFixture fixture = - selectedPublicationFixture(tenantId, "pending-readback-proof-game", false); + selectedFullPublicationFixture(tenantId, "pending-readback-proof-game", false); String publishRequestId = fixture.operation().account().input().selection().intent().publishRequestId(); String publishWorkflowId = fixture.operation().workflowId(); @@ -684,7 +684,7 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidateAndRemap() { String tenantId = isolatedTenantId(); SelectedPublicationFixture fixture = - selectedPublicationFixture(tenantId, "failed-remap-proof-game", true); + selectedFullPublicationFixture(tenantId, "failed-remap-proof-game", true); String publishRequestId = fixture.operation().account().input().selection().intent().publishRequestId(); String publishWorkflowId = fixture.operation().workflowId(); @@ -886,7 +886,7 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() { String tenantId = "9002"; SelectedPublicationFixture fixture = - selectedPublicationFixture(tenantId, "successful-transaction-proof-game", false); + selectedFullPublicationFixture(tenantId, "successful-transaction-proof-game", false); String publishRequestId = fixture.operation().account().input().selection().intent().publishRequestId(); String publishWorkflowId = fixture.operation().workflowId(); @@ -1037,7 +1037,7 @@ void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() { } /** Fixture-only Account/World inputs; this exercises GD's actual selected owner transaction. */ - private SelectedPublicationFixture selectedPublicationFixture( + private SelectedPublicationFixture selectedFullPublicationFixture( String tenantId, String gameName, boolean includePublishedSource) { TransactionTemplate sourceTransaction = new TransactionTemplate(transactionManager); sourceTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); @@ -1082,7 +1082,7 @@ private SelectedPublicationFixture selectedPublicationFixture( GameAsset persistedAsset = gameAssetRepository.save(asset); try { GameDesignPublicationOperation operation = - IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( + IsolatedPublicationOwnerSetup.retainFrozenSourceBackedSelectedFull( dsl, target, persisted.getVersionStateEpoch(), From e12f130b5c7b9c2c5259c52486cbce3a9e92b6a1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:30:35 +1300 Subject: [PATCH 36/61] Apply canonical selected-publication test formatting --- .../publication/IsolatedPublicationOperationFixtures.java | 6 ++---- ...SelectedFullOwnerPublicationPostgresIntegrationTest.java | 4 +++- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java index fbd0bc7c0f..98a856ff30 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -133,8 +133,7 @@ private static GameDesignPublicationOperation fresh( public static GameDesignPublicationOperation forSelection( AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { - return selection( - selected, seed, false, 3); + return selection(selected, seed, false, 3); } /** Builds a fresh selected-full operation without reinterpreting retained schema-3 history. */ @@ -153,8 +152,7 @@ public static GameDesignPublicationOperation forSelectedFullSelection( */ public static GameDesignPublicationOperation historicalV1ForSelection( AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { - return selection( - selected, seed, true, 3); + return selection(selected, seed, true, 3); } private static GameDesignPublicationOperation selection( diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index c0ee5af5ce..a69ed969d0 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -1869,7 +1869,9 @@ void logPostgres(String role, PostgreSQLContainer postgres) { } catch (RuntimeException unavailable) { System.out.printf( "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s elapsed_since_diagnostic_start_nanos=%d status=unavailable error=%s%n", - role, System.nanoTime() - diagnosticOriginNanos, unavailable.getClass().getSimpleName()); + role, + System.nanoTime() - diagnosticOriginNanos, + unavailable.getClass().getSimpleName()); } } From cbacfefc6660e92a10fafe30b9cfeaa721981744 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:53:12 +1300 Subject: [PATCH 37/61] Avoid redecoding byte-identical validated publication terminals --- ...countPublicationAuthorizationRepository.java | 9 +++++---- ...tSelectedPublicationSettlementGrpcCodec.java | 1 - ...ectedPublicationSettlementGrpcCodecTest.java | 17 +++++++++++++++++ 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java index ec61455a67..1f326c852d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java @@ -197,18 +197,19 @@ public byte[] settle( requireTransaction(); Objects.requireNonNull(operation, "operation"); Objects.requireNonNull(gameDesign, "gameDesign"); - var world = GameDesignPublicationTerminalEvidence.fromStored(worldTerminalEvidence); + byte[] retainedWorldTerminal = + Objects.requireNonNull(worldTerminalEvidence, "worldTerminalEvidence").clone(); String expectedPhase = gameDesign.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED ? "PUBLISHED" : "ABORTED"; if (!expectedPhase.equals(worldOutcome) || !Arrays.equals(operation.canonicalBytes(), gameDesign.operationBytes()) - || !Arrays.equals(gameDesign.canonicalBytes(), world.canonicalBytes())) { + || !Arrays.equals(gameDesign.canonicalBytes(), retainedWorldTerminal)) { throw new IllegalArgumentException("Exact publication owner outcomes disagree"); } readOriginal(operation.account()); - byte[] receipt = settlementReceipt(operation, gameDesign, worldOutcome, worldTerminalEvidence); + byte[] receipt = settlementReceipt(operation, gameDesign, worldOutcome, retainedWorldTerminal); Record prior = dsl.fetchOne( "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", @@ -231,7 +232,7 @@ public byte[] settle( gameDesign.outcome().name(), gameDesign.canonicalBytes(), worldOutcome, - worldTerminalEvidence, + retainedWorldTerminal, receipt); Record retained = dsl.fetchOne( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java index b911a2b407..22085d2767 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java @@ -122,7 +122,6 @@ private static void validateReceipt(Request request, byte[] receipt) { try { operation = GameDesignPublicationOperationBinding.fromStored(request.originalOperation()); terminal = GameDesignPublicationTerminalEvidence.fromStored(gameDesignTerminalBytes); - GameDesignPublicationTerminalEvidence.fromStored(worldTerminalBytes); } catch (RuntimeException malformed) { throw new IllegalArgumentException( "Account receipt lacks complete canonical publication evidence", malformed); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java index f59a9cb65d..39f7bd3eab 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java @@ -126,6 +126,17 @@ void rejectsChangedRequestEchoUnknownFieldsAndChangedOrNoncanonicalReceiptFrames byte[] wrongTerminal = receipt(operation, changedTerminal, null, null, null, null); byte[] wrongWorldTerminal = receipt(operation, terminal, null, null, null, sameOperationOtherOutcome.canonicalBytes()); + byte[] missingWorldTerminal = receipt(operation, terminal, null, null, null, new byte[0]); + byte[] noncanonicalWorldTerminal = + receipt( + operation, + terminal, + null, + null, + null, + ByteString.copyFrom(terminal.canonicalBytes()) + .concat(ByteString.copyFrom(new byte[] {0})) + .toByteArray()); for (var invalid : List.of( response.toBuilder().setUnknownFields(unknown()).build(), @@ -143,6 +154,12 @@ void rejectsChangedRequestEchoUnknownFieldsAndChangedOrNoncanonicalReceiptFrames response.toBuilder() .setSettlementReceipt(ByteString.copyFrom(wrongWorldTerminal)) .build(), + response.toBuilder() + .setSettlementReceipt(ByteString.copyFrom(missingWorldTerminal)) + .build(), + response.toBuilder() + .setSettlementReceipt(ByteString.copyFrom(noncanonicalWorldTerminal)) + .build(), response.toBuilder() .setSettlementReceipt( response.getSettlementReceipt().concat(ByteString.copyFrom(new byte[] {0}))) From f79477380a930c90496d516c9e48e2b903429055 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 16:44:47 +1300 Subject: [PATCH 38/61] Give positive Account owner proof its own PostgreSQL lifecycle --- .../AccountControlUiPositiveOwnerPostgresIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java index d6d8eea0b4..2736f558c8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -112,7 +112,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest { @Container static final PostgreSQLContainer postgres = - AccountControlUiOwnerWorkflowPostgresIntegrationTest.postgres; + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static final GenericContainer redis = From fc11e3c1a353537c433ea480b3332d0057df3afc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 21:13:38 +1300 Subject: [PATCH 39/61] test(gamedesign): prove selected-full release SQL guards and retries --- ...ame-authoring-publishing-and-activation.md | 6 + ...leaseCanonicalIdentityIntegrationTest.java | 296 ++++++++++++++++++ 2 files changed, 302 insertions(+) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 91ff3907ed..86e79a945f 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -50,6 +50,12 @@ The restored Version identity native owner test preserves the original retained All six native cases freshly pass with zero failures, errors or skips against the canonical PostgreSQL image and owning filesystem migrations. Canonical formatting, style, Integration Checkstyle and SpotBugs pass; passive capture identifies the one run-owned PostgreSQL container and independently confirms its absence after completion. This proves owner-local identity and historical retention mechanics with controlled setup. It does not establish creator or issuer authority, currentness, publication enablement, an immutable production release, activation or a genuine Gameplay handoff. No production, installed migration or registration changes are included. +### Selected-full release profile and exact retry storage proof + +Three further native cases use the current test fixture's schema-4 World input from its first construction, actual Game Design source inheritance, reviewed policy, selection, source captures and local publication storage. Direct SQL rejects an incorrect digest schema independently for each of the five participant owners, without creating a bundle or changing the original Game and Version rows or their row versions. A valid v4 bundle retains its original World and participant bytes on independent read and exact retry; changed generation configuration refuses without changing the complete bundle row or its row version. Two concurrent exact storage calls return the same single retained bundle, followed by another unchanged-row retry. Their start latch establishes submitted calls and outcomes; it does not independently measure precommit blocking. A separate SQL case refuses missing selectors, malformed text or numeric epochs, changed request bindings, missing opaque evidence and empty or changed participants, preserving the original Game and Version rows and their row versions without creating a bundle. The unchanged eligible input then commits through actual SQL and independently reads back its original selector bytes. + +All eight native bundle cases freshly passed on donor code source `2226e1ca6a4929bea9611255dd5d2f84177e6faa`, with zero failures, errors or skips. Canonical formatting, style, Integration Checkstyle and SpotBugs passed; the one passively identified PostgreSQL container was independently absent after completion. This is donor evidence only; receiving qualification on #2967 remains pending. The proof uses stipulated Account, World and other remote participant evidence and a controlled empty-asset candidate. It does not establish a genuine immutable release, authenticated creator or issuer, currentness, public finalizer enablement, activation, settlement or a Gameplay handoff. The three selected-full fixture helpers are already present at their inherited shared-test blobs in this receiver. No production, installed migration or registration changes are included. + ### Selected-full owner publication preparation The source candidate prepares complete selected-owner publication consumption under the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile). It reuses the actual parent World closure producer, adds its full-profile consumer mapping, and composes the selected Game Design digest read/collector with independently retained Entity, Automation and Game Logic receipts. The Game Logic adapter reads the exact retained terminal, selected source and manifest through the existing owner repository and returns both manifest and ability projections; its default Spring composition remains denied. Private selected writer mechanics use the exact canonical selection/request binding and selected gate. Public Game Design fresh/PENDING publication remains denied. Existing Game Design V1020 storage is reused; no Game Design migration is added. diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 5db106da16..43aedd6b50 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -442,6 +442,302 @@ void repositoryNestedTransactionRollsBackWithOuterJooqOwnerTransaction() { assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); } + @Test + void selectedFullV4StorageRejectsMixedProfilesAndExactlyReplaysOriginalBytes() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selected-v4-profile-source"); + Version version = saveVersion(fixture, owner); + var operation = selectedFullOperation(fixture, version); + var json = new tools.jackson.databind.ObjectMapper(); + var participants = + net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures.participants( + version.getId(), operation.world(), 4); + String original = + new String(operation.world().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + var gameBefore = sourceRow(fixture.dsl(), "game", owner.getId()); + var versionBefore = sourceRow(fixture.dsl(), "version", version.getId()); + for (int index = 0; index < participants.size(); index++) { + var mixed = + (tools.jackson.databind.node.ArrayNode) + json.readTree(json.writeValueAsString(participants)); + var participant = participants.get(index); + ((tools.jackson.databind.node.ObjectNode) mixed.get(index)) + .put( + "digestSchemaVersion", + participant.digestSchemaVersion() == 1 ? 2 : participant.digestSchemaVersion() - 1); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, version, operation, original, json.writeValueAsString(mixed))) + .as("mixed storage profile for %s", participant.participantKey()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("selected participant differs from commit/digest/schema"); + assertThat(bundleCount(fixture.dsl())).isZero(); + assertThat(sourceRow(fixture.dsl(), "game", owner.getId())).isEqualTo(gameBefore); + assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); + } + var requested = selectedFullBundle(version, operation.world()); + var saved = + fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> fixture.releaseBundleRepository().save(requested))); + assertThat(saved).isNotNull(); + var tuple = releaseBundleTuple(fixture.dsl(), saved.getId()); + var independent = + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(independent).usingRecursiveComparison().isEqualTo(saved); + assertThat(independent.getWorldPublishedStartLocationEvidenceJson()).isEqualTo(original); + assertThat(independent.getParticipantDigestsJson()) + .isEqualTo(json.writeValueAsString(participants)); + assertThat(fixture.releaseBundleRepository().save(requested)) + .usingRecursiveComparison() + .isEqualTo(saved); + var changed = selectedFullBundle(version, operation.world()); + changed.setGenerationConfigRevision("changed-selected-generation"); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(releaseBundleTuple(fixture.dsl(), saved.getId())).isEqualTo(tuple); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + + @Test + void concurrentExactSelectedFullRetriesCommitOneImmutableBundle() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selected-full-concurrent-source"); + Version version = saveVersion(fixture, owner); + var operation = selectedFullOperation(fixture, version); + var start = new java.util.concurrent.CountDownLatch(1); + try (var executor = java.util.concurrent.Executors.newFixedThreadPool(2)) { + java.util.concurrent.Callable save = + () -> { + start.await(); + return fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> + new PublishedReleaseBundleRepository(fixture.dsl()) + .save(selectedFullBundle(version, operation.world())))); + }; + var first = executor.submit(save); + var second = executor.submit(save); + start.countDown(); + var one = first.get(20, java.util.concurrent.TimeUnit.SECONDS); + var two = second.get(20, java.util.concurrent.TimeUnit.SECONDS); + assertThat(two).usingRecursiveComparison().isEqualTo(one); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + var beforeRetry = releaseBundleTuple(fixture.dsl(), one.getId()); + assertThat( + fixture + .releaseBundleRepository() + .save(selectedFullBundle(version, operation.world()))) + .usingRecursiveComparison() + .isEqualTo(one); + assertThat(releaseBundleTuple(fixture.dsl(), one.getId())).isEqualTo(beforeRetry); + } + } + + @Test + void sqlGuardRejectsMissingAndChangedSelectedFullBindingsWithoutAnyRelease() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selected-full-guard-source"); + Version version = saveVersion(fixture, owner); + var operation = selectedFullOperation(fixture, version); + var json = new tools.jackson.databind.ObjectMapper(); + String original = + new String(operation.world().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + String participants = + json.writeValueAsString( + net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures + .participants(version.getId(), operation.world(), 4)); + var gameBefore = sourceRow(fixture.dsl(), "game", owner.getId()); + var versionBefore = sourceRow(fixture.dsl(), "version", version.getId()); + assertThat(json.readTree(original).path("request").path("versionStateEpoch").isTextual()) + .isTrue(); + assertThatThrownBy(() -> insertRawSelectedFull(fixture, version, operation, null, participants)) + .isInstanceOf(DataAccessException.class); + for (String epoch : java.util.List.of("0", "01", "-1", "9223372036854775808")) { + var changed = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("versionStateEpoch", epoch); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, version, operation, json.writeValueAsString(changed), participants)) + .isInstanceOf(DataAccessException.class); + } + var numericEpoch = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + ((tools.jackson.databind.node.ObjectNode) numericEpoch.get("request")) + .put("versionStateEpoch", 1L); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, + version, + operation, + json.writeValueAsString(numericEpoch), + participants)) + .isInstanceOf(DataAccessException.class); + for (String field : + java.util.List.of( + "canonicalTenantId", + "canonicalVersionId", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "intakeRequestId")) { + var changed = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + var request = (tools.jackson.databind.node.ObjectNode) changed.get("request"); + if (field.equals("digestSchemaVersion")) request.put(field, 3); + else request.put(field, field.endsWith("Id") ? UUID.randomUUID().toString() : "changed"); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, version, operation, json.writeValueAsString(changed), participants)) + .isInstanceOf(DataAccessException.class); + } + for (String field : + java.util.List.of( + "selectorReceiptBytesBase64", + "originalAccountBindingBytesBase64", + "appliedResultBytesBase64")) { + var changed = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + changed.remove(field); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, version, operation, json.writeValueAsString(changed), participants)) + .isInstanceOf(DataAccessException.class); + } + assertThatThrownBy(() -> insertRawSelectedFull(fixture, version, operation, original, "[]")) + .isInstanceOf(DataAccessException.class); + var changedParticipants = (tools.jackson.databind.node.ArrayNode) json.readTree(participants); + ((tools.jackson.databind.node.ObjectNode) changedParticipants.get(0)) + .put("contentDigest", "c".repeat(64)); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, + version, + operation, + original, + json.writeValueAsString(changedParticipants))) + .isInstanceOf(DataAccessException.class); + assertThat(bundleCount(fixture.dsl())).isZero(); + assertThat(sourceRow(fixture.dsl(), "game", owner.getId())).isEqualTo(gameBefore); + assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); + fixture + .transactionTemplate() + .executeWithoutResult( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> { + insertRawSelectedFull(fixture, version, operation, original, participants); + return fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow(); + })); + assertThat( + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow() + .getWorldPublishedStartLocationEvidenceJson()) + .isEqualTo(original); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + + /** Actual GDS owner selection/captures with explicitly stipulated remote Account/World input. */ + private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation + selectedFullOperation(Fixture fixture, Version version) { + var target = + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + return fixture + .transactionTemplate() + .execute( + status -> { + try { + return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .retainFrozenSourceBackedSelectedFull( + fixture.dsl(), + target, + version.getVersionStateEpoch(), + "ISOLATED selected-full storage regression", + java.util.List.of()); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + + private PublishedReleaseBundle selectedFullBundle( + Version version, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence evidence) { + var candidate = bundle(version.getTenantId(), version.getId()); + candidate.setAttestationSchemaVersion("v4"); + candidate.setPublishWorkflowId(evidence.request().publishWorkflowId()); + candidate.setParticipantDigestsJson( + new tools.jackson.databind.ObjectMapper() + .writeValueAsString( + net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures + .participants(version.getId(), evidence, 4))); + candidate.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8)); + return candidate; + } + + private void insertRawSelectedFull( + Fixture fixture, + Version version, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation, + String evidence, + String participants) { + fixture + .dsl() + .execute( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, " + + "canonical_tenant_id, canonical_version_id, published_release_bundle_ref, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, generation_config_revision, manifest_schema_version, artifact_digests_json, " + + "required_manifest_asset_keys_json, participant_digests_json, command_definitions_json, script_only, " + + "world_published_start_location_evidence_json) VALUES (?, ?, 1, ?, ?, ?, 'v4', ?, ?, ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", + version.getTenantId(), + version.getId(), + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + UUID.randomUUID().toString(), + operation.workflowId(), + MANIFEST_HASH, + GENERATION_CONFIG_REVISION, + participants, + evidence); + } + private Fixture fixture(MigrationVersion target) { String schema = "game_design_release_identity_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); From d6c33ce6f0d7d9a7aec08914006f8026dc330d44 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 21:19:13 +1300 Subject: [PATCH 40/61] docs(gamedesign): record selected storage receiving proof --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 86e79a945f..e5b0968868 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -54,7 +54,7 @@ All six native cases freshly pass with zero failures, errors or skips against th Three further native cases use the current test fixture's schema-4 World input from its first construction, actual Game Design source inheritance, reviewed policy, selection, source captures and local publication storage. Direct SQL rejects an incorrect digest schema independently for each of the five participant owners, without creating a bundle or changing the original Game and Version rows or their row versions. A valid v4 bundle retains its original World and participant bytes on independent read and exact retry; changed generation configuration refuses without changing the complete bundle row or its row version. Two concurrent exact storage calls return the same single retained bundle, followed by another unchanged-row retry. Their start latch establishes submitted calls and outcomes; it does not independently measure precommit blocking. A separate SQL case refuses missing selectors, malformed text or numeric epochs, changed request bindings, missing opaque evidence and empty or changed participants, preserving the original Game and Version rows and their row versions without creating a bundle. The unchanged eligible input then commits through actual SQL and independently reads back its original selector bytes. -All eight native bundle cases freshly passed on donor code source `2226e1ca6a4929bea9611255dd5d2f84177e6faa`, with zero failures, errors or skips. Canonical formatting, style, Integration Checkstyle and SpotBugs passed; the one passively identified PostgreSQL container was independently absent after completion. This is donor evidence only; receiving qualification on #2967 remains pending. The proof uses stipulated Account, World and other remote participant evidence and a controlled empty-asset candidate. It does not establish a genuine immutable release, authenticated creator or issuer, currentness, public finalizer enablement, activation, settlement or a Gameplay handoff. The three selected-full fixture helpers are already present at their inherited shared-test blobs in this receiver. No production, installed migration or registration changes are included. +All eight native bundle cases freshly passed on donor code source `2226e1ca6a4929bea9611255dd5d2f84177e6faa`, with zero failures, errors or skips. Canonical formatting, style, Integration Checkstyle and SpotBugs passed; the one passively identified PostgreSQL container was independently absent after completion. On receiving source `fc11e3c1a353537c433ea480b3332d0057df3afc`, all eight bundle cases, ten publication-transaction cases and two historical selector-migration cases freshly passed together with zero failures, errors or skips (2026-10-16 08:14:55–08:16:25 UTC). Integration Checkstyle, SpotBugs, formatting and documentation checks also passed. Main verified fresh reports, unchanged source and independent absence of all four strictly run-owned PostgreSQL containers after forced removal. This is separate receiving evidence; donor attribution remains unchanged. The proof uses stipulated Account, World and other remote participant evidence and a controlled empty-asset candidate. It does not establish a genuine immutable release, authenticated creator or issuer, currentness, public finalizer enablement, activation, settlement or a Gameplay handoff. The three selected-full fixture helpers are already present at their inherited shared-test blobs in this receiver. No production, installed migration or registration changes are included. ### Selected-full owner publication preparation From c2f04d797179710e81df08033b16d4f596997e1e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 23:12:26 +1300 Subject: [PATCH 41/61] Prove retained Account fence rows through owner migrations --- .../player-access-and-session.md | 6 + ...ftFenceHistoryPostgresIntegrationTest.java | 390 ++++++++++++++++++ 2 files changed, 396 insertions(+) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java 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 821498f52e..6a331e6242 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Retained Draft authorization fence migrations + +The [Account fence history fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java) executes the owning filesystem migrations from V75 through V76 and then the current default migration set. Its Account UUID and provenance come from PostgreSQL defaults; it retains the original v1 binding, commit order, stipulated World committed readback, missing Game Design outcome, pending source change and 512-byte source key. Every original column and row version in all six authorization ledger tables, and every prior complete Flyway history row, survives both upgrades. The expected V87 addition of one Global Roles serialization lock is checked separately; it supplies no authority evidence. Exact replay, current pending-mutation refusal and denied binding/readback rewrites leave the retained rows unchanged. + +At source `6a9be6e90decee3c478f36fa4d5ba9f41ddcc313`, the focused native case and affected integration static analysis and formatting pass: one fresh case, zero failures, errors or skips. The actual local run completed on 2026-10-16 from 10:01:32Z to 10:02:08Z. Its strict passive observer owns one PostgreSQL container with an inherited resource-session descriptor, no ownership gaps or observer errors, and independent confirmation that the exact container is absent afterward. Fixture cleanup emits kill 9 and exit 137; this is not graceful shutdown proof. Source capture and World terminal authority are stipulated. This proves retained storage and migration behavior, without genuine World application, final Account settlement, issuer/currentness authority, runtime activation, gameplay admission, Entity delivery or completion of a genuine handoff. + ### Retained StartSession owner tuples The focused Game Session owner fixture retains original unsafe numeric v1 fence carriers through current-execution rejection, including exactly representable values above the safe JSON integer range. It checks the original stored bytes and row version after decoder refusal, conflicting current-spelling replay, Account-projection attachment, evidence continuation and current-attempt reads; the original attempt remains the only row and runtime/admission pointers stay absent. This is controlled PostgreSQL integrity proof, without issuer or deployment provenance. The focused case passes once with two unsafe numeric vectors at source `c6bf1b202b55d0b2616a26d72e4af50c543793fb`; affected integration static analysis, formatting and documentation checks pass. The strict passive observer owns its single PostgreSQL container, with an inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container after completion. Account source-protection and six-store publication cases retain their separate proof boundaries. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..5984a479e7 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java @@ -0,0 +1,390 @@ +package integration.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +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; + +/** Retained V75 storage only; source capture and World terminal authority are test stipulations. */ +class AccountDraftFenceHistoryPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private static final List TABLES = + List.of( + "account_draft_authorization_source_locks", + "account_draft_authorization_fences", + "account_draft_authorization_sources", + "account_draft_authorization_owner_readbacks", + "account_draft_authorization_source_changes", + "account_draft_authorization_changed_scopes"); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @Test + void retainedV1OrderReadbackAndPendingChangeSurviveRequiredOwnerAndCurrentMigrations() { + String schema = "account_fence_history_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = POSTGRES.dataSource(schema); + migrate(source, schema, "75"); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + // V75 predates restriction birth. Let PostgreSQL generate the UUID and its real provenance; + // current AccountRepository insertion must not be used to invent a historical birth receipt. + UUID account = insertHistoricalAccount(dsl); + DraftAuthorizationFenceBinding binding = binding(account); + SourceEvidence legacyKey = binding.sources().get(1); + assertThat(legacyKey.key().getBytes(StandardCharsets.UTF_8)).hasSize(512); + var world = + new OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {8}); + var change = new SourceChange(UUID.randomUUID(), binding.sources(), new byte[] {12}); + seedHistoricalState(dsl, transaction, binding, world, change); + + // Freeze the original columns so later additions cannot disguise a rewrite of retained data. + Map queries = originalRowQueries(dsl); + Map> rows = rows(dsl, queries); + assertThat(rows.values()).allSatisfy(tableRows -> assertThat(tableRows).isNotEmpty()); + int rank75 = historyRank(dsl); + List history75 = history(dsl, rank75); + migrate(source, schema, "76"); + assertThat(rows(dsl, queries)).isEqualTo(rows); + assertThat(history(dsl, rank75)).isEqualTo(history75); + assertRetained(dsl, transaction, binding, world, change, legacyKey); + assertThat(rows(dsl, queries)).isEqualTo(rows); + + int rank76 = historyRank(dsl); + List history76 = history(dsl, rank76); + Flyway current = migrate(source, schema, null); + assertThat(current.info().pending()).isEmpty(); + assertThat(historyRank(dsl)).isGreaterThan(rank76); + assertThat(history(dsl, rank76)).isEqualTo(history76); + Map> currentRows = rows(dsl, queries); + rows.forEach( + (table, originalRows) -> { + if (table.equals("account_draft_authorization_source_locks")) { + // V87 adds a serialization lock from the real Account scope, never authority evidence. + assertThat(currentRows.get(table)) + .containsAll(originalRows) + .hasSize(originalRows.size() + 1); + } else { + assertThat(currentRows.get(table)).isEqualTo(originalRows); + } + }); + assertThat( + dsl.fetch("SELECT source_key FROM account_draft_authorization_source_locks") + .getValues(0, String.class)) + .containsExactlyInAnyOrder( + binding.sources().get(0).key(), legacyKey.key(), "GLOBAL_ROLES:" + account); + assertRetained(dsl, transaction, binding, world, change, legacyKey); + transaction.executeWithoutResult( + ignored -> + assertThat(new DraftAuthorizationFenceRepository(dsl).sourceMutationPermitted(change)) + .isFalse()); + assertThat(rows(dsl, queries)).isEqualTo(currentRows); + assertHistoricalProvenance(dsl, account); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_draft_authorization_fences SET binding = ? WHERE operation_id = ?", + new byte[] {99}, + binding.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM account_draft_authorization_owner_readbacks WHERE operation_id = ?", + binding.operationId())) + .isInstanceOf(DataAccessException.class); + assertThat(rows(dsl, queries)).isEqualTo(currentRows); + } + + private static void assertRetained( + DSLContext dsl, + TransactionTemplate transaction, + DraftAuthorizationFenceBinding binding, + OwnerReadback world, + SourceChange change, + SourceEvidence legacyKey) { + var repository = new DraftAuthorizationFenceRepository(dsl); + transaction.executeWithoutResult( + ignored -> { + assertThat( + repository + .readOriginalBinding(binding.operationId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(binding.canonicalBytes()); + assertThat(repository.reserve(binding).binding()) + .containsExactly(binding.canonicalBytes()); + assertThat(repository.read(binding).ordering()).isEqualTo(Ordering.COMMIT_ORDER); + assertThat(repository.readOwnerResult(binding, Owner.WORLD).orElseThrow().readback()) + .containsExactly(world.canonicalBytes()); + assertThat(repository.readOwnerResult(binding, Owner.GAME_DESIGN)).isEmpty(); + assertThat(repository.readSettlement(binding)).isEqualTo(Settlement.PENDING); + assertThat(repository.readSourceChange(change).status()).isEqualTo("WAITING"); + }); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ?", + legacyKey.key())) + .get(0, String.class)) + .isEqualTo(legacyKey.key()); + } + + private static void seedHistoricalState( + DSLContext dsl, + TransactionTemplate transaction, + DraftAuthorizationFenceBinding binding, + OwnerReadback world, + SourceChange change) { + // Preserve V75's actual guarded insert/order lifecycle. Current source-change APIs also + // inspect later publication owners, which do not exist in this predecessor schema. + transaction.executeWithoutResult( + ignored -> { + for (SourceEvidence evidence : binding.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT DO NOTHING", + evidence.key()); + } + dsl.execute( + "INSERT INTO account_draft_authorization_fences (operation_id, request_id, commit_id, fence_id, binding, ordering) VALUES (?, ?, ?, ?, ?, 'RESERVED')", + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.canonicalBytes()); + for (SourceEvidence evidence : binding.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + evidence.key(), + evidence.canonicalBytes()); + } + dsl.execute( + "UPDATE account_draft_authorization_fences SET ordering = 'COMMIT_ORDER', ordered_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + binding.operationId()); + dsl.execute( + "INSERT INTO account_draft_authorization_owner_readbacks (operation_id, owner, outcome, readback) VALUES (?, 'WORLD', 'COMMITTED', ?)", + binding.operationId(), + world.canonicalBytes()); + dsl.execute( + "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change.changeId(), + change.canonicalBytes()); + for (SourceEvidence evidence : change.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", + change.changeId(), + evidence.key()); + } + }); + } + + private static UUID insertHistoricalAccount(DSLContext dsl) { + UUID suffix = UUID.randomUUID(); + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash, role, email_verified, " + + "login_auth_modes, lifecycle_state) VALUES (?, ?, 'historical-test-verifier', " + + "'player', FALSE, 'PASSWORD,EMAIL_OTP', 'active') RETURNING account_uuid", + "fence-history-" + suffix, + suffix + "@example.test")); + UUID account = Objects.requireNonNull(row.get(0, UUID.class)); + assertThat(account.version()).isEqualTo(4); + assertHistoricalProvenance(dsl, account); + return account; + } + + private static void assertHistoricalProvenance(DSLContext dsl, UUID account) { + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, account_uuid_provenance, account_uuid_source_numeric_id, " + + "account_repository_insert_transaction_id FROM accounts WHERE account_uuid = ?", + account)); + assertThat(row.get("id", Long.class)).isPositive(); + assertThat(row.get("account_uuid_provenance", String.class)) + .isEqualTo("ACCOUNT_DATABASE_INSERT"); + assertThat(row.get("account_uuid_source_numeric_id", Long.class)) + .isEqualTo(row.get("id", Long.class)); + assertThat(row.get("account_repository_insert_transaction_id", Long.class)).isNull(); + } + + private static DraftAuthorizationFenceBinding binding(UUID account) { + var complete = + DraftCommitBinding.create( + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "tenant-key", + 2, + "tenant-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "historical/base:9007199254740993", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "historical-world-payload")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + account, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "2", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + "3", + "5", + "stream/" + account, + "2", + new byte[] {7}), + new SourceEvidence( + SourceKind.ISSUER, + "x".repeat(505), + "3", + "5", + "stream/legacy512", + "2", + new byte[] {9}))); + } + + private static Map originalRowQueries(DSLContext dsl) { + Map queries = new LinkedHashMap<>(); + for (String table : TABLES) { + List columns = + dsl.fetch( + "SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position", + table) + .getValues(0, String.class); + assertThat(columns).isNotEmpty(); + String projection = + String.join(",", columns.stream().map(name -> "\"" + name + "\"").toList()); + queries.put( + table, + "SELECT to_jsonb(original)::text FROM (SELECT " + + projection + + ",xmin::text AS row_xmin FROM " + + table + + ") original ORDER BY to_jsonb(original)::text"); + } + return queries; + } + + private static Map> rows(DSLContext dsl, Map queries) { + Map> rows = new LinkedHashMap<>(); + queries.forEach((table, query) -> rows.put(table, dsl.fetch(query).getValues(0, String.class))); + return rows; + } + + private static int historyRank(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT max(installed_rank) FROM flyway_schema_history")) + .get(0, Integer.class); + } + + private static List history(DSLContext dsl, int rank) { + return dsl.fetch( + "SELECT to_jsonb(h)::text FROM flyway_schema_history h WHERE installed_rank <= ? ORDER BY installed_rank", + rank) + .getValues(0, String.class); + } + + private static Flyway migrate(DriverManagerDataSource source, String schema, String target) { + Path root = Path.of("").toAbsolutePath(); + while (root != null && !Files.isRegularFile(root.resolve("gradlew"))) root = root.getParent(); + root = Objects.requireNonNull(root, "Repository filesystem migrations required"); + var configuration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + root.resolve("services/account-service/src/main/resources/db/migration"), + "filesystem:" + + root.resolve("services/common-saga/src/main/resources/db/migration/saga")); + if (target != null) configuration.target(target); + Flyway flyway = configuration.load(); + flyway.migrate(); + return flyway; + } +} From 2ed0d06b0714afe8fd7c23e8f3b19217e5e73b71 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 23:46:33 +1300 Subject: [PATCH 42/61] Record qualified Account fence history receiving proof --- .../implementation-tracking/player-access-and-session.md | 2 ++ 1 file changed, 2 insertions(+) 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 6a331e6242..a399f9d752 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,8 @@ The [Account fence history fixture](../../../services/account-service/src/test/j At source `6a9be6e90decee3c478f36fa4d5ba9f41ddcc313`, the focused native case and affected integration static analysis and formatting pass: one fresh case, zero failures, errors or skips. The actual local run completed on 2026-10-16 from 10:01:32Z to 10:02:08Z. Its strict passive observer owns one PostgreSQL container with an inherited resource-session descriptor, no ownership gaps or observer errors, and independent confirmation that the exact container is absent afterward. Fixture cleanup emits kill 9 and exit 137; this is not graceful shutdown proof. Source capture and World terminal authority are stipulated. This proves retained storage and migration behavior, without genuine World application, final Account settlement, issuer/currentness authority, runtime activation, gameplay admission, Entity delivery or completion of a genuine handoff. +On Gameplay receiving source `c2f04d797179710e81df08033b16d4f596997e1e`, the same native case freshly passed once with zero failures, errors or skips, together with affected Account integration static analysis, formatting and documentation checks (2026-10-16 10:14:00–10:15:37 UTC). Main read the complete receiving test and saved XML, verified its unchanged qualified Java postimage and independently confirmed its exact run-owned PostgreSQL container absent. Later parent propagation changes no Account implementation or this test. This is focused receiving evidence for retained history; the separate failed whole-Account invocation retains its original outcome. + ### Retained StartSession owner tuples The focused Game Session owner fixture retains original unsafe numeric v1 fence carriers through current-execution rejection, including exactly representable values above the safe JSON integer range. It checks the original stored bytes and row version after decoder refusal, conflicting current-spelling replay, Account-projection attachment, evidence continuation and current-attempt reads; the original attempt remains the only row and runtime/admission pointers stay absent. This is controlled PostgreSQL integrity proof, without issuer or deployment provenance. The focused case passes once with two unsafe numeric vectors at source `c6bf1b202b55d0b2616a26d72e4af50c543793fb`; affected integration static analysis, formatting and documentation checks pass. The strict passive observer owns its single PostgreSQL container, with an inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container after completion. Account source-protection and six-store publication cases retain their separate proof boundaries. From 296d9f0c734a1b0d46c57ceae404b5840339b3dc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:32:22 +1300 Subject: [PATCH 43/61] fix(publication): budget Account settlement for composed owner reads --- ...ntSelectedPublicationSettlementClient.java | 3 +- ...lectedPublicationSettlementClientTest.java | 376 ++++++++++++++++++ 2 files changed, 378 insertions(+), 1 deletion(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java index 7ca015d0a2..8ac8526d31 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java @@ -22,7 +22,8 @@ public final class AccountSelectedPublicationSettlementClient extends AbstractReloadingBlockingGrpcClient< AccountSelectedPublicationSettlementServiceGrpc .AccountSelectedPublicationSettlementServiceBlockingStub> { - private static final long CALL_DEADLINE_SECONDS = 5L; + // Covers both bounded owner reads plus Account persistence, receipt construction, and readback. + private static final long CALL_DEADLINE_SECONDS = 30L; private final String workloadNamespace; private volatile boolean initialized; diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java new file mode 100644 index 0000000000..6ac82997be --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java @@ -0,0 +1,376 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical mTLS proof that Account settlement may complete after the former five-second window. */ +class AccountSelectedPublicationSettlementClientTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @Test + void returnsCanonicalReceiptFromAuthenticatedAccountPeerAfterFormerFiveSecondWindow( + @TempDir Path directory) throws Exception { + TestPki pki = TestPki.create(directory); + var operation = WorldPublicationTerminalTestFixtures.operation(); + var terminal = + WorldPublicationTerminalTestFixtures.terminal( + operation, GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()); + byte[] receipt = receipt(operation, terminal); + var response = AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt); + AtomicReference received = new AtomicReference<>(); + var service = + new AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceImplBase() { + @Override + public void settleSelectedPublication( + SettleSelectedPublicationRequest wireRequest, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !GAME_DESIGN_URI.equals(peer.uri())) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + received.set(wireRequest); + try { + TimeUnit.SECONDS.sleep(6L); + observer.onNext(response); + observer.onCompleted(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + observer.onError(Status.CANCELLED.withCause(interrupted).asRuntimeException()); + } + } + }; + + try (TransportServer server = startServer(pki, service); + AccountSelectedPublicationSettlementClient client = client(pki, server.port(), directory)) { + client.init(); + long started = System.nanoTime(); + byte[] actualReceipt = client.settle(request); + long elapsedNanos = System.nanoTime() - started; + + assertThat(elapsedNanos).isGreaterThanOrEqualTo(TimeUnit.SECONDS.toNanos(6L)); + assertThat(actualReceipt).containsExactly(receipt); + assertThat(received.get()) + .isEqualTo(AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); + } + } + + private static byte[] receipt( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence terminal) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + DraftAuthorizationFenceBinding.frame( + out, + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + return out.toByteArray(); + } + + private static TransportServer startServer(TestPki pki, io.grpc.BindableService service) + throws Exception { + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.accountServer().privateKey(), pki.accountServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(service) + .intercept(new GrpcPeerIdentityInterceptor()) + .build() + .start(); + return new TransportServer(server); + } + + private static AccountSelectedPublicationSettlementClient client( + TestPki pki, int port, Path directory) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + return new AccountSelectedPublicationSettlementClient( + endpoints, pki.clientProperties(directory), new GrpcChannelFactory(), NAMESPACE); + } + + private record TransportServer(Server server) implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Account settlement loopback server did not terminate"); + } + } + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, TestIdentity accountServer, TestIdentity gameDesignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD Account settlement test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + return new TestPki( + readCertificate(caFile), + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) throws Exception { + Path certificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + gameDesignClient.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + gameDesignClient.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String uri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + uri + ",DNS:localhost,IP:127.0.0.1"; + String usage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(2, TimeUnit.SECONDS); + throw new IllegalStateException("test keytool operation timed out"); + } + if (process.exitValue() != 0) { + throw new IllegalStateException( + "test keytool operation failed with exit " + process.exitValue()); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} From 81c363eb01e130c0acf0febea96154f6f477a9f3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:08:20 +1300 Subject: [PATCH 44/61] docs: align Game Logic selected owner contracts --- .../game-logic-service/api-contracts.md | 10 ++++ .../game-logic-service/runtime-and-data.md | 59 +++++++++++++++++-- 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md index d2f24a2288..da7751f16a 100644 --- a/design/architecture/microservices/game-logic-service/api-contracts.md +++ b/design/architecture/microservices/game-logic-service/api-contracts.md @@ -53,6 +53,16 @@ Expected response: ## gRPC +### Selected-source intake command + +The standalone [`RetainGameplayRuleIntake`](../../../../protos/game-logic/v1/gameplay_rule_intake_service.proto) method admits only the exact verified same-namespace Game Design workload, authenticated before decoding. Its versioned request carries independent transport correlation and the complete original Account intake authorization bytes/digest; the closed response echoes the exact binding and original immutable terminal. The intake owner rejects the canonical original Draft and Game Logic intake-authorization credential contexts; player or operator context supplies no intake mutation authority. A service identity alone does not authorize retention: the exact Account HELD operation and synchronized Game Design source remain mandatory under the [selected-input owner contract](runtime-and-data.md#selected-release-rule-inputs-and-intake). The adapter is unregistered and grants no publication, activation or runtime permission. + +### Selected-source terminal read + +The separate, unregistered [`ReadGameplayRuleIntakeTerminal`](../../../../protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto) method accepts only verified same-namespace Account callers, authenticating before decoding source evidence. Its versioned request binds the namespace, fresh read correlation and exact original Account intake authorization bytes/digest. Its closed response echoes that tuple and returns either the original canonical terminal and digest or explicit absence; absence is not an abort. The read is allowlisted to Account and performs no source creation, retention, abort, settlement, or admission. The [Account owner contract](../account-service/api-contracts.md#grpc-apis) defines held-order fencing and exact settlement authority; the [runtime/data owner](runtime-and-data.md#selected-release-rule-inputs-and-intake) defines intake and definitive-abort semantics. The [selected intake tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) and [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records unregistered transport, bounded-message and physical proof gates. + +### Gameplay methods + - `Ping(PingRequest) returns (PingResponse)` is the basic connectivity check defined in [`game_logic_service.proto`](../../../../protos/game-logic/v1/game_logic_service.proto). - `ExecuteCommand(ExecuteCommandRequest) returns (ExecuteCommandResponse)` evaluates a parsed gameplay command and returns the outcome. - `SendCommunication` is the target gameplay communication contract: it inherits the complete validated `PlayerExecutionContext` from Game Session, classifies a world/gameplay communication type, resolves topology/perception/capability/effect facts, and forwards one bounded plan with stable identity, authorized candidate views, and owner handoffs. The current Game Logic adapter first requires `account_id` to be present, positive, and numeric; malformed, missing, or non-positive account identity returns `INVALID_ARGUMENT` before Entity Management or Social calls. It then projects the flat request to Social & Groups as `tenant_id`, that validated account identity as `sender_id`, mapped communication `type`, normalized text as `content`, the resolved recipient when applicable, and `effect_id`; it never falls back to `character_id` for sender authority. It does not forward `session_id`, room context, target kind/name, or legacy `session_attestation` unchanged. Game Logic owns validating the incoming request fields against the target context, but focused tenant/session/character/target mismatch and projection proof remains an implementation gap. Until that target context is propagated, the live request remains the flat field set documented under [Player execution context](#player-execution-context), including legacy `session_attestation`; those request fields are data to validate against the target context, never caller authority. Account messaging, ordinary group/channel communication, browser social actions, and ordinary account/social mail are Social-owned classes and may use an authenticated in-game adapter without becoming Game Logic actions or exposing private content to tenant-authored scripts. Deliberately world-specific mail is a gameplay communication class under [ADR 0147](../../decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md); [ADR 0148](../../decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md) remains the value and attachment authority. See active ADR 0147, mapped from reviewed archive record `archive-ADR-0134`. diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index f9812c20b9..ab5fe9f0f1 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -8,14 +8,14 @@ The prepared selected gameplay-rule intake repository, terminal owner and public The sections below define the target-state runtime contract. Current implementation and proof status is: -- The current implementation attests an empty owned-rule manifest and returns synthetic `appliedCommitId = "version:"` because Game Logic does not yet own version-scoped draft rule tables. The empty-manifest digest is intentional and does not represent hidden service state. +- The default Spring digest composition denies full-version reads because its retained publication source reader is not configured. An explicitly composed reader can validate exact retained intake evidence; missing source or receipt never produces an empty-manifest fallback or synthetic `version:` commit. This does not register or enable publication. The [selected intake tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) and [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation) retain detailed execution attribution and remaining proof limits. - Same-type Game Logic takeover behind an existing edge connection is target behavior, but suppression of a client-visible reconnect after an ordinary qualifying Game Logic restart remains implementation or proof debt under ADR 0013. - Target: `SendCommunication` and every other player-delegated gameplay RPC propagate one complete, validated typed `PlayerExecutionContext` from Game Session through Game Logic and onward. Game Logic validates the context against request and owner evidence, never treats caller-supplied identifiers as authority, remains stateless, and owns semantic gameplay outcomes; Game Session owns session, reconnect, and presentation state. This is the ADR 0024 target contract. - Current implementation gap: the live `SendCommunicationRequest` is still a flat schema with tenant/session/character/account, communication/text and target metadata, room, game-instance, speaker, and effect fields plus legacy `session_attestation`; its current proto does not carry typed `playableStateNamespaceId`, `playableStateScope`, region/epoch, pointer, or admitted-bundle fields. Complete typed-context propagation is therefore not current behavior or proof. ## Runtime Notes -- Stateless service accessed over gRPC by other microservices. +- Stateless gameplay execution accessed over gRPC by other microservices; immutable authored-source intake evidence is durable owner storage, not process-local player or session state. - No authoritative gameplay state may exist only in Game Logic process memory. Any state that must survive instance loss belongs in authoritative domain services, durable ledgers, or Game Session-owned coordination, so another Game Logic instance can take over immediately. - Same-type Game Logic instances must be freely replaceable behind the current caller connection. Meaningful gameplay state needed after a non-edge restart must be reconstructed from authoritative service APIs and Game Session-provided tick/session context rather than preserved only in local memory. - Uses a modular command parser for extensibility. The text protocol's system commands such as `LOGIN`, `LOGON`, and `PING` are interpreted and completed by Game Session; this service focuses on gameplay commands only, as described in the [Game Session Service](../game-session-service/protocols.md#minimal-text-command-protocol). @@ -34,21 +34,70 @@ The sections below define the target-state runtime contract. Current implementat The Game Logic Service does not orchestrate or own synchronous saga or Temporal workflows. All gameplay commands execute inside ticks using Redis-based rollback and the transaction model described in [Transaction Strategies](../../system-architecture-transactions.md). -When a game version is published, its rule data is prepared and finalized by the Game Design and Game Session services; this service reads the already-published, versioned rule data for the active `runtime_version` and does not participate directly in the durable `publish` workflow. +Before the publication digest gate, Game Design supplies authored inputs through the separate authenticated intake below, and Game Logic validates and immutably retains that exact selection. Publication reads the retained evidence without creating or repairing it. Game Session owns runtime orchestration; it does not replace Game Logic's rule-input retention authority. Runtime consumption is limited to the published, pinned release for the active `runtime_version`. Role classification: Game Logic is a digest-gate participant for full publishes, not a workflow-step participant, unless future publish workflows add explicit finalize or compensation steps owned by this service. ## Draft Digest Contract -For full-version publish gating, this service is still a required digest participant even though it does not orchestrate publish-workflow steps. It must expose `GetDraftDesignDigest(tenantId, versionId)` and publish a service-local digest input manifest with: +For full-version publish gating, this service is still a required digest participant even though it does not orchestrate publish-workflow steps. Its authenticated `GetDraftDesignDigest` read binds the publication request and exact retained selection below, rather than selecting content by tenant and version alone, and publishes a service-local digest input manifest with: -- included objects such as version-scoped rule and configuration tables this service owns that affect runtime command behavior; +- included objects and source ownership for the complete effective, version-scoped set of supported command inputs that affect runtime command behavior; - excluded objects such as runtime queues, caches, telemetry tables, and other non-launchability data; - canonicalization rules covering stable ordering, normalization, and null or default handling before hashing; and - `digestSchemaVersion` bump criteria, where any include, exclude, or canonicalization change requires an explicit schema bump and replay or re-record workflow. Publish gating must fail closed if this service cannot attest a digest under its documented manifest for the reported `digestSchemaVersion`. +### Selected-Release Rule Inputs and Intake + +This is the Game Logic owner contract under the canonical [selected-full publication profile](../game-design-service/version-control.md#selected-full-publication-profile). It defines required target behavior; the implementation-status section and linked trackers describe what is implemented or proved. + +Game Design remains the authoring and revision-history owner for authored gameplay rule inputs. Game Logic owns validation and immutable retention of the selected release's rule-input evidence, and attests only the exact selected tenant, version, and applied commit received through an authenticated, operation-bound source operation. A workload identity by itself does not authorize that mutation; the current authority and the source operation's mutation authorization must remain bound through commit. The producer handoff and retained manifest are target behavior and are not established by the current digest receiver. + +The retained input set must be complete for the supported command inputs effective in that version. It includes supported ability and action definitions and the referenced actor-state, resource, condition, and effect catalogs; command and action metadata including admission tags; disposition and continuous-overlay policy; observation, targeting, target-selection, and default target-set bindings; and cost, cooldown, feedback, or lifecycle declarations when they are part of the selected authoritative source. The authoring shapes and ownership remain defined by [Ability & Action Design Tools](../game-design-service/ability-action-tools.md) and the owning domain contracts. This list defines the completeness boundary, not a new wire schema or an additional execution engine. Unknown or unsupported authored inputs make intake and attestation fail closed; they must not be filtered out to produce an apparently empty or partial manifest. + +Intake is a separate, mutation-authorized source operation. `GetDraftDesignDigest` remains a read-only full-version publication read over the already retained, exact-version evidence; it does not populate or repair that evidence. An empty selected input set is attestable only when an authenticated source operation proves the complete owner inventory for the exact selected commit is empty. Missing storage, a missing producer, or absent rows are not evidence of an empty authored set. + +The content-selection binding is distinct from the unchanged `publicationDigestRequest/v1` authorization/replay context. Its `game-logic-publication-source-read/v1` preimage consists of exactly three unsigned canonical ASCII byte-length frames, in order: the UTF-8 schema name, the exact existing publication request canonical preimage, and the complete original finalized Account Game Logic intake authorization bytes retained by Game Design's immutable selected receipt. Lengths use canonical decimal digits followed by `:` and exactly that many bytes; missing, extra, trailing or noncanonical frames deny. Segment and total limits, including framing and transport overhead, must be enforced before allocation. Hash the exact bytes using the existing SHA-256 representation and freeze executable preimage/hash vectors. This binding selects content; it creates no read or mutation authority and does not reinterpret the shared publication schema. + +Game Design derives that binding only from its immutable selected receipt, never from caller-selected historical authorization or latest state. Game Logic authenticates the exact Game Design workload and publication method before decoding, independently validates both bindings, then reads the exact genuine retained intake operation and its successful terminal. The complete authorization, canonical tenant/version, selected commit and source must agree byte-for-byte with retained owner evidence. Authorization bytes and digest alone prove neither Account issuance nor successful retention. The numeric Game Design Version row in the unchanged publication scope must agree with the original selected binding's persisted target; retain its canonical UUID and source-row provenance rather than inventing a UUID/numeric alias. + +The response binds the complete original lookup, source and commit provenance, positive participant schema/canonicalization evidence, aggregate digest and dedicated ability-schema digest. Game Design exact-checks each before recording an attestation. Missing or mismatched retained evidence denies; there is no tenant/version-only or latest fallback, read-side repair, fresh mutation reauthorization of historical intake, or reuse of the Account-only terminal-read permission for Game Design. Game Logic is not a script-patch participant. This selection plumbing does not establish complete source/settlement or final release-attestation proof; current construction and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + +The original Game Design author operation settles before this intake. Game Logic obtains the complete synchronized source from Game Design's authenticated exact-commit owner read and verifies a distinct [Account intake authorization](../account-service/api-contracts.md#grpc-apis) for that same immutable source. That exact finalized authorization also accompanies its [operation-authorized source read](../game-design-service/api-contracts.md#operation-authorized-gameplay-source-read); Game Logic cannot reuse Account's preliminary read-only branch or omit independent Account readback. It does not retrospectively join the original Draft's participant vector or allocate another selected commit. Account source participation remains held through Game Logic's local commit and exact terminal settlement; a remote `HELD` sample alone is insufficient. Retained source, complete manifest/provenance and the immutable intake result commit atomically. A definitive abort uses the same operation serialization and prevents later retention; missing rows or expired waits do not prove abort. Identical recovery returns the original result, never a latest source or replacement manifest. These obligations do not make Game Logic a publication-workflow mutation participant. + +The standalone [`RetainGameplayRuleIntake`](../../../../protos/game-logic/v1/gameplay_rule_intake_service.proto) transport admits only verified same-namespace Game Design, authenticated before decoding. It invokes the existing distinct-order intake, not publication authorization. Exact namespace, independent transport correlation and complete original authorization bytes/digest are echoed with the immutable original terminal; both retained and definitive-abort retries preserve their original outcome. The client verifies Game Logic's workload and exact response binding. Game Design obtains the subsequent settlement receipt through the [Account-owned settlement transport](../account-service/api-contracts.md#grpc-apis), never by calling the Account-only terminal reader. Intake and terminal adapters remain standalone and unregistered; their existence does not establish a genuine authorization producer or publication completion. The intake owner rejects the canonical original Draft and Game Logic intake-authorization credential contexts; those creator credentials do not accompany the owner-to-owner intake. Player or operator context supplies no intake mutation authority. + +The authenticated publication read must preserve the exact source-operation and selected-commit correlation through its retained-manifest lookup and readback. Validating the publication request and then resolving content by tenant/version alone is insufficient when it can select a different source operation; neither a latest lookup nor request authentication repairs missing immutable provenance. + +The full-version manifest and the dedicated `abilitySchemaDigest` share the selected commit and Game Logic's existing canonicalization and `digestSchemaVersion` contract, but they attest distinct scopes. The aggregate full-manifest `contentDigest` is not an ability-schema digest, and neither the Automation & Scripting digest nor Game Design's control-plane digest substitutes for either Game Logic attestation. Any change to the dedicated ability-schema input set or its canonicalization requires the same explicit schema bump and digest replay or re-record process as other manifest changes. This contract governs publication evidence only; it does not authorize activation of unpublished rules or make Game Logic a participant in Game Design's publication workflow mutations. Game Logic does not read an admin database for runtime rules. + +### Dedicated Ability-Schema Projection v1 + +The dedicated content preimage is RFC 8785 canonical UTF-8 JSON with exactly `{"schema":"gameplay-ability-schema/v1","families":{...}}`. `families` contains all 15 names in the closed `gameplay-rule-manifest/v1` grammar, including explicit empty arrays. Validate the complete selected manifest before projecting: unknown fields or definitions, missing families, unresolved references and unsupported shapes fail even outside the selected closure. Seed every `ABILITIES` and every `ACTIONS` definition, then retain the complete typed-reference closure keyed by `(family, logical key)`. Preserve every field of each retained definition, its original selected-manifest family order, and every nested-array order. A visited set terminates reachable cycles while retaining all reachable definitions; this does not establish execution support for an otherwise unsupported cycle. + +The closed grammar's reference edges are exhaustive: + +| Definition family | Typed reference edges | +| --- | --- | +| `ABILITIES` | `actionSequenceId` → `ACTIONS`. | +| `ACTIONS` | `admissionTags` → `ADMISSION_TAGS`; target sets → targeting/selection policies and optional unresolved feedback; costs → `RESOURCES`; effect bindings → `EFFECTS`; `feedbackKeys` → `FEEDBACK`. | +| `CONDITIONS` | `effectKeys` → `EFFECTS`. | +| `EFFECTS` | `statKey` → declared numeric `STATS` or `RESOURCES`; `ADJUST_RESOURCE` and `MAXIMUM` require `RESOURCES`; `conditionKey` → `CONDITIONS`. | +| `OBSERVATION_POLICIES` | Predicate references below. | +| `TARGETING_POLICIES` | `observationPolicyKey` → `OBSERVATION_POLICIES`; eligibility predicate references; `safeFailureFeedbackKey` → `FEEDBACK`. | +| `SELECTION_POLICIES` | Comparator `statKey` → numeric `STATS` or `RESOURCES`; `MAXIMUM` requires `RESOURCES`. | +| `DISPOSITIONS` | `deniedAdmissionTags` → `ADMISSION_TAGS`; `safeFeedbackKey` → `FEEDBACK`. | +| `COMMANDS` | `actionSequenceId` → `ACTIONS`; `admissionTags` → `ADMISSION_TAGS`; commands are not roots or reverse dependencies. | +| `CONTINUOUS_OVERLAYS` | Eligibility predicate references; `deniedAdmissionTags` → `ADMISSION_TAGS`; `effectKeys` → `EFFECTS`. | +| `DEFAULT_BINDINGS` | Target sets → targeting/selection policies and optional unresolved feedback. | +| `STATS`, `RESOURCES`, `ADMISSION_TAGS`, `FEEDBACK` | No external definition references. Their complete fields, tags and feedback arguments remain retained when reached. | + +Target-set policy fields are `targetingPolicyKey` → `TARGETING_POLICIES`, `targetSelectionPolicyKey` → `SELECTION_POLICIES`, and non-null `unresolvedFeedbackKey` → `FEEDBACK`. Predicate operands are traversed recursively: `STAT_COMPARE.factKey` selects its declared numeric stat/resource; `CONDITION_PRESENT.factKey` → `CONDITIONS`; `DISPOSITION_EQUALS.factKey` → `DISPOSITIONS`. `SOURCE` and declared target-set keys are action-local, not catalog aliases. Cooldown keys, names, tags, player-selector slots and feedback argument/message identifiers create no guessed external edges. The closed grammar rejects stat/resource key collisions before resolving a numeric reference. Unreferenced catalogs, commands, overlays and default bindings stay outside this dedicated digest, while remaining in the aggregate manifest. An effective implicit runtime dependency not expressible by this grammar must be reported and denied, not silently omitted or guessed from names. + +Hash these exact bytes with the existing lowercase `sha256:` encoding. Carry the positive participant `digestSchemaVersion`, canonicalization evidence and exact selected-commit/source-operation provenance separately; source/auth receipts, publication metadata and commit IDs never enter this content-only preimage. A valid explicit-empty manifest has a defined content hash but cannot establish authenticated empty-source provenance: the original complete owner inventory and immutable intake must independently prove it. The executable [projection vectors](../../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java) freeze empty preimage/hash `sha256:0207783645e944996b4f7589d2662d5b8309231769681e162ee05de51d34db2a` and the complete two-action/all-root preimage/hash `sha256:659a321a8fd1a02a4825a81568d67dee5039a1cb538756fb91c212aeaea1c536`, plus transitive-field, ordering, unrelated-input and negative cases. Any include/exclude, edge or canonicalization change requires the existing explicit schema bump and replay/re-record process; do not reinterpret retained evidence. Projection construction alone does not register the digest receiver, authorize publication or activate gameplay. + ## Redis Role and Prefixes ### Coordination Redis From 26d00c22169d19e190ae43953ab7ef1cad136ecf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:16:46 +1300 Subject: [PATCH 45/61] test: prove canonical actor repository scope isolation --- .../gameplay-rules-entities-and-effects.md | 6 + .../RetainedActorIdentityIntegrationTest.java | 181 ++++++++++++++++++ 2 files changed, 187 insertions(+) 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 1a8e071898..1a61cfad28 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 @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for gameplay rules, entities, and ## Current Status +### Canonical actor repository read isolation + +One focused case in [RetainedActorIdentityIntegrationTest](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java) freshly passes against PostgreSQL with affected integration static and formatting checks. It calls the actual `ActorIdentityRepository` roster and exact-actor readers against populated tenant, account and namespace decoys, wrong scope and a quarantined actor. All five controlled actor rows share the same private numeric keys; canonical reads select only the exact UUID tuple and preserve the original row values and `xmin`. This restores focused reader coverage beyond the preceding raw-SQL tuple checks. Other cases retain their earlier execution attribution; the initial observer command-guard failure occurred before Gradle/test execution and receives no proof credit. + +These stored SQL identities prove bounded storage/read isolation, not genuine owner issuance, Account/tenant provenance, authenticated caller composition, canonical player admission or runtime quarantine activation. Existing passive owner and registration holds remain unchanged. + ### Selected gameplay-rule retention and receipt composition The prepared standalone Game Logic intake owner requires the exact Account HELD authorization and selected synchronized Game Design source before retaining an immutable terminal. The Game Design selected-intake command and receipt owners compose that retention with Account-owned terminal settlement and persist the exact receipt under existing GDS V1009. New Game Logic V1003 follows the empty owned V1 baseline and the shared Saga V1000–V1002 history; existing Account and GDS migration history stays unchanged. None of these owners or read adapters is registered, and the current legacy digest receiver and runtime rule consumption remain separate. 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 index e1d4434505..49fb05ab34 100644 --- 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 @@ -381,6 +381,187 @@ private List storedActorUuids( scope.name()); } + @Test + void canonicalOwnerRepositoryReadsExactScopedActorsAndExcludesQuarantine() { + // These stored identities are controlled SQL inputs, not owner issuance or player admission. + var shared = PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + var isolated = PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; + UUID otherAccount = UUID.randomUUID(); + UUID otherTenant = UUID.randomUUID(); + UUID otherNamespace = UUID.randomUUID(); + UUID targetActor = UUID.randomUUID(); + UUID accountActor = UUID.randomUUID(); + UUID tenantActor = UUID.randomUUID(); + UUID namespaceActor = UUID.randomUUID(); + UUID quarantinedActor = UUID.randomUUID(); + insertNamespace(tenantUuid, namespaceUuid, shared); + insertNamespace(tenantUuid, otherNamespace, isolated); + insertNamespace(otherTenant, namespaceUuid, shared); + // Identical private numeric keys deliberately do not grant canonical tuple equivalence. + insertActor( + "reader-target", + targetActor, + accountUuid, + tenantUuid, + namespaceUuid, + shared, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + insertActor( + "reader-account", + accountActor, + otherAccount, + tenantUuid, + namespaceUuid, + shared, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + insertActor( + "reader-tenant", + tenantActor, + accountUuid, + otherTenant, + namespaceUuid, + shared, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + insertActor( + "reader-namespace", + namespaceActor, + accountUuid, + tenantUuid, + otherNamespace, + isolated, + "shared-live", + "OWNER_RESOLVED", + null, + accountId, + tenantId); + insertActor( + "reader-quarantine", + quarantinedActor, + accountUuid, + tenantUuid, + namespaceUuid, + shared, + "shared-live", + "QUARANTINED", + "TEST_ONLY_UNQUALIFIED", + accountId, + tenantId); + var originalRows = + jdbcTemplate.queryForList( + "SELECT to_jsonb(actor)::text || ':' || xmin::text FROM characters actor " + + "WHERE id IN (SELECT id FROM characters WHERE tenant_id = ? AND account_id = ?) " + + "ORDER BY character_uuid", + String.class, + tenantId, + accountId); + assertThat(originalRows).hasSize(5); + + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), accountUuid.toString(), namespaceUuid.toString(), shared)) + .extracting(identity -> identity.characterUuid()) + .containsExactly(targetActor); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), otherAccount.toString(), namespaceUuid.toString(), shared)) + .extracting(identity -> identity.characterUuid()) + .containsExactly(accountActor); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + otherTenant.toString(), accountUuid.toString(), namespaceUuid.toString(), shared)) + .extracting(identity -> identity.characterUuid()) + .containsExactly(tenantActor); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), accountUuid.toString(), otherNamespace.toString(), isolated)) + .extracting(identity -> identity.characterUuid()) + .containsExactly(namespaceActor); + assertThat( + actorIdentityRepository.findOwnerResolvedRoster( + tenantUuid.toString(), accountUuid.toString(), namespaceUuid.toString(), isolated)) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + shared, + targetActor.toString())) + .get() + .satisfies( + identity -> { + assertThat(identity.characterUuid()).isEqualTo(targetActor); + assertThat(identity.accountUuid()).isEqualTo(accountUuid); + assertThat(identity.tenantUuid()).isEqualTo(tenantUuid); + assertThat(identity.playableStateNamespaceId()).isEqualTo(namespaceUuid); + assertThat(identity.playableStateScope()).isEqualTo(shared); + assertThat(identity.status().name()).isEqualTo("OWNER_RESOLVED"); + }); + for (UUID excluded : List.of(accountActor, tenantActor, namespaceActor, quarantinedActor)) { + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + shared, + excluded.toString())) + .isEmpty(); + } + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + otherAccount.toString(), + namespaceUuid.toString(), + shared, + targetActor.toString())) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + otherTenant.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + shared, + targetActor.toString())) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + otherNamespace.toString(), + isolated, + targetActor.toString())) + .isEmpty(); + assertThat( + actorIdentityRepository.findOwnerResolvedActor( + tenantUuid.toString(), + accountUuid.toString(), + namespaceUuid.toString(), + isolated, + targetActor.toString())) + .isEmpty(); + assertThat( + jdbcTemplate.queryForList( + "SELECT to_jsonb(actor)::text || ':' || xmin::text FROM characters actor " + + "WHERE id IN (SELECT id FROM characters WHERE tenant_id = ? AND account_id = ?) " + + "ORDER BY character_uuid", + String.class, + tenantId, + accountId)) + .isEqualTo(originalRows); + } + @Test void namespaceIdentityAndScopeAreImmutableWithoutActorReferences() { for (PlayableStateScope scope : From 3252ed58ef7507b576012195ecc0bc2facea375c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:31:50 +1300 Subject: [PATCH 46/61] test: retain complete large Entity terminal receipts over mTLS --- .../gameplay-rules-entities-and-effects.md | 2 + ...ourceIntakeTerminalReadClientMtlsTest.java | 69 +++++++++++++++++++ 2 files changed, 71 insertions(+) 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 1a61cfad28..a08cca41ec 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 @@ -129,6 +129,8 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Validation and Proof +- A restored positive Entity terminal-read socket case freshly passes with affected Common Platform Core test Checkstyle, SpotBugs and formatting. The actual `GrpcEntitySelectedSourceIntakeTerminalReadClient` receives a complete canonical receipt larger than the ordinary 4 MiB gRPC default over loopback mTLS, within the declared wire bound; the server verifies the Account workload and original request, and the client returns the exact original receipt and authorization bytes. The existing [terminal client test](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java) previously covered only missing-receipt transport and server pinning; that case retains its earlier execution attribution. The complete authorization, World inventory and Entity receipt are controlled fixtures, and the shared test PKI differs from the donor's inline PKI helper. This is client/codec transport proof, not genuine issuer or recipient storage, currentness, settlement, runtime registration or handoff closure. + - The 2026-10-14 current-parent source correction keeps the assignment/roster family unregistered under ordinary component scanning, including when the former activation flags are true, and excludes both roster methods from the JWT public-method allowlist. The initial consolidated gate executed 281 Entity unit cases with one stale allowlist assertion failure, 30 native PostgreSQL cases with no failures, errors or skips, and 17 focused Game Session roster-client cases with no failures, errors or skips. After correcting that assertion, all 11 focused registration, manual-composition and peer-policy cases passed with no failures, errors or skips; affected formatting, static analysis and documentation checks passed. These combined results qualify the bounded source and unchanged retained storage, not production registration, ADR 0163 disposal, genuine authenticated caller completion or a fresh packaged player journey. - 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. diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java index ca3ae70881..816985ea7f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -103,6 +103,75 @@ void authenticatesAccountClientAndPinsSameNamespaceEntityServer() throws Excepti assertThat(calls).hasValue(1); } + @Test + void loopbackMtlsAcceptsCompleteLargeCanonicalReceipt() throws Exception { + // Codec/transport values only: this fixture supplies no genuine Account/World/Entity authority. + var fixture = + net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures + .create(); + var request = + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + NAMESPACE, fixture.authorization()); + byte[] expectedReceipt = fixture.receipt().canonicalBytes(); + var wire = + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence(request, fixture.receipt())); + assertThat(wire.getSerializedSize()).isGreaterThan(4 * 1024 * 1024); + assertThat(wire.getSerializedSize()) + .isLessThanOrEqualTo( + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.MAX_WIRE_BYTES); + var service = + new EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceImplBase() { + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest original, + StreamObserver observer) { + calls.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + var decoded = + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(original); + assertThat(decoded).isEqualTo(request); + assertThat(decoded.binding().canonicalBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + observer.onNext( + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence( + decoded, fixture.receipt()))); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + entityServer.privateKey(), entityServer.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + client = newClient(accountClient); + client.init(); + + var actual = client.read(request); + + assertThat(actual.request()).isEqualTo(request); + assertThat(actual.receipt().canonicalBytes()).isEqualTo(expectedReceipt); + assertThat(actual.receipt().authorizationBindingBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + assertThat(calls).hasValue(1); + } + private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { startServer(identity, 0); From 07034210edd8c95d90dabd78115b96a3c68676c2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 17 Oct 2026 21:10:49 +1300 Subject: [PATCH 47/61] docs(automation): describe selected source inventory boundary --- .../runtime-and-data.md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md index 0048d2555f..24b45510ab 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -39,6 +39,37 @@ The current dry-run and readiness capacity reservations also are not idempotent The current queue consumer has an additional bounded-drain limitation that must remain explicit: `drainWorkItems` and `drainIndexedWorkItemPointers` consume pointers with atomic Redis `LPOP`, so a producer's concurrent `RPUSH` is not discarded by a range/read followed by deletion. The indexed path still uses database-wide `KEYS("automation:queue:*")`, and the current lists have no pointer TTL or maximum-length bound, so the path is not a cluster-safe discovery or retention proof. Durable claim fallback can process pending PostgreSQL rows independently, but it does not establish a reset/rebuild recovery gate. Target enqueue/rebuild must atomically apply `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`, preserve or durably account for unreturned tails and concurrent appends, use an owner-maintained/cursor-based cluster-safe queue index rather than database-wide `KEYS`, and trigger bounded durable re-drive with exact identity/readback before reset-gate release. The two settings remain environment/service configuration (currently `TBD`); no target support claim is valid until each environment supplies validated positive bounds and focused concurrent-drain, truncation/expiry, cluster, and re-drive proof. +The selected-source terminal reader and Account settlement composition are standalone and unregistered construction components; they do not establish complete authenticated owner intake or physical proof. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) owns their code and validation status. Without the exact committed Account settlement, finalized source participation remains pending. + +## Authored Template Source Inventory + +Automation owns the source inventory declaration schema carried as authored content by a new versioned Game Design `TEMPLATE_CONFIG` source ([closed schema and reference rules](../game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state)). The Automation value schema is `automation-authored-source-inventory/v1` with exactly three required family arrays: `SCRIPT_DEFINITIONS`, `EVENT_BINDINGS`, and `SCRIPT_PATCH_SOURCES`. The current shared value accepts only explicitly authored empty arrays; omitted, null, unknown, malformed, duplicate, trailing, oversized, or nonempty input is rejected. Its canonical RFC 8785 bytes preserve the authored declaration deterministically. This declaration is content only: it is not an owner receipt, source readback, authorization, provenance, or proof of owner completeness, and cannot qualify a publication on its own. Existing `TEMPLATE_CONFIG` schema-version content is not reinterpreted as this declaration. + +The authored shape is: + +```json +{ + "schema": "automation-authored-source-inventory/v1", + "families": { + "SCRIPT_DEFINITIONS": [], + "EVENT_BINDINGS": [], + "SCRIPT_PATCH_SOURCES": [] + } +} +``` + +Script schedule definitions remain derived from script source and are not another authored family. The optional template `automation.scriptPatch` is a separate default selection of one exact patch for the same base version; its absence means no template default and does not establish an empty patch-source inventory. The declaration producer, full owner census/retention and Account terminal-settlement composition remain incomplete; the standalone terminal reader does not register or enable intake. Publication must continue to deny where complete authenticated owner evidence or physical proof is unavailable. + +An Automation selected-source intake is a distinct Account-authorized operation, not participation inferred from a Game Design-only commit. Account must first authorize the exact immutable source read; after the read, Automation must retain the original content and outcome while holding revalidated current Account authority through its local commit. The declaration must originate in a genuine authored revision of the exact selected Game Design commit. Its inventory covers script roots, every event binding and patch source, and all dependent or inbound behavior/hook references from the complete selected World and other authored inputs. An explicit empty declaration is supported only when authenticated owner evidence closes that whole selected input set and rejects conflicting or unqualified existing content. Missing producers, omitted families, unavailable rows and a tenant-wide script query are not absence proof; an unsupported nonempty input denies instead of being discarded. + +The immutable intake result retains the canonical tenant/version and selected commit, original source revision and operation, complete inventory bytes, exact Account authorization binding, original owner terminal and their digests. The result and authenticated readback are derived after the authored source commit, outside its preimage. An identical retry reads the original result; changed scope, selection, content or authorization binding conflicts rather than manufacturing a new receipt. A workload identity, creator declaration or matching digest alone is insufficient. Until the required selected-input producers and continuously held-authority proof exist, the Automation receipt cannot qualify publication, which must not substitute an empty or synthetic version marker. + +The separate [`AutomationSelectedSourceIntakeCommandService.RetainSelectedSource`](../../../../protos/automation-scripting/v1/automation_selected_source_intake_command.proto) supplies a closed schema-version-1 retention command without changing those owner checks. The receiver authenticates the exact Game Design workload against its configured namespace before decoding and rejects authenticated caller context and ambient original-Draft-order, Game Logic intake or selected-owner authorization-producer credentials. It separately denies a mismatched request namespace or ambient SQL/synchronization. Its request binds an independent nonzero transport correlation, complete original Account Automation-retention authorization bytes/digest, and the original World freeze request and acknowledgement through their existing codecs. The complete selected Draft, canonical tenant/version and namespace must agree across those bindings; original operation, fence, intake and applicable freeze identities cannot be reused as transport correlation. Success echoes the entire request and returns only the complete canonical `COMMITTED_EMPTY` receipt and digest. Changing only the transport correlation replays the same owner receipt, not another intake. The request wire bound is the 16 MiB authorization bound plus both existing 1 MiB World Account-binding bounds and 64 KiB; the response bound adds the unchanged Automation receipt bound and another 64 KiB. These wire budgets do not expand any embedded grammar or byte limit. The workload-only file-backed mTLS client pins Automation, applies a five-second deadline and rejects ambient SQL/synchronization before transport. This standalone command remains unregistered and grants no publication, source release, admission or runtime activation. + +Automation's terminal read is a separate schema-version-1 `AUTOMATION_INTAKE_TERMINAL_READ` request, authenticated only for the exact same-namespace Account mTLS peer. It carries a fresh read correlation distinct from the original operation, fence and intake request, plus the complete original authorization binding bytes and digest. The only positive terminal is the typed `COMMITTED_EMPTY` outcome, with the complete canonical immutable Automation receipt bytes and recomputed digest; an exact retry returns that same receipt even when the read correlation changes. Missing, pending, changed, corrupt or ambiguous evidence denies and is never interpreted as absence, abort or release authority. Account's settlement consequence is defined by its [selected-owner intake contract](../account-service/api-contracts.md#grpc-apis) and must preserve the same original operation under its existing source locks. + +Publication consumes this empty-only receipt only within the [canonical selected-full profile](../game-design-service/version-control.md#selected-full-publication-profile), with the original publication request/freeze binding and independent exact recipient readback. The immutable receipt and closed transport definitions do not enable arbitrary nonempty Automation source, produce genuine Account authorization, establish continuous currentness or register a runtime command. The [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation) retains the implementation and controlled-proof limits. + ## Architecture and Design Notes - Executes scripts in response to world or player events received via gRPC callbacks from Game Session and other domain services. Standard lifecycle events (`onSpawn`, `onEnterRegion`, `onCommand`, and similar) are delivered as unary gRPC calls via `TriggerScriptEvent`, while tick-derived scheduling signals are driven by a gRPC streaming tick heartbeat originating from Game Session. From d8661725f047374015114017986543da46b633aa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 11:29:17 +1300 Subject: [PATCH 48/61] Expose physical LOGIN install failure stages --- ...eplayLoginContextRedisIntegrationTest.java | 95 +++++++++++++++---- 1 file changed, 74 insertions(+), 21 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java index c6d0b1961d..1770009798 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -303,8 +303,13 @@ void exactInstallAndRetryUsePhysicalAcknowledgementsIndependentReadbackAndNoSecr var provider = new TracedProvider(writer); var client = client(provider, qualification, 1); var installed = InitialGameplayLoginContextState.installed(original, result); - assertThat(client.install(original, result).orElseThrow().encode()) - .containsExactly(installed.encode()); + provider.expectedReadback = installed.encode(); + var firstInstall = client.install(original, result); + System.out.println("Initial LOGIN context install observations: " + provider.traces); + assertThat(firstInstall) + .as("first physical install observations: %s", provider.traces) + .isPresent(); + assertThat(firstInstall.orElseThrow().encode()).containsExactly(installed.encode()); byte[] payload = admin.get(key(original)); assertThat(payload).containsExactly(installed.encode()); assertThat(containsSequence(payload, result.compactJwtBytes())) @@ -314,8 +319,10 @@ void exactInstallAndRetryUsePhysicalAcknowledgementsIndependentReadbackAndNoSecr .as("credential excluded from live payload") .isFalse(); assertThat(admin.pexpiretime(key(original))).isEqualTo(-1L); - assertThat(client.install(original, result).orElseThrow().encode()) - .containsExactly(installed.encode()); + var exactRetry = client.install(original, result); + System.out.println("Initial LOGIN context retry observations: " + provider.traces); + assertThat(exactRetry).as("exact physical retry observations: %s", provider.traces).isPresent(); + assertThat(exactRetry.orElseThrow().encode()).containsExactly(installed.encode()); assertThat(admin.get(key(original))).containsExactly(payload); assertThat(provider.traces).hasSize(4); assertThat(provider.traces.get(0)) @@ -1107,6 +1114,7 @@ private static final class TracedProvider private Runnable beforeEval = () -> {}; private Runnable afterAck = () -> {}; private final AtomicInteger opened = new AtomicInteger(); + private byte[] expectedReadback; private TracedProvider(RedisClient client) { this.client = client; @@ -1134,31 +1142,76 @@ public StatefulRedisConnection get() { (commandProxy, command, arguments) -> { String name = command.getName(); trace.add(name); - if (name.equals("evalsha")) beforeEval.run(); - if (name.equals("get") && index == 1 && fault.equals("readback")) { - connection.close(); - throw new IllegalStateException( - "Controlled independent readback connection interrupted"); - } - Object answer = invoke(commands, command, arguments); - if (name.equals("dispatch") - && arguments != null - && arguments[0] instanceof ProtocolKeyword keyword - && new String(keyword.getBytes(), StandardCharsets.US_ASCII) - .equals("WAITAOF")) { - trace.add("WAITAOF"); - afterAck.run(); - if (fault.equals("lost-ack")) { + boolean waitAof = + name.equals("dispatch") + && arguments != null + && arguments[0] instanceof ProtocolKeyword keyword + && new String(keyword.getBytes(), StandardCharsets.US_ASCII) + .equals("WAITAOF"); + if (waitAof) trace.add("WAITAOF"); + try { + if (name.equals("evalsha")) beforeEval.run(); + if (name.equals("get") && index == 1 && fault.equals("readback")) { connection.close(); throw new IllegalStateException( - "Controlled physical acknowledgement response delivery lost"); + "Controlled independent readback connection interrupted"); + } + Object answer = invoke(commands, command, arguments); + if (name.equals("evalsha")) recordLongReply(trace, "evalsha", answer); + if (name.equals("get")) recordGet(trace, index, answer); + if (name.equals("pttl")) recordLongReply(trace, "pttl", answer); + if (waitAof) { + recordWaitAofReply(trace, answer); + afterAck.run(); + if (fault.equals("lost-ack")) { + connection.close(); + throw new IllegalStateException( + "Controlled physical acknowledgement response delivery lost"); + } } + return answer; + } catch (Throwable failure) { + trace.add( + "commandException=" + + (waitAof ? "WAITAOF" : name) + + ":" + + failure.getClass().getName()); + throw failure; } - return answer; }); }); } + private void recordGet(List trace, int connectionIndex, Object answer) { + boolean present = answer instanceof byte[]; + trace.add("getPresent=" + present); + if (connectionIndex == 1 && expectedReadback != null) { + trace.add( + "readbackMatchesExpected=" + + (answer instanceof byte[] bytes && Arrays.equals(expectedReadback, bytes))); + } + } + + private static void recordLongReply(List trace, String command, Object answer) { + if (answer instanceof Long value) trace.add(command + "Result=" + value); + else trace.add(command + "ReplyType=" + replyType(answer)); + } + + private static void recordWaitAofReply(List trace, Object answer) { + if (answer instanceof List counts + && counts.size() == 2 + && counts.get(0) instanceof Long local + && counts.get(1) instanceof Long replicas) { + trace.add("WAITAOFCounts=local:" + local + ",replicas:" + replicas); + } else { + trace.add("WAITAOFReplyType=" + replyType(answer)); + } + } + + private static String replyType(Object answer) { + return answer == null ? "null" : answer.getClass().getName(); + } + private static Object invoke(Object target, Method method, Object[] args) throws Throwable { try { return method.invoke(target, args); From ee80be0af534c42fed4aecdbc609f6cf48f66603 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:45:08 +1300 Subject: [PATCH 49/61] Add publication settlement receiving boundary --- .../runtime-and-data.md | 31 + .../game-logic-service/runtime-and-data.md | 59 +- design/project-management/ai-observations.md | 38 + ...ame-authoring-publishing-and-activation.md | 32 + .../gameplay-rules-entities-and-effects.md | 2 + .../player-access-and-session.md | 52 + .../world-runtime-and-movement.md | 2 + .../selected_publication_order_service.proto | 30 + ...ected_publication_settlement_service.proto | 31 + .../DraftAuthorizationFenceRepository.java | 4 +- ...StartSessionReservationEvidenceClient.java | 76 +- ...SessionActivationProtectionRepository.java | 26 + .../session/AccountControlUiActorService.java | 49 +- ...blicationAuthorizationReadGrpcService.java | 78 + ...ntPublicationAuthorizationReadService.java | 85 + ...untPublicationAuthorizationRepository.java | 333 +++ ...ccountPublicationAuthorizationService.java | 50 + ...ectedDraftPublicationOrderGrpcService.java | 152 ++ ...tSelectedDraftPublicationOrderService.java | 88 + ...ctedDraftPublicationSettlementService.java | 139 ++ ...ectedPublicationSettlementGrpcService.java | 97 + ...selected_publication_closure_inventory.sql | 73 + ...ftFenceHistoryPostgresIntegrationTest.java | 390 ++++ ...wardMigrationsPostgresIntegrationTest.java | 4 +- ...tionProtectionPostgresIntegrationTest.java | 191 ++ ...iPositiveOwnerPostgresIntegrationTest.java | 132 +- ...inalDraftOrderPostgresIntegrationTest.java | 363 ++- ...horizationMtlsPostgresIntegrationTest.java | 1082 +++++++++ ...nAuthorizationPostgresIntegrationTest.java | 1396 ++++++++++++ ...horizationFenceWorldParticipationTest.java | 27 +- ...tSessionReservationEvidenceClientTest.java | 310 ++- .../AccountControlUiSigningAndActorTest.java | 7 + ...blicationAuthorizationReadServiceTest.java | 246 +++ ...ntPublicationAuthorizationServiceTest.java | 43 + ...ctedDraftPublicationOrderGrpcMtlsTest.java | 578 +++++ ...dDraftPublicationOrderGrpcServiceTest.java | 305 +++ ...ectedDraftPublicationOrderServiceTest.java | 292 +++ ...DraftPublicationSettlementServiceTest.java | 403 ++++ ...dPublicationSettlementGrpcServiceTest.java | 142 ++ ...ldParticipationSettlementGrpcMtlsTest.java | 130 +- ...ntStartSessionReservationProofPkiTest.java | 85 + .../AccountControlUiOriginalOrderFixture.java | 16 +- .../AccountControlUiOwnerSourcesFixture.java | 5 +- .../AccountControlUiSignerFixture.java | 4 +- ...ccountStartSessionReservationProofPki.java | 346 +++ .../GameDesignPublicationTerminalClient.java | 14 +- ...AccountSelectedPublicationOrderClient.java | 139 ++ ...ntSelectedPublicationOrderCredentials.java | 113 + ...ountSelectedPublicationOrderGrpcCodec.java | 152 ++ ...ntSelectedPublicationSettlementClient.java | 160 ++ ...electedPublicationSettlementGrpcCodec.java | 246 +++ ...ublicationTerminalCompletionGrpcCodec.java | 4 + ...electedOwnerIntakeClientLifecycleTest.java | 40 +- .../common/gamedesign/AssetSourceTest.java | 270 +++ .../CommandDefinitionClosedFieldsTest.java | 97 + ...untSelectedPublicationOrderClientTest.java | 158 ++ ...lectedPublicationOrderCredentialsTest.java | 99 + ...SelectedPublicationOrderGrpcCodecTest.java | 112 + ...lectedPublicationSettlementClientTest.java | 376 ++++ ...tedPublicationSettlementGrpcCodecTest.java | 240 ++ ...licationTerminalClientTransactionTest.java | 93 + ...nPublicationTerminalReadGrpcCodecTest.java | 172 ++ ...cationTerminalCompletionGrpcCodecTest.java | 37 + ...ectedDraftPublicationAdmissionService.java | 339 +++ ...nerPublicationPostgresIntegrationTest.java | 1958 +++++++++++++---- ...leaseCanonicalIdentityIntegrationTest.java | 296 +++ .../publication/AssetSnapshotTest.java | 101 + .../RealmPolicySourceRetentionTest.java | 129 ++ .../publication/GameplayRuleSourceTest.java | 412 ++++ ...dDraftPublicationAdmissionServiceTest.java | 675 ++++++ ...ationOwnerCompositionCrossServiceTest.java | 39 +- ...electedFullPublicationEvidenceFixture.java | 155 +- ...tedFullPublicationEvidenceFixtureTest.java | 21 +- 73 files changed, 13878 insertions(+), 793 deletions(-) create mode 100644 protos/account/v1/selected_publication_order_service.proto create mode 100644 protos/account/v1/selected_publication_settlement_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java create mode 100644 services/account-service/src/main/resources/db/migration/V1011__selected_publication_closure_inventory.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandDefinitionClosedFieldsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRetentionTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java diff --git a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md index 0048d2555f..24b45510ab 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -39,6 +39,37 @@ The current dry-run and readiness capacity reservations also are not idempotent The current queue consumer has an additional bounded-drain limitation that must remain explicit: `drainWorkItems` and `drainIndexedWorkItemPointers` consume pointers with atomic Redis `LPOP`, so a producer's concurrent `RPUSH` is not discarded by a range/read followed by deletion. The indexed path still uses database-wide `KEYS("automation:queue:*")`, and the current lists have no pointer TTL or maximum-length bound, so the path is not a cluster-safe discovery or retention proof. Durable claim fallback can process pending PostgreSQL rows independently, but it does not establish a reset/rebuild recovery gate. Target enqueue/rebuild must atomically apply `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`, preserve or durably account for unreturned tails and concurrent appends, use an owner-maintained/cursor-based cluster-safe queue index rather than database-wide `KEYS`, and trigger bounded durable re-drive with exact identity/readback before reset-gate release. The two settings remain environment/service configuration (currently `TBD`); no target support claim is valid until each environment supplies validated positive bounds and focused concurrent-drain, truncation/expiry, cluster, and re-drive proof. +The selected-source terminal reader and Account settlement composition are standalone and unregistered construction components; they do not establish complete authenticated owner intake or physical proof. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) owns their code and validation status. Without the exact committed Account settlement, finalized source participation remains pending. + +## Authored Template Source Inventory + +Automation owns the source inventory declaration schema carried as authored content by a new versioned Game Design `TEMPLATE_CONFIG` source ([closed schema and reference rules](../game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state)). The Automation value schema is `automation-authored-source-inventory/v1` with exactly three required family arrays: `SCRIPT_DEFINITIONS`, `EVENT_BINDINGS`, and `SCRIPT_PATCH_SOURCES`. The current shared value accepts only explicitly authored empty arrays; omitted, null, unknown, malformed, duplicate, trailing, oversized, or nonempty input is rejected. Its canonical RFC 8785 bytes preserve the authored declaration deterministically. This declaration is content only: it is not an owner receipt, source readback, authorization, provenance, or proof of owner completeness, and cannot qualify a publication on its own. Existing `TEMPLATE_CONFIG` schema-version content is not reinterpreted as this declaration. + +The authored shape is: + +```json +{ + "schema": "automation-authored-source-inventory/v1", + "families": { + "SCRIPT_DEFINITIONS": [], + "EVENT_BINDINGS": [], + "SCRIPT_PATCH_SOURCES": [] + } +} +``` + +Script schedule definitions remain derived from script source and are not another authored family. The optional template `automation.scriptPatch` is a separate default selection of one exact patch for the same base version; its absence means no template default and does not establish an empty patch-source inventory. The declaration producer, full owner census/retention and Account terminal-settlement composition remain incomplete; the standalone terminal reader does not register or enable intake. Publication must continue to deny where complete authenticated owner evidence or physical proof is unavailable. + +An Automation selected-source intake is a distinct Account-authorized operation, not participation inferred from a Game Design-only commit. Account must first authorize the exact immutable source read; after the read, Automation must retain the original content and outcome while holding revalidated current Account authority through its local commit. The declaration must originate in a genuine authored revision of the exact selected Game Design commit. Its inventory covers script roots, every event binding and patch source, and all dependent or inbound behavior/hook references from the complete selected World and other authored inputs. An explicit empty declaration is supported only when authenticated owner evidence closes that whole selected input set and rejects conflicting or unqualified existing content. Missing producers, omitted families, unavailable rows and a tenant-wide script query are not absence proof; an unsupported nonempty input denies instead of being discarded. + +The immutable intake result retains the canonical tenant/version and selected commit, original source revision and operation, complete inventory bytes, exact Account authorization binding, original owner terminal and their digests. The result and authenticated readback are derived after the authored source commit, outside its preimage. An identical retry reads the original result; changed scope, selection, content or authorization binding conflicts rather than manufacturing a new receipt. A workload identity, creator declaration or matching digest alone is insufficient. Until the required selected-input producers and continuously held-authority proof exist, the Automation receipt cannot qualify publication, which must not substitute an empty or synthetic version marker. + +The separate [`AutomationSelectedSourceIntakeCommandService.RetainSelectedSource`](../../../../protos/automation-scripting/v1/automation_selected_source_intake_command.proto) supplies a closed schema-version-1 retention command without changing those owner checks. The receiver authenticates the exact Game Design workload against its configured namespace before decoding and rejects authenticated caller context and ambient original-Draft-order, Game Logic intake or selected-owner authorization-producer credentials. It separately denies a mismatched request namespace or ambient SQL/synchronization. Its request binds an independent nonzero transport correlation, complete original Account Automation-retention authorization bytes/digest, and the original World freeze request and acknowledgement through their existing codecs. The complete selected Draft, canonical tenant/version and namespace must agree across those bindings; original operation, fence, intake and applicable freeze identities cannot be reused as transport correlation. Success echoes the entire request and returns only the complete canonical `COMMITTED_EMPTY` receipt and digest. Changing only the transport correlation replays the same owner receipt, not another intake. The request wire bound is the 16 MiB authorization bound plus both existing 1 MiB World Account-binding bounds and 64 KiB; the response bound adds the unchanged Automation receipt bound and another 64 KiB. These wire budgets do not expand any embedded grammar or byte limit. The workload-only file-backed mTLS client pins Automation, applies a five-second deadline and rejects ambient SQL/synchronization before transport. This standalone command remains unregistered and grants no publication, source release, admission or runtime activation. + +Automation's terminal read is a separate schema-version-1 `AUTOMATION_INTAKE_TERMINAL_READ` request, authenticated only for the exact same-namespace Account mTLS peer. It carries a fresh read correlation distinct from the original operation, fence and intake request, plus the complete original authorization binding bytes and digest. The only positive terminal is the typed `COMMITTED_EMPTY` outcome, with the complete canonical immutable Automation receipt bytes and recomputed digest; an exact retry returns that same receipt even when the read correlation changes. Missing, pending, changed, corrupt or ambiguous evidence denies and is never interpreted as absence, abort or release authority. Account's settlement consequence is defined by its [selected-owner intake contract](../account-service/api-contracts.md#grpc-apis) and must preserve the same original operation under its existing source locks. + +Publication consumes this empty-only receipt only within the [canonical selected-full profile](../game-design-service/version-control.md#selected-full-publication-profile), with the original publication request/freeze binding and independent exact recipient readback. The immutable receipt and closed transport definitions do not enable arbitrary nonempty Automation source, produce genuine Account authorization, establish continuous currentness or register a runtime command. The [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation) retains the implementation and controlled-proof limits. + ## Architecture and Design Notes - Executes scripts in response to world or player events received via gRPC callbacks from Game Session and other domain services. Standard lifecycle events (`onSpawn`, `onEnterRegion`, `onCommand`, and similar) are delivered as unary gRPC calls via `TriggerScriptEvent`, while tick-derived scheduling signals are driven by a gRPC streaming tick heartbeat originating from Game Session. diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index f9812c20b9..ab5fe9f0f1 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -8,14 +8,14 @@ The prepared selected gameplay-rule intake repository, terminal owner and public The sections below define the target-state runtime contract. Current implementation and proof status is: -- The current implementation attests an empty owned-rule manifest and returns synthetic `appliedCommitId = "version:"` because Game Logic does not yet own version-scoped draft rule tables. The empty-manifest digest is intentional and does not represent hidden service state. +- The default Spring digest composition denies full-version reads because its retained publication source reader is not configured. An explicitly composed reader can validate exact retained intake evidence; missing source or receipt never produces an empty-manifest fallback or synthetic `version:` commit. This does not register or enable publication. The [selected intake tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) and [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation) retain detailed execution attribution and remaining proof limits. - Same-type Game Logic takeover behind an existing edge connection is target behavior, but suppression of a client-visible reconnect after an ordinary qualifying Game Logic restart remains implementation or proof debt under ADR 0013. - Target: `SendCommunication` and every other player-delegated gameplay RPC propagate one complete, validated typed `PlayerExecutionContext` from Game Session through Game Logic and onward. Game Logic validates the context against request and owner evidence, never treats caller-supplied identifiers as authority, remains stateless, and owns semantic gameplay outcomes; Game Session owns session, reconnect, and presentation state. This is the ADR 0024 target contract. - Current implementation gap: the live `SendCommunicationRequest` is still a flat schema with tenant/session/character/account, communication/text and target metadata, room, game-instance, speaker, and effect fields plus legacy `session_attestation`; its current proto does not carry typed `playableStateNamespaceId`, `playableStateScope`, region/epoch, pointer, or admitted-bundle fields. Complete typed-context propagation is therefore not current behavior or proof. ## Runtime Notes -- Stateless service accessed over gRPC by other microservices. +- Stateless gameplay execution accessed over gRPC by other microservices; immutable authored-source intake evidence is durable owner storage, not process-local player or session state. - No authoritative gameplay state may exist only in Game Logic process memory. Any state that must survive instance loss belongs in authoritative domain services, durable ledgers, or Game Session-owned coordination, so another Game Logic instance can take over immediately. - Same-type Game Logic instances must be freely replaceable behind the current caller connection. Meaningful gameplay state needed after a non-edge restart must be reconstructed from authoritative service APIs and Game Session-provided tick/session context rather than preserved only in local memory. - Uses a modular command parser for extensibility. The text protocol's system commands such as `LOGIN`, `LOGON`, and `PING` are interpreted and completed by Game Session; this service focuses on gameplay commands only, as described in the [Game Session Service](../game-session-service/protocols.md#minimal-text-command-protocol). @@ -34,21 +34,70 @@ The sections below define the target-state runtime contract. Current implementat The Game Logic Service does not orchestrate or own synchronous saga or Temporal workflows. All gameplay commands execute inside ticks using Redis-based rollback and the transaction model described in [Transaction Strategies](../../system-architecture-transactions.md). -When a game version is published, its rule data is prepared and finalized by the Game Design and Game Session services; this service reads the already-published, versioned rule data for the active `runtime_version` and does not participate directly in the durable `publish` workflow. +Before the publication digest gate, Game Design supplies authored inputs through the separate authenticated intake below, and Game Logic validates and immutably retains that exact selection. Publication reads the retained evidence without creating or repairing it. Game Session owns runtime orchestration; it does not replace Game Logic's rule-input retention authority. Runtime consumption is limited to the published, pinned release for the active `runtime_version`. Role classification: Game Logic is a digest-gate participant for full publishes, not a workflow-step participant, unless future publish workflows add explicit finalize or compensation steps owned by this service. ## Draft Digest Contract -For full-version publish gating, this service is still a required digest participant even though it does not orchestrate publish-workflow steps. It must expose `GetDraftDesignDigest(tenantId, versionId)` and publish a service-local digest input manifest with: +For full-version publish gating, this service is still a required digest participant even though it does not orchestrate publish-workflow steps. Its authenticated `GetDraftDesignDigest` read binds the publication request and exact retained selection below, rather than selecting content by tenant and version alone, and publishes a service-local digest input manifest with: -- included objects such as version-scoped rule and configuration tables this service owns that affect runtime command behavior; +- included objects and source ownership for the complete effective, version-scoped set of supported command inputs that affect runtime command behavior; - excluded objects such as runtime queues, caches, telemetry tables, and other non-launchability data; - canonicalization rules covering stable ordering, normalization, and null or default handling before hashing; and - `digestSchemaVersion` bump criteria, where any include, exclude, or canonicalization change requires an explicit schema bump and replay or re-record workflow. Publish gating must fail closed if this service cannot attest a digest under its documented manifest for the reported `digestSchemaVersion`. +### Selected-Release Rule Inputs and Intake + +This is the Game Logic owner contract under the canonical [selected-full publication profile](../game-design-service/version-control.md#selected-full-publication-profile). It defines required target behavior; the implementation-status section and linked trackers describe what is implemented or proved. + +Game Design remains the authoring and revision-history owner for authored gameplay rule inputs. Game Logic owns validation and immutable retention of the selected release's rule-input evidence, and attests only the exact selected tenant, version, and applied commit received through an authenticated, operation-bound source operation. A workload identity by itself does not authorize that mutation; the current authority and the source operation's mutation authorization must remain bound through commit. The producer handoff and retained manifest are target behavior and are not established by the current digest receiver. + +The retained input set must be complete for the supported command inputs effective in that version. It includes supported ability and action definitions and the referenced actor-state, resource, condition, and effect catalogs; command and action metadata including admission tags; disposition and continuous-overlay policy; observation, targeting, target-selection, and default target-set bindings; and cost, cooldown, feedback, or lifecycle declarations when they are part of the selected authoritative source. The authoring shapes and ownership remain defined by [Ability & Action Design Tools](../game-design-service/ability-action-tools.md) and the owning domain contracts. This list defines the completeness boundary, not a new wire schema or an additional execution engine. Unknown or unsupported authored inputs make intake and attestation fail closed; they must not be filtered out to produce an apparently empty or partial manifest. + +Intake is a separate, mutation-authorized source operation. `GetDraftDesignDigest` remains a read-only full-version publication read over the already retained, exact-version evidence; it does not populate or repair that evidence. An empty selected input set is attestable only when an authenticated source operation proves the complete owner inventory for the exact selected commit is empty. Missing storage, a missing producer, or absent rows are not evidence of an empty authored set. + +The content-selection binding is distinct from the unchanged `publicationDigestRequest/v1` authorization/replay context. Its `game-logic-publication-source-read/v1` preimage consists of exactly three unsigned canonical ASCII byte-length frames, in order: the UTF-8 schema name, the exact existing publication request canonical preimage, and the complete original finalized Account Game Logic intake authorization bytes retained by Game Design's immutable selected receipt. Lengths use canonical decimal digits followed by `:` and exactly that many bytes; missing, extra, trailing or noncanonical frames deny. Segment and total limits, including framing and transport overhead, must be enforced before allocation. Hash the exact bytes using the existing SHA-256 representation and freeze executable preimage/hash vectors. This binding selects content; it creates no read or mutation authority and does not reinterpret the shared publication schema. + +Game Design derives that binding only from its immutable selected receipt, never from caller-selected historical authorization or latest state. Game Logic authenticates the exact Game Design workload and publication method before decoding, independently validates both bindings, then reads the exact genuine retained intake operation and its successful terminal. The complete authorization, canonical tenant/version, selected commit and source must agree byte-for-byte with retained owner evidence. Authorization bytes and digest alone prove neither Account issuance nor successful retention. The numeric Game Design Version row in the unchanged publication scope must agree with the original selected binding's persisted target; retain its canonical UUID and source-row provenance rather than inventing a UUID/numeric alias. + +The response binds the complete original lookup, source and commit provenance, positive participant schema/canonicalization evidence, aggregate digest and dedicated ability-schema digest. Game Design exact-checks each before recording an attestation. Missing or mismatched retained evidence denies; there is no tenant/version-only or latest fallback, read-side repair, fresh mutation reauthorization of historical intake, or reuse of the Account-only terminal-read permission for Game Design. Game Logic is not a script-patch participant. This selection plumbing does not establish complete source/settlement or final release-attestation proof; current construction and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + +The original Game Design author operation settles before this intake. Game Logic obtains the complete synchronized source from Game Design's authenticated exact-commit owner read and verifies a distinct [Account intake authorization](../account-service/api-contracts.md#grpc-apis) for that same immutable source. That exact finalized authorization also accompanies its [operation-authorized source read](../game-design-service/api-contracts.md#operation-authorized-gameplay-source-read); Game Logic cannot reuse Account's preliminary read-only branch or omit independent Account readback. It does not retrospectively join the original Draft's participant vector or allocate another selected commit. Account source participation remains held through Game Logic's local commit and exact terminal settlement; a remote `HELD` sample alone is insufficient. Retained source, complete manifest/provenance and the immutable intake result commit atomically. A definitive abort uses the same operation serialization and prevents later retention; missing rows or expired waits do not prove abort. Identical recovery returns the original result, never a latest source or replacement manifest. These obligations do not make Game Logic a publication-workflow mutation participant. + +The standalone [`RetainGameplayRuleIntake`](../../../../protos/game-logic/v1/gameplay_rule_intake_service.proto) transport admits only verified same-namespace Game Design, authenticated before decoding. It invokes the existing distinct-order intake, not publication authorization. Exact namespace, independent transport correlation and complete original authorization bytes/digest are echoed with the immutable original terminal; both retained and definitive-abort retries preserve their original outcome. The client verifies Game Logic's workload and exact response binding. Game Design obtains the subsequent settlement receipt through the [Account-owned settlement transport](../account-service/api-contracts.md#grpc-apis), never by calling the Account-only terminal reader. Intake and terminal adapters remain standalone and unregistered; their existence does not establish a genuine authorization producer or publication completion. The intake owner rejects the canonical original Draft and Game Logic intake-authorization credential contexts; those creator credentials do not accompany the owner-to-owner intake. Player or operator context supplies no intake mutation authority. + +The authenticated publication read must preserve the exact source-operation and selected-commit correlation through its retained-manifest lookup and readback. Validating the publication request and then resolving content by tenant/version alone is insufficient when it can select a different source operation; neither a latest lookup nor request authentication repairs missing immutable provenance. + +The full-version manifest and the dedicated `abilitySchemaDigest` share the selected commit and Game Logic's existing canonicalization and `digestSchemaVersion` contract, but they attest distinct scopes. The aggregate full-manifest `contentDigest` is not an ability-schema digest, and neither the Automation & Scripting digest nor Game Design's control-plane digest substitutes for either Game Logic attestation. Any change to the dedicated ability-schema input set or its canonicalization requires the same explicit schema bump and digest replay or re-record process as other manifest changes. This contract governs publication evidence only; it does not authorize activation of unpublished rules or make Game Logic a participant in Game Design's publication workflow mutations. Game Logic does not read an admin database for runtime rules. + +### Dedicated Ability-Schema Projection v1 + +The dedicated content preimage is RFC 8785 canonical UTF-8 JSON with exactly `{"schema":"gameplay-ability-schema/v1","families":{...}}`. `families` contains all 15 names in the closed `gameplay-rule-manifest/v1` grammar, including explicit empty arrays. Validate the complete selected manifest before projecting: unknown fields or definitions, missing families, unresolved references and unsupported shapes fail even outside the selected closure. Seed every `ABILITIES` and every `ACTIONS` definition, then retain the complete typed-reference closure keyed by `(family, logical key)`. Preserve every field of each retained definition, its original selected-manifest family order, and every nested-array order. A visited set terminates reachable cycles while retaining all reachable definitions; this does not establish execution support for an otherwise unsupported cycle. + +The closed grammar's reference edges are exhaustive: + +| Definition family | Typed reference edges | +| --- | --- | +| `ABILITIES` | `actionSequenceId` → `ACTIONS`. | +| `ACTIONS` | `admissionTags` → `ADMISSION_TAGS`; target sets → targeting/selection policies and optional unresolved feedback; costs → `RESOURCES`; effect bindings → `EFFECTS`; `feedbackKeys` → `FEEDBACK`. | +| `CONDITIONS` | `effectKeys` → `EFFECTS`. | +| `EFFECTS` | `statKey` → declared numeric `STATS` or `RESOURCES`; `ADJUST_RESOURCE` and `MAXIMUM` require `RESOURCES`; `conditionKey` → `CONDITIONS`. | +| `OBSERVATION_POLICIES` | Predicate references below. | +| `TARGETING_POLICIES` | `observationPolicyKey` → `OBSERVATION_POLICIES`; eligibility predicate references; `safeFailureFeedbackKey` → `FEEDBACK`. | +| `SELECTION_POLICIES` | Comparator `statKey` → numeric `STATS` or `RESOURCES`; `MAXIMUM` requires `RESOURCES`. | +| `DISPOSITIONS` | `deniedAdmissionTags` → `ADMISSION_TAGS`; `safeFeedbackKey` → `FEEDBACK`. | +| `COMMANDS` | `actionSequenceId` → `ACTIONS`; `admissionTags` → `ADMISSION_TAGS`; commands are not roots or reverse dependencies. | +| `CONTINUOUS_OVERLAYS` | Eligibility predicate references; `deniedAdmissionTags` → `ADMISSION_TAGS`; `effectKeys` → `EFFECTS`. | +| `DEFAULT_BINDINGS` | Target sets → targeting/selection policies and optional unresolved feedback. | +| `STATS`, `RESOURCES`, `ADMISSION_TAGS`, `FEEDBACK` | No external definition references. Their complete fields, tags and feedback arguments remain retained when reached. | + +Target-set policy fields are `targetingPolicyKey` → `TARGETING_POLICIES`, `targetSelectionPolicyKey` → `SELECTION_POLICIES`, and non-null `unresolvedFeedbackKey` → `FEEDBACK`. Predicate operands are traversed recursively: `STAT_COMPARE.factKey` selects its declared numeric stat/resource; `CONDITION_PRESENT.factKey` → `CONDITIONS`; `DISPOSITION_EQUALS.factKey` → `DISPOSITIONS`. `SOURCE` and declared target-set keys are action-local, not catalog aliases. Cooldown keys, names, tags, player-selector slots and feedback argument/message identifiers create no guessed external edges. The closed grammar rejects stat/resource key collisions before resolving a numeric reference. Unreferenced catalogs, commands, overlays and default bindings stay outside this dedicated digest, while remaining in the aggregate manifest. An effective implicit runtime dependency not expressible by this grammar must be reported and denied, not silently omitted or guessed from names. + +Hash these exact bytes with the existing lowercase `sha256:` encoding. Carry the positive participant `digestSchemaVersion`, canonicalization evidence and exact selected-commit/source-operation provenance separately; source/auth receipts, publication metadata and commit IDs never enter this content-only preimage. A valid explicit-empty manifest has a defined content hash but cannot establish authenticated empty-source provenance: the original complete owner inventory and immutable intake must independently prove it. The executable [projection vectors](../../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java) freeze empty preimage/hash `sha256:0207783645e944996b4f7589d2662d5b8309231769681e162ee05de51d34db2a` and the complete two-action/all-root preimage/hash `sha256:659a321a8fd1a02a4825a81568d67dee5039a1cb538756fb91c212aeaea1c536`, plus transitive-field, ordering, unrelated-input and negative cases. Any include/exclude, edge or canonicalization change requires the existing explicit schema bump and replay/re-record process; do not reinterpret retained evidence. Projection construction alone does not register the digest receiver, authorize publication or activate gameplay. + ## Redis Role and Prefixes ### Coordination Redis diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a26991937f..a1bec92aec 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -123,12 +123,50 @@ Entry format: - 2026-10-15: Selected-full digest fixture R41/R42 produced different fixed-golden values from otherwise unchanged source. The fixture serialized `Map.of` payloads into strings inside a canonical binding; outer canonicalization preserves string contents and therefore does not normalize the inner map order. Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof. No production digest or retained bytes were changed. R44 and the fresh R45 JVM agree on the normalized vector; all 686 GDS unit cases pass in R45. +- 2026-10-15: Separate selected-publication owner proofs missed an Account settlement profile gap. The actual GDS terminal → authenticated World completion → both real terminal reads composition reached Account V94 and failed with SQLSTATE 23514 because its inventory validator still admitted only inventory/1 + World/3, while the current canonical producer retains closure inventory/2 + World/4. Preserve that failed composition beside prior component passes; a forward validator correction needs exact profile/refusal and existing-settlement byte/row-version upgrade proof. Do not rewrite installed migrations or treat controlled terminal readbacks as actual producer composition. Correction and qualification are in progress. + +- 2026-10-15 follow-up: Account's forward V1011 now converges the exact inventory/1 + World/3 and closure inventory/2 + World/4 validation profiles while retaining the original framing, digest, source and artifact guards. R14 passes the actual six-store terminal-to-settlement composition and nine malformed-profile refusals; R16 passes original PUBLISHED and NO_PUBLICATION settlement upgrade/replay with unchanged stored bytes and row versions. A test-only V1010 predecessor allowlist omission was corrected separately. These controlled component proofs supply no genuine creator, issuer, environment or deployed authority. + - `2026-10-15`: Preserve receiver status when relocating inherited tracker proof - Context: the local #3224 parent reconciliation relocated inherited LOGIN proof into a dedicated section. Selecting the complete incoming tracker plus one receiver proof paragraph also displaced the receiver's first-party denial and historical-proof qualifications. The candidate had not been published. - Observation: verifying nonoverlapping blobs and paragraphs unique against the merge base missed receiver status that also appeared in the base. Main later compared the complete receiver document, restored every original receiver paragraph byte-for-byte, and retained the incoming concise status and relocated proof. No production source changed. - Expected pattern: inspect the complete overlap against the receiver's current contract and status, including text shared with the merge base. Proof relocation alone does not authorize replacing unrelated current-status sections with an earlier parent's view. - Reconsideration trigger: a native reconciliation check proves preservation across moved paragraphs and status replacements; ordinary clean merges and nonoverlap comparisons do not establish that property. +- `2026-10-16`: Keep FireController briefs within the size limit + - Context: FireController job briefs are capped at 200,000 characters. + - Observation: Repeatedly prepending completed and running checkpoints caused a revision to be rejected before the active execution state could be saved. + - Expected pattern: Archive the full previous brief, retain standing instructions and superseding decisions, replace the active execution section, and put milestones in native updates/checkpoints. Consolidation restored guarded updates without losing source history or standing authority. + +- `2026-10-16`: Keep the original Logging claim-read client workload-only + - Context: A generic gRPC channel and stub customizer did not establish the original Logging claim-read client's workload-only boundary: the common customizer attaches bearer metadata, and a trusted TLS channel alone does not pin the expected SPIFFE workload. + - Observation: The corrected client uses the existing Common peer credentials and response verifier, preserves default-off composition, and rejects ambient SQL, synchronization and caller context before RPC. Controlled loopback mTLS and the existing native owner consumer now prove this bounded behavior; they do not establish genuine upstream authority. + - Expected pattern: Keep the configured server identity separate from mutation target data, and follow canonical usable TLS-material policy rather than copying a donor's regular-file predicate. +- `2026-10-16`: Bound subprocess output and waits in the original claim-read test PKI fixture + - Context: Reading subprocess output to EOF before a timed wait leaves the supposed deadline unbounded. + - Observation: The original claim-read test PKI helper now redirects output to an owned temporary file, waits before reading it, and terminates/reaps a timed-out or interrupted child with interrupt preservation. Actual stalled-keytool timeout and interruption cases pass alongside the affected TLS and native owner proofs. + - Expected pattern: Keep this correction in the purpose-specific fixture; it does not require a general command framework or change production TLS material policy. + +- `2026-10-16`: Recheck original ControlUI expiry after owner locks + - Context: An initial ControlUI token expiry check became stale across later owner locks in both current-actor paths. Registry cleanup retention and authorization-reference expiry did not replace the original token's validity boundary. + - Observation: The focused native fixture advances the existing actor clock at the real locking read: the old code entered both callbacks after expiry; the correction rejects them without changing the original row while preserving exact held-order recovery. + - Expected pattern: Keep current authorization and historical recovery distinct when reconciling displaced guards. + +- `2026-10-16`: Compare the complete original validity interval at one owner boundary + - Context: original creator callbacks can wait for Account owner locks after initial token verification. + - Observation: an expiry-only final check misses a clock observation before the original not-before bound; registry cleanup retention and authorization-reference expiry do not define the original token's full interval. + - Expected pattern: use one existing-clock observation for the canonical original `issuedAt <= now < expiresAt` interval, test both denial bounds and exact lower-bound equality, preserve immutable evidence, and keep historical exact-order recovery separate from fresh authorization. + +- `2026-10-16`: Separate original signer provenance from present public-key acceptance + - Context: fresh signed and committed-JTI creator callbacks must retain their original key identity. + - Observation: an immutable source pin, historical committed-signer receipt and still-fresh signature cache do not independently establish that the original key remains in the current protected public snapshot. + - Expected pattern: load the existing trusted source outside SQL and synchronization, compare the original key ID and RFC 7638 fingerprint, preserve accepted retiring-key membership and historical exact recovery, and state the per-invocation snapshot limit beside the proof. + +- `2026-10-16`: Bound child waits in standalone receiver PKI fixtures + - Context: The standalone activation and World participation receiver PKI fixtures had the same output-before-wait pattern, leaving child execution unbounded. + - Observation: Both use the existing purpose-specific bounded-child pattern; four actual stalled-JDK-child timeout/interruption cases and all eight consuming receiver cases pass. + - Expected pattern: Compare each remaining fixture owner independently; an earlier Logging fixture pass does not prove these locations, and controlled socket proof does not establish real Account settlement or genuine PKI. + - `2026-10-16`: Check both public mapping directions when an internal read requires an identity distinct from its original operation. The launch-association receiver retained that guard while a refactor removed it from the request encoder; the receiver's refusal did not constrain local encoding. A producer refusal assertion reproduced the omission at `653c42cea1`, and restoring the existing encoder guard passed the full 917-case Common gate at `cefbf09ebb`. Keep the transport identity rule at both boundaries and distinguish local codec proof from controlled socket responses or genuine owner authority. - `2026-10-16`: Report source validation separately from packaged smoke diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index e660a8a9d1..c020cf65c6 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,32 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +### Selected publication reservation preparation + +The unregistered reservation adapter independently reads the retained selection, exact Account HELD evidence, World freeze/inventory/selector and original World source/delivery before the existing local reservation transaction. The coherent continuation supplies Account's selected-publication producer, HELD read, typed order transport and exact terminal-settlement owner. Current terminal clients and binding guards remain authoritative; no parallel terminal codec is introduced. The ten GDS ordering/refusal units, twenty-five Account owner units and seven Common typed-order units pass with their original focused attribution. + +R14 freshly passes eleven Account native cases and the extended six-store Full composition with zero failures, errors or skips in those cases. The composition uses the actual Account store and normal Redis issuance fixture, authenticated Account HELD and World committed-freeze replay/read endpoints before real GDS admission/reservation and exact retry. The original GDS delivery intake identity is preserved through World application; mutable World retry readers are asserted unused. The atomic v4 bundle/terminal commit and immutable readback still execute. The actual Game Design terminal receiver, authenticated Game Design-to-World completion producer and World's independent Game Design terminal read then supply both real terminal owners to Account settlement. Settlement before World completion refuses without a receipt; successful settlement and exact retry preserve the original terminal bytes, receipt and row version. Nine direct malformed closure/profile mutations are refused by Account SQL. The local inbound Account caller context is explicitly controlled; its two outbound terminal reads execute real mTLS. Passive capture owns all eight run-created PostgreSQL containers without gaps or observer errors. + +The composed proof exposed Account V94's obsolete inventory profile. Forward V1011 converges the validator to the same exact legacy inventory/1 + World/3 and explicit closure inventory/2 + World/4 pairs already owned by Game Design and World. All remaining frame, digest, source, artifact, selected-commit and owner-correlation guards remain enforced; installed migrations and retained rows are unchanged. R14's sole failure was the new historical fixture's unsupported V1010 target. After adding that exact test-only predecessor, R16 freshly passes the V1010-to-current upgrade and replay case for both original terminal outcomes, retaining authorization, source, settlement, issuer and prior Flyway rows including row versions. Scoped generation, compilation, static analysis, formatting and documentation checks pass; the other native cases retain R14 attribution. + +FreshBeginR3 freshly passes the same six-store composition with a fresh authenticated World begin, rather than a fixture-created freeze. World starts with its owner OPEN and no attempt, Account correlation, inventory or canonical frozen capture. Actual Game Design selection and source-qualified Version handlers and Account HELD are called over mTLS. A controlled Account transport outage refuses before World effects, preserving all five owner tables including row versions; enabling the real read creates the exact FROZEN checkpoint, Account correlation, complete inventory and selector capture. An exact begin retry succeeds with both mutable upstream transports denied and without repeating any owner reads or changing retained rows. The World fixture now only reads the independently committed result. The later actual reservation, v4 bundle and terminal-to-Account settlement still pass in that same fresh native case. FreshBeginR3 has zero failures, errors or skips; all six run-owned PostgreSQL containers are passively identified without ownership gaps or observer errors. Compilation, scoped static analysis, formatting and documentation checks pass. + +ActualOrderR2 freshly passes that same native composition after replacing the directly invoked Account producer with the real selected-order transport. Game Design calls the actual Account receiver with the original creator credential; Account independently authenticates the actual retained Game Design selection through its existing owner client before its local producer transaction. A controlled Game Design transport outage preserves Account authorization, source, settlement and issuer rows including row versions. Successful ordering creates one original held order from the single committed creator issuance; exact retry rereads the real selection, returns identical original binding bytes and preserves retained rows. That returned binding drives the fresh World begin and later actual publication and settlement. The case has zero failures, errors or skips, with all six run-created PostgreSQL containers passively owned without gaps or observer errors. Scoped compilation, static analysis and formatting pass. These are actual component transports with controlled upstream creator, issuer, environment and PKI; the public-finalizer/currentness/recovery holds remain unchanged. + +Original World source/version registration and APPLIED input remain controlled fixture preparation. Upstream creator, issuer, environment, PKI and other declared source/candidate inputs remain controlled. These components remain unregistered and do not supply accepted through-commit production authority, failed-selection recovery, a reachable publication finalizer or a production entrypoint. Fresh/PENDING publication and runtime authority remain denied. All genuine Gameplay handoffs remain open. The complete boundary is assigned to Gameplay's existing receiving PR, with no additional extraction PR. + +### Selected publication settlement transport receiving + +The canonical source continuation also preserves the donor's unique asset requiredness, identity, canonical payload, command closed-field, gameplay catalog/reference and realm-policy provenance regressions at their current owners. Terminal-read request and response refusal vectors use the current framed grammar, including explicit UNKNOWN, complete request echo, malformed or substituted terminal rejection and defensive original bytes. These structural and owner-local units use controlled values; they do not establish original authority, production activation or genuine physical handoffs. + +Current Account settlement and World terminal-completion requests require the complete v2 operation tag before owner access. The shared decoder preserves historical v1 operation and terminal bytes for history reads; that support does not widen either current transport contract. Both codecs reject the historical profile from direct request construction and protobuf decoding, following the existing rule that retained history does not widen consumers that lack older-profile support. + +The selected Account order, held-read and settlement clients, Game Design selection and terminal-read clients, and World terminal-read client release their local monitor before the shared certificate watcher drains an in-flight reload callback. Their close flags still deny reuse; the existing selected-owner lifecycle matrix covers callback contention, idempotent shutdown and closed-client initialization denial. + +The canonical Game Design publication terminal client retains the original donor's local transaction exclusion: active owner SQL and synchronization-only contexts fail before transport access. This guard stays on the current closed framed terminal-read API; the alternate donor client, evidence type and service are not reintroduced. + +The current-carrier continuation retains the standalone, unregistered Account selected-publication settlement receiver, explicit file-backed mTLS client and closed request/receipt codec from the preserved #3105 donor. Account still derives settlement from its two independent authenticated Game Design and World owner reads; the caller supplies only the complete original operation and transport correlation. The codec validates the unchanged six-frame receipt, exact operation and owner terminal/outcome agreement within the serialized wire bound. The selected full-owner fixture now invokes this actual Account receiver over loopback mTLS, requires a World workload caller to be denied, retains no settlement before World completion and checks unchanged receipt bytes and row metadata on retry. Original creator/issuer/environment, source provenance, selected inputs and ephemeral PKI remain controlled. No production service registration, migration, activation or genuine Gameplay handoff is established. + ### Gameplay source catalog and legacy handoff proof The existing Game Design gameplay source PostgreSQL owner test now retains a nonempty action, ability, effect, resource and admission-tag catalog beside an ordinary asset in one owner outcome. Exact retry and independent repository reads preserve the original source bytes. A disjoint asset change inherits the gameplay epoch and original binding; explicit ability and action deletion advances the gameplay epoch while preserving the prior snapshot. Additional cases deny legacy effective commands and generic gameplay-rule history before or after the typed snapshot, including an explicitly emptied rule inventory. Generic history under a different private tenant or Version does not contaminate the exact selected source. @@ -24,6 +50,12 @@ The restored Version identity native owner test preserves the original retained All six native cases freshly pass with zero failures, errors or skips against the canonical PostgreSQL image and owning filesystem migrations. Canonical formatting, style, Integration Checkstyle and SpotBugs pass; passive capture identifies the one run-owned PostgreSQL container and independently confirms its absence after completion. This proves owner-local identity and historical retention mechanics with controlled setup. It does not establish creator or issuer authority, currentness, publication enablement, an immutable production release, activation or a genuine Gameplay handoff. No production, installed migration or registration changes are included. +### Selected-full release profile and exact retry storage proof + +Three further native cases use the current test fixture's schema-4 World input from its first construction, actual Game Design source inheritance, reviewed policy, selection, source captures and local publication storage. Direct SQL rejects an incorrect digest schema independently for each of the five participant owners, without creating a bundle or changing the original Game and Version rows or their row versions. A valid v4 bundle retains its original World and participant bytes on independent read and exact retry; changed generation configuration refuses without changing the complete bundle row or its row version. Two concurrent exact storage calls return the same single retained bundle, followed by another unchanged-row retry. Their start latch establishes submitted calls and outcomes; it does not independently measure precommit blocking. A separate SQL case refuses missing selectors, malformed text or numeric epochs, changed request bindings, missing opaque evidence and empty or changed participants, preserving the original Game and Version rows and their row versions without creating a bundle. The unchanged eligible input then commits through actual SQL and independently reads back its original selector bytes. + +All eight native bundle cases freshly passed on donor code source `2226e1ca6a4929bea9611255dd5d2f84177e6faa`, with zero failures, errors or skips. Canonical formatting, style, Integration Checkstyle and SpotBugs passed; the one passively identified PostgreSQL container was independently absent after completion. On receiving source `fc11e3c1a353537c433ea480b3332d0057df3afc`, all eight bundle cases, ten publication-transaction cases and two historical selector-migration cases freshly passed together with zero failures, errors or skips (2026-10-16 08:14:55–08:16:25 UTC). Integration Checkstyle, SpotBugs, formatting and documentation checks also passed. Main verified fresh reports, unchanged source and independent absence of all four strictly run-owned PostgreSQL containers after forced removal. This is separate receiving evidence; donor attribution remains unchanged. The proof uses stipulated Account, World and other remote participant evidence and a controlled empty-asset candidate. It does not establish a genuine immutable release, authenticated creator or issuer, currentness, public finalizer enablement, activation, settlement or a Gameplay handoff. The three selected-full fixture helpers are already present at their inherited shared-test blobs in this receiver. No production, installed migration or registration changes are included. + ### Selected-full owner publication preparation The source candidate prepares complete selected-owner publication consumption under the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile). It reuses the actual parent World closure producer, adds its full-profile consumer mapping, and composes the selected Game Design digest read/collector with independently retained Entity, Automation and Game Logic receipts. The Game Logic adapter reads the exact retained terminal, selected source and manifest through the existing owner repository and returns both manifest and ability projections; its default Spring composition remains denied. Private selected writer mechanics use the exact canonical selection/request binding and selected gate. Public Game Design fresh/PENDING publication remains denied. Existing Game Design V1020 storage is reused; no Game Design migration is added. 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 e73c2bafc9..a95054cf6e 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 @@ -129,6 +129,8 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Validation and Proof +- A restored positive Entity terminal-read socket case freshly passes with affected Common Platform Core test Checkstyle, SpotBugs and formatting. The actual `GrpcEntitySelectedSourceIntakeTerminalReadClient` receives a complete canonical receipt larger than the ordinary 4 MiB gRPC default over loopback mTLS, within the declared wire bound; the server verifies the Account workload and original request, and the client returns the exact original receipt and authorization bytes. The existing [terminal client test](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java) previously covered only missing-receipt transport and server pinning; that case retains its earlier execution attribution. The complete authorization, World inventory and Entity receipt are controlled fixtures, and the shared test PKI differs from the donor's inline PKI helper. This is client/codec transport proof, not genuine issuer or recipient storage, currentness, settlement, runtime registration or handoff closure. + - The 2026-10-14 current-parent source correction keeps the assignment/roster family unregistered under ordinary component scanning, including when the former activation flags are true, and excludes both roster methods from the JWT public-method allowlist. The initial consolidated gate executed 281 Entity unit cases with one stale allowlist assertion failure, 30 native PostgreSQL cases with no failures, errors or skips, and 17 focused Game Session roster-client cases with no failures, errors or skips. After correcting that assertion, all 11 focused registration, manual-composition and peer-policy cases passed with no failures, errors or skips; affected formatting, static analysis and documentation checks passed. These combined results qualify the bounded source and unchanged retained storage, not production registration, ADR 0163 disposal, genuine authenticated caller completion or a fresh packaged player journey. - 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. 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 d78c337afd..e98e4e639e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,56 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Retained Draft authorization fence migrations + +The [Account fence history fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java) executes the owning filesystem migrations from V75 through V76 and then the current default migration set. Its Account UUID and provenance come from PostgreSQL defaults; it retains the original v1 binding, commit order, stipulated World committed readback, missing Game Design outcome, pending source change and 512-byte source key. Every original column and row version in all six authorization ledger tables, and every prior complete Flyway history row, survives both upgrades. The expected V87 addition of one Global Roles serialization lock is checked separately; it supplies no authority evidence. Exact replay, current pending-mutation refusal and denied binding/readback rewrites leave the retained rows unchanged. + +At source `6a9be6e90decee3c478f36fa4d5ba9f41ddcc313`, the focused native case and affected integration static analysis and formatting pass: one fresh case, zero failures, errors or skips. The actual local run completed on 2026-10-16 from 10:01:32Z to 10:02:08Z. Its strict passive observer owns one PostgreSQL container with an inherited resource-session descriptor, no ownership gaps or observer errors, and independent confirmation that the exact container is absent afterward. Fixture cleanup emits kill 9 and exit 137; this is not graceful shutdown proof. Source capture and World terminal authority are stipulated. This proves retained storage and migration behavior, without genuine World application, final Account settlement, issuer/currentness authority, runtime activation, gameplay admission, Entity delivery or completion of a genuine handoff. + +On Gameplay receiving source `c2f04d797179710e81df08033b16d4f596997e1e`, the same native case freshly passed once with zero failures, errors or skips, together with affected Account integration static analysis, formatting and documentation checks (2026-10-16 10:14:00–10:15:37 UTC). Main read the complete receiving test and saved XML, verified its unchanged qualified Java postimage and independently confirmed its exact run-owned PostgreSQL container absent. Later parent propagation changes no Account implementation or this test. This is focused receiving evidence for retained history; the separate failed whole-Account invocation retains its original outcome. + +### Retained StartSession owner tuples + +The focused Game Session owner fixture retains original unsafe numeric v1 fence carriers through current-execution rejection, including exactly representable values above the safe JSON integer range. It checks the original stored bytes and row version after decoder refusal, conflicting current-spelling replay, Account-projection attachment, evidence continuation and current-attempt reads; the original attempt remains the only row and runtime/admission pointers stay absent. This is controlled PostgreSQL integrity proof, without issuer or deployment provenance. The focused case passes once with two unsafe numeric vectors at source `c6bf1b202b55d0b2616a26d72e4af50c543793fb`; affected integration static analysis, formatting and documentation checks pass. The strict passive observer owns its single PostgreSQL container, with an inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container after completion. Account source-protection and six-store publication cases retain their separate proof boundaries. + +The existing [World original-owner composition](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java) now passes its positive operation at fence values 9,007,199,254,740,992, 9,007,199,254,740,993 and 9,223,372,036,854,775,807. Actual Account issuance/redemption, native Game Session storage and the authenticated Account-to-Game Session current-attempt mTLS read preserve each exact fence, original tuple and redemption projection; the authenticated read leaves the complete stored row and row version unchanged. All three fresh parameterized cases pass with zero failures, errors or skips at source `f1ba70374fab5c7d7a4b733c0bea2bd842a2cd7b`, together with affected cross-service static analysis, formatting and documentation checks. The strict passive observer owns all three run-created PostgreSQL containers, with an inherited resource-session descriptor, no ownership gaps or observer errors, and all three absent after completion. This closes the two focused owner-tuple proof gaps within these controlled fixtures. Creator, Logging claims, publication/launch evidence and PKI remain controlled; the existing World preparation/activation and Account settlement composition uses unregistered owners and a test-local World transport wrapper. It does not establish genuine issuer/environment authority, deployed composition, gameplay admission, Entity placement or completion of any genuine handoff. + +### Original creator validity at the callback boundary + +Both current-actor methods compare the original ControlUI token's complete validity interval after their final blocking owner operations, immediately before invoking a fresh authorization callback. One observation of the existing clock must satisfy `issuedAt <= now < expiresAt`; the canonical original issuance has whole-second `issuedAt = iat = nbf` and zero skew. The original token, registry cleanup deadline, source evidence and retained order remain unchanged. Exact historical recovery of an already-held original order remains permitted after creator expiry. + +The existing Account original-order PostgreSQL fixture changes its injected actor clock when the real final owner locking read completes. The earlier expiry-only code enters both callbacks when that clock moves before the original not-before boundary. The corrected fixture denies both early and expired callbacks without changing the original row JSON or row version, permits both callbacks at exact original `issuedAt` equality, and preserves the existing expired-creator exact-recovery case. These seven native cases plus the unchanged healthy secured Account owner case pass at `cefccc984d6154b9d1b8c3e439541584d2844fc8` with zero failures, errors or skips and affected integration static analysis and formatting. Seven existing Actor unit cases and Main/unit static analysis retain their passing attribution at `774864935ba9783dab410507689ad2848c00fe15`, with the identical production blob. That earlier aggregate failed only because the fixture used an unavailable assertion overload; the test-only correction retains its exact Boolean predicate. Strict passive capture owns the final run's two PostgreSQL containers with inherited resource-session descriptor, no ownership gaps or observer errors, and neither container remaining afterward. This establishes a controlled temporal boundary at a real locking read, not measured physical contention, continuous production protection, genuine upstream authority, activation, admission or Entity delivery. + +### Original creator key acceptance + +Both fresh current-actor paths load the existing trusted public JWKS source outside SQL transactions and synchronization. They require the immutable original signer receipt’s exact key ID and RFC 7638 fingerprint in that protected snapshot, alongside the existing signature/profile, active registry, historical signer provenance, current Account source and final token validity checks. Accepted original keys may coexist with other current public keys; acceptance does not require selecting the newest active signer. The snapshot belongs to one invocation and supplies no guarantee that acceptance continues through later locks, callback or commit. Exact historical held-order recovery remains separate from fresh authentication. + +The existing native original-order fixture proves missing-key and same-key-ID replacement refusal in both paths, accepted-original membership alongside another key, untrusted-source and protected-read failure refusal, and rejection before protected reads under ambient SQL or synchronization. Each parameter compares complete original row JSON and row version. Current snapshot membership is explicitly stipulated through the same concrete source fixture; the source-failure cases execute its real protected observation failure. This models accepted retiring-key membership and does not prove actual signer rotation, publication, withdrawal or compromise authority. At source `5c5363a5ba7caf3af5e6ca9dd93ea212ce3b0c5f`, all fourteen parameters, seven existing native time/equality/recovery cases, the healthy secured Account owner case and seven existing Actor unit cases pass: twenty-nine fresh cases with zero failures, errors or skips. Affected main, unit, integration and test-fixture static analysis, formatting and documentation checks pass. The test-only old-code source `fff5a48653bbcf6e0cd04610dd264c9e1b65c243` first preserves the original row, then fails all four missing/replaced-key callback-denial assertions. The successful run’s strict passive observer owns two PostgreSQL containers with an inherited resource-session descriptor, no ownership gaps or observer errors, and both containers absent afterward. These are bounded component proofs, without genuine upstream authority, runtime registration, gameplay admission or Entity delivery. + +### Original Logging claim-read client + +The existing Account StartSession reservation-evidence client pins the configured Logging & Admin workload URI with the shared pre-request credentials and response verifier. It uses workload-only mTLS without the generic bearer-token stub customizer, rejects caller context and ambient SQL transactions or synchronization before RPC, and preserves the original tuple, purpose, deadline and exact response binding checks. The server identity comes from the existing configured workload namespace, independently of the mutation target namespace. Usable configured certificate, key and CA resources are required without adding a universal regular-file storage restriction; the existing default-off registration stays unchanged. + +The focused source `3357125badc6ad36f6d2e77ea1105685960e86c4` passes ten secured-client cases, two fixture child-process cases, the default-off bean-definition case and the existing Account original-owner PostgreSQL case: fourteen fresh cases with zero failures, errors or skips. Actual loopback mTLS rejects wrong workload, wrong namespace or missing server URI before request delivery; plaintext, missing client credentials, caller context and ambient SQL/synchronization are denied separately. The native owner case uses the actual Logging socket and certificate-derived approved Account leaf; remaining inbound Account and upstream authority contexts stay controlled. Its strict passive observer owns the single run-created PostgreSQL container with the inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container after completion. Affected main, unit, integration and test-fixture static analysis, formatting and documentation checks pass. The test PKI helper now waits within its deadline before reading child output, then terminates and reaps on timeout or interruption while preserving interrupt status; the two new cases prove those paths with actual stalled JDK children. Earlier client/owner passes did not establish this child-process deadline. These controlled component results do not establish genuine creator, issuer, environment or PKI authority, deployed registration, gameplay admission, Entity placement or any genuine handoff. + +### Standalone activation receiver test PKI + +The purpose-specific PKI fixtures in the [activation acquisition receiver test](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java) and [World participation settlement receiver test](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java) now redirect child output to an owned temporary file and wait within the execution deadline before reading it. Timeout or interruption terminates and reaps the child within the bounded cleanup wait and preserves interrupt status. The existing activation settlement receiver test consumes the corrected acquisition fixture; the World participation fixture retains its separate ownership. + +At source `7bc64728ded6619058c926e93ee58f693ae440a5`, all twelve selected cases pass freshly with zero failures, errors or skips: four actual stalled-JDK-child timeout/interruption cases and eight controlled-PKI loopback receiver cases across those three suites. Affected unit static analysis and formatting pass. The receivers use mocked Account owners; acquisition and activation settlement exercise authenticated caller access to malformed-request decoding, while World participation reaches its controlled owner lookup or rejects invalid callers. These results do not establish successful real settlement, owner SQL, genuine PKI or upstream authority, runtime registration or a genuine Gameplay handoff. The prior Logging client and native owner proofs retain their separate source attribution. + +### Selected publication owner preparation + +Activation settlement preserves the canonical source-first lock order: the repository locks exact original source keys in Java canonical order with NOWAIT before locking and rereading the immutable protection row. The focused PostgreSQL refusal fixture controls historical lookup and terminal evidence to exercise only source contention, lock ordering, rollback and absence of settlement effects; it does not prove authenticated terminal production or a complete Java settlement write/readback. + +The disclosure source-lock adapter preserves complete keys through the canonical 2,048 UTF-8 byte bound already owned by shared source evidence and V76 storage. It no longer applies the obsolete 512-byte Java limit. The focused unit covers legacy and longer keys, ASCII and Unicode at the exact byte boundary, and rejection beyond it without truncation or aliasing; physical source-lock and disclosure behavior retain their separately attributed native proof. + +The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. R14 freshly passes eleven focused Account native cases and the real six-store Game Design/World terminal-to-Account settlement composition, including refusal before World completion, exact post-commit receipt replay and nine malformed closure/profile refusals. The latter uses both actual terminal owners and mTLS reads; the local inbound Account caller context remains explicitly controlled. Forward V1011 accepts only the canonical paired legacy and closure inventory profiles, preserving the existing frame, correlation, source and artifact guards. No installed migration is rewritten. + +R16 freshly passes the added V1010-to-current retained-settlement upgrade case for both original terminal outcomes after the test fixture explicitly supports that predecessor. Authorization, source, settlement, issuer and prior Flyway rows retain their exact bytes and row versions through upgrade and replay. The other twelve passing native cases retain R14 attribution; all have zero skips. Account's twenty-five focused units and Common's seven typed-order units retain their preceding pass, and affected generation, static, formatting and documentation checks pass. R14's passive capture owns all eight exact run-created PostgreSQL containers; R16 owns its one, with no ownership gaps or observer errors. Upstream creator, issuer, environment and PKI remain controlled. These owners remain unregistered and grant no publication finalizer, player admission, genuine authority or runtime activation. + +ActualOrderR2 freshly passes the six-store owner composition with actual Game Design-to-Account selected-publication ordering and Account-to-Game-Design immutable selection reads over mTLS. Account captures the environment internally and authenticates the original creator through its existing owner. A controlled Game Design transport outage creates no authorization/source/settlement state and preserves the original issuer rows and row versions. Successful ordering and exact retry retain one held order and unchanged binding/source rows from the single committed issuance; the returned actual order then drives fresh World freeze, publication and exact both-owner terminal settlement. One fresh native case passes with zero skips, six exact PostgreSQL containers passively owned and no observer gaps or errors; affected compilation, static analysis and formatting pass. No new production code, migration, registration or runtime authority is added. Upstream creator, issuer, environment and PKI remain controlled, and the local inbound settlement caller context remains a separate controlled component seam. + ### Selected recipient source intake preparation R31 freshly passes all eight Account final-authorization, exact Entity/Automation terminal-storage and retained-upgrade cases with zero skips. Account's 1,500 unit cases pass with four existing skips, Common's 811 units pass with zero skips, and World's 593 units retain the unchanged R30 pass. A real Java writer-exclusion omission exposed by R30 is corrected: the shared settlement check now includes the existing pending selected-owner reservation predicate, matching the retained SQL guard. The shared synthetic terminal codec fixture is carried at its first consumer. R35 freshly passes the successor disclosure composition at the actual V1008–V1010 repository frontier, including physical source-writer exclusion until exact reservation abort; its static, formatting and documentation checks pass. The earlier V1007-only source proof retains separate R33 attribution. Full-native PostgreSQL/Redis limits remain; controlled source, terminal and PKI inputs establish no genuine authority. @@ -64,6 +114,8 @@ Focused proof is split by unchanged source attribution: twelve shared validator ### Original StartSession source-protection storage +Preceding isolated receiving qualification at `9f48ef606ffe1f73d99adc17f9f88dbb5677624e` on immutable #2967 input `ec4ca374f95d94c130d3578269744477f20b8085` passes 34 focused physical PostgreSQL cases: 18 admission, nine activation and seven credential-cleanup cases, with zero failures, errors or skips. Affected integration static analysis, formatting and documentation checks pass. This canonical lineage installs complete original-tuple byte equality and the independent nested issuance-operation identity checks directly in V1003; it does not install the historical donor V163-to-V164 scalar-guard replacement. The passing canonical predecessor proof retains the actual 112-script history, row bytes and metadata, relation/function identities and prior guard definitions. The activation suite additionally defines a direct contradictory-owner-issuance regression alongside the existing admission case; upstream rows are deliberately stipulated while current acquisition guards remain enabled. These are controlled Account integrity checks and do not establish genuine creator/issuer/environment continuity, authenticated World production, activation or any Gameplay handoff. + 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). diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index f247585592..dd1a8a3ed8 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -86,6 +86,8 @@ Registered mutation ingress remains refused. The existing internal mutation pref ### Selected publication World owner source +FreshBeginR3 freshly passes the six-store selected-publication composition with actual authenticated fresh World begin. The initial World owner is OPEN and no freeze attempt, Account correlation, inventory or canonical frozen capture exists. World independently reads the actual retained Game Design selection, source-qualified current Version and Account HELD through real mTLS handlers. A controlled Account transport outage leaves all five World owner tables and row versions unchanged. The successful request commits the original FROZEN checkpoint, Account correlation and complete inventory, then captures the exact canonical selector. Repeating the same begin with mutable upstream transports denied performs no further owner reads and preserves retained rows. The fixture's former manual freeze/capture is replaced by independent committed readback. The existing actual Game Design reservation, v4 bundle and terminal-to-Account settlement still execute in that one fresh native case, with zero failures, errors or skips. All six run-created PostgreSQL containers are passively owned without gaps or observer errors; affected compilation, static analysis and formatting pass. Upstream original source/APPLIED preparation, creator, issuer, environment and PKI remain controlled. This proves the fresh component path and does not register ingress, supply continuous production authority, implement failed-selection recovery or close any genuine handoff. + The standalone consumer succeeds the shared fence/Common foundation published in [PR #3217](https://github.com/benhook1013/FireMUD/pull/3217) at `8afceb8` on parent `7b2ce634`. Its 66-path scope contains 37 World production files, the existing Common codec and test, 20 World unit/transport files, one current-default PostgreSQL chain, the World Common test-fixtures dependency, four documentation files and an observation. All published migration postimages remain unchanged. Standalone unregistered components cover original Account-order-bound APPLIED application, selected freeze/checkpoint, immutable authored graph, complete artifact inventory, canonical selector/frozen graph, and default-denied terminal completion/readback. The terminal path uses the canonical `GameDesignPublicationTerminalClient` directly and denies UNKNOWN evidence. Existing cumulative V1014 supports exact six-family counts with owner-proved zeros; the selected source explicitly declares all seven inbound families empty. No new migration or generator registry was added, and unsupported nonempty generation rules remain denied. The [World runtime/data manifest](../../architecture/microservices/world-management-service/runtime-and-data.md#digest-input-manifest) owns family/input/digest storage, [procedural generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md#derived-world-artifact-publication) owns derived-artifact/read consequences, and the [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) owns operations. diff --git a/protos/account/v1/selected_publication_order_service.proto b/protos/account/v1/selected_publication_order_service.proto new file mode 100644 index 0000000000..a23b205803 --- /dev/null +++ b/protos/account/v1/selected_publication_order_service.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered Game Design-only producer. No environment authority is caller supplied. +service AccountSelectedPublicationOrderService { + rpc AuthorizeSelectedPublication(AuthorizeSelectedPublicationRequest) + returns (AuthorizeSelectedPublicationResponse); +} + +message AuthorizeSelectedPublicationRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Transport correlation only; the selected publication request owns durable identity. + string request_id = 3; + bytes original_selection = 4; + // The original creator credential travels only in protected per-call metadata. + reserved 5; + reserved "original_creator_credential"; +} + +message AuthorizeSelectedPublicationResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + bytes original_selection = 4; + bytes publication_authorization_binding = 5; +} diff --git a/protos/account/v1/selected_publication_settlement_service.proto b/protos/account/v1/selected_publication_settlement_service.proto new file mode 100644 index 0000000000..205166bb73 --- /dev/null +++ b/protos/account/v1/selected_publication_settlement_service.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone authenticated settlement of one exact selected-publication authorization. +service AccountSelectedPublicationSettlementService { + rpc SettleSelectedPublication(SettleSelectedPublicationRequest) + returns (SettleSelectedPublicationResponse); +} + +message SettleSelectedPublicationRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Independent transport correlation; the retained Account order remains the settlement key. + string request_id = 3; + // Complete canonical game-design-publication-operation/v2 bytes. + bytes original_operation = 4; +} + +message SettleSelectedPublicationResponse { + // Exact unchanged request echo. + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + bytes original_operation = 4; + // Existing six-frame account-selected-publication-settlement/v1 receipt. + bytes settlement_receipt = 5; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 96fa1d078a..ec905e7362 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -295,9 +295,9 @@ public void lockDisclosureSources(List exactSources) { throw new IllegalArgumentException("Distinct exact disclosure source evidence required"); } for (SourceEvidence source : sources) { - if (source.key().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 512) { + if (source.key().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 2048) { throw new IllegalArgumentException( - "Disclosure source key exceeds the existing Account source-lock bound"); + "Disclosure source key exceeds the Account source-lock bound"); } } lockSources(sources); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java index ff072c2bf7..08fc966d17 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java @@ -12,17 +12,23 @@ import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.grpc.GrpcTlsMaterialResolver; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Reads and validates Logging/Admin's current StartSession reservation claim snapshot. @@ -43,30 +49,30 @@ public final class StartSessionReservationEvidenceClient private static final long CALL_DEADLINE_SECONDS = 5L; private static final UUID NIL_UUID = new UUID(0L, 0L); + private final String expectedLoggingPeerUri; private final Clock clock; + private final CommonGrpcClientProperties transportTlsProperties; @Autowired public StartSessionReservationEvidenceClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, - BlockingGrpcStubCustomizer stubCustomizer) { - this(endpoints, tlsProperties, channelFactory, stubCustomizer, Clock.systemUTC()); + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this(endpoints, tlsProperties, channelFactory, workloadNamespace, Clock.systemUTC()); } StartSessionReservationEvidenceClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, - BlockingGrpcStubCustomizer stubCustomizer, + String workloadNamespace, Clock clock) { - super( - endpoints, - tlsProperties, - channelFactory, - stubCustomizer, - StartSessionReservationEvidenceClient.class); + super(endpoints, tlsProperties, channelFactory, StartSessionReservationEvidenceClient.class); + this.expectedLoggingPeerUri = loggingAdminServerUri(workloadNamespace); this.clock = Objects.requireNonNull(clock, "clock is required"); + this.transportTlsProperties = + Objects.requireNonNull(tlsProperties, "TLS properties are required").copy(); } @PostConstruct @@ -88,9 +94,10 @@ protected String defaultTarget() { protected StartSessionReservationEvidenceServiceGrpc .StartSessionReservationEvidenceServiceBlockingStub buildStub(io.grpc.ManagedChannel channel) { - return applyStubCustomizer( - StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) - .withCompression("gzip")); + return StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedLoggingPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedLoggingPeerUri)) + .withCompression("gzip"); } /** Reads the exact active claim for ISSUE or RECOVER and validates every returned binding. */ @@ -101,6 +108,7 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( UUID currentClaimOwnerId, long currentClaimFence, Purpose purpose) { + requireWorkloadOnlyContext(); Objects.requireNonNull(tuple, "reservation tuple is required"); requireNonNilUuid(reservationOwnerId, "reservationOwnerId"); requireNonNilUuid(currentClaimOwnerId, "currentClaimOwnerId"); @@ -123,6 +131,7 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( .setPurpose(toWirePurpose(purpose)) .build(); + requireWorkloadMtls(); var currentStub = stub(); if (currentStub == null) { throw new IllegalStateException("Logging/Admin reservation evidence client is unavailable"); @@ -143,6 +152,47 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( return response; } + static String loggingAdminServerUri(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("StartSession target namespace is invalid"); + } + return "spiffe://firemud/ns/" + targetNamespace + "/sa/logging-admin-service"; + } + + private void requireWorkloadMtls() { + if (transportTlsProperties.isPlaintext()) { + throw new IllegalStateException("Logging/Admin reservation evidence requires workload mTLS"); + } + try { + var material = new GrpcTlsMaterialResolver().resolve(transportTlsProperties); + if (material == null) { + throw new IllegalStateException("Missing workload TLS material"); + } + try (var certificate = material.certChain().openStream(); + var privateKey = material.privateKey().openStream(); + var ca = material.caCert().openStream()) { + if (certificate.read() < 0 || privateKey.read() < 0 || ca.read() < 0) { + throw new IllegalStateException("Empty workload TLS material"); + } + } + } catch (IOException | RuntimeException unavailable) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires usable workload mTLS", unavailable); + } + } + + private static void requireWorkloadOnlyContext() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires no ambient SQL or synchronization"); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires a workload-only caller context"); + } + } + private void validateResponse( ReadCurrentClaimEvidenceResponse response, StartSessionPreAuthorizationReservationTuple tuple, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java index ff49f47dc6..439fd2c64e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java @@ -211,6 +211,16 @@ public StoredSettlement settleExact( accountEvidence.accountProtectionId(), accountEvidence.accountProtectionFence()) .orElseThrow(AccountStartSessionActivationProtectionRepository::unavailable); requireSameEvidence(protection.evidence(), accountEvidence); + lockOriginalSourceRows(protection.evidence()); + Record locked = + dsl.fetchOne( + "SELECT * FROM " + + PROTECTIONS + + " WHERE activation_protection_id = ? FOR UPDATE NOWAIT", + accountEvidence.accountProtectionId()); + if (locked == null) throw unavailable(); + protection = decodeProtection(locked, readSources(accountEvidence.accountProtectionId())); + requireSameEvidence(protection.evidence(), accountEvidence); dsl.execute( "INSERT INTO " @@ -240,6 +250,22 @@ public StoredSettlement settleExact( return stored; } + private void lockOriginalSourceRows(AccountStartSessionActivationProtectionEvidence evidence) { + for (SourceEvidence source : + evidence.sourceEvidenceVector().stream() + .sorted(java.util.Comparator.comparing(SourceEvidence::key)) + .toList()) { + Record locked = + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks " + + "WHERE source_key = ? FOR UPDATE NOWAIT", + source.key()); + if (locked == null || !source.key().equals(text(locked, "source_key"))) { + throw unavailable(); + } + } + } + private Record selectProtectionByRequestId(String requestId) { return dsl.fetchOne( "SELECT * FROM " + PROTECTIONS + " WHERE control_plane_request_id = ?", requestId); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java index 2c42841b14..c441393805 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -144,6 +144,7 @@ T withCurrent( Function action) { outsideSql(); var signed = verifySigned(compactJwt); + var acceptedKey = readAcceptedSignerKey(signed.claims.keyId()); String tokenHash = AccountControlUiIssuanceRepository.hash(compactJwt.getBytes(StandardCharsets.US_ASCII)); byte[] exactRegistry = registry.readActive(tokenHash); @@ -159,6 +160,7 @@ T withCurrent( throw denied(); } requireSignerIdentity(stored, signed); + requireAcceptedSignerKey(stored, acceptedKey); signers.requireOriginal(stored.signerReceipt); var current = authority.capture(stored.accountId, selectedTenant, environment); if (!Arrays.equals(current.evidence(), stored.sources)) { @@ -168,6 +170,7 @@ T withCurrent( if (!committed.tokenHash().equals(tokenHash)) { throw denied(); } + requireCurrentOriginalToken(stored); return action.apply(new Current(stored, current)); }); } @@ -202,6 +205,13 @@ T withCurrentCommitted( throw denied(); } + Object receiptKeyId = + AccountControlUiIssuanceRepository.object(original.signerReceipt).get("kid"); + if (!(receiptKeyId instanceof String keyId)) { + throw denied(); + } + var acceptedKey = readAcceptedSignerKey(keyId); + requireAcceptedSignerKey(original, acceptedKey); byte[] exactRegistry = registry.readActive(original.tokenHash); return transaction.execute( ignored -> { @@ -223,10 +233,44 @@ T withCurrentCommitted( || !Arrays.equals(committed.activeRegistry, exactRegistry)) { throw denied(); } + requireCurrentOriginalToken(committed); return action.apply(new Current(committed, current)); }); } + /** + * One protected snapshot per fresh call; this does not promise acceptance through later locks. + */ + private AcceptedSignerKey readAcceptedSignerKey(String keyId) { + outsideSql(); + String fingerprint = + AccountJwtJwksTrustedSource.publicKeyFingerprint( + publicSource.load(), publicSourcePin, keyId) + .orElseThrow(AccountControlUiActorService::denied); + return new AcceptedSignerKey(keyId, fingerprint); + } + + private static void requireAcceptedSignerKey( + AccountControlUiIssuanceRepository.Stored original, AcceptedSignerKey accepted) { + var receipt = AccountControlUiIssuanceRepository.object(original.signerReceipt); + if (!accepted.keyId().equals(receipt.get("kid")) + || !accepted.fingerprint().equals(receipt.get("publicKeyFingerprint"))) { + throw denied(); + } + } + + private record AcceptedSignerKey(String keyId, String fingerprint) {} + + private void requireCurrentOriginalToken(AccountControlUiIssuanceRepository.Stored original) { + var now = clock.instant(); + if (original.issuedAt == null + || original.expiresAt == null + || now.isBefore(original.issuedAt) + || !now.isBefore(original.expiresAt)) { + throw denied(); + } + } + /** Production asymmetric/profile verification, also used before any candidate is persisted. */ SignedObservation verifySigned(String compactJwt) { outsideSql(); @@ -365,8 +409,9 @@ public String toString() { } private static void outsideSql() { - if (TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException("Signature/registry reads must precede owner SQL locks"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Signature/registry/JWKS reads must precede owner SQL locks"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java new file mode 100644 index 0000000000..3bedfb6d7e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountPublicationAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadGrpcCodec; + +/** Standalone endpoint only: peer authentication precedes decoding and persistence lookup. */ +public final class AccountPublicationAuthorizationReadGrpcService + extends AccountPublicationAuthorizationReadServiceGrpc + .AccountPublicationAuthorizationReadServiceImplBase { + private final AccountPublicationAuthorizationReadService owner; + private final String trustedNamespace; + + public AccountPublicationAuthorizationReadGrpcService( + AccountPublicationAuthorizationReadService owner, String trustedNamespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest request, + StreamObserver observer) { + try { + AccountPublicationAuthorizationReadService.requirePeer(trustedNamespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence + .Request + decoded; + try { + decoded = AccountPublicationAuthorizationReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical Account publication read required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Account publication namespace differs from peer") + .asRuntimeException()); + return; + } + final ReadHeldPublicationAuthorizationResponse response; + try { + owner.requireHeld(decoded); + response = AccountPublicationAuthorizationReadGrpcCodec.toHeldResponse(decoded); + } catch (StatusRuntimeException failure) { + observer.onError( + Status.fromCode(Status.fromThrowable(failure).getCode()) + .withDescription("Account publication authorization owner read denied or unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Account publication owner read unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java new file mode 100644 index 0000000000..aabbb848e7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered owner read of a distinct retained publication order; never a terminal result. */ +public final class AccountPublicationAuthorizationReadService { + private final AccountPublicationAuthorizationRepository repository; + private final String trustedNamespace; + private final TransactionTemplate ownerTransaction; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner persistence collaborator.") + public AccountPublicationAuthorizationReadService( + AccountPublicationAuthorizationRepository repository, + PlatformTransactionManager transactions, + String trustedNamespace) { + this.repository = Objects.requireNonNull(repository); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + public void requireHeld(AccountPublicationAuthorizationReadEvidence.Request request) { + requirePeer(trustedNamespace); + Objects.requireNonNull(request); + if (!trustedNamespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("Account publication namespace differs from peer") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent Account publication owner transaction required") + .asRuntimeException(); + } + try { + ownerTransaction.execute( + status -> { + repository.readHeld(request.binding()); + return null; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (IllegalArgumentException inconsistent) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact held Account publication authorization unavailable") + .asRuntimeException(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Account publication owner read unavailable") + .asRuntimeException(); + } + } + + static void requirePeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + String peerUri = peer.uri(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peerUri) + && !("spiffe://firemud/ns/" + namespace + "/sa/world-management-service").equals(peerUri)) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design or World Management workload required") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java new file mode 100644 index 0000000000..1f326c852d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java @@ -0,0 +1,333 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal owner-transaction storage; remote evidence must first be authenticated by composition. + */ +public final class AccountPublicationAuthorizationRepository { + private final DSLContext dsl; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner persistence collaborator.") + public AccountPublicationAuthorizationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + AccountPublicationAuthorizationBinding authorize( + AccountPublicationAuthorizationBinding.PreallocationInput input, + AccountControlUiActorService.Current current, + Runnable admission) { + requireTransaction(); + Record prior = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations" + + " WHERE tenant_uuid = ? AND publish_request_id = ? FOR UPDATE", + current.stored().tenantId, + input.selection().intent().publishRequestId()); + if (prior != null) { + var original = + AccountPublicationAuthorizationBinding.fromStored(prior.get("binding", byte[].class)); + requireExact(prior, original, input, current); + return original; + } + admission.run(); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, current.source().sources()); + dsl.execute( + "INSERT INTO account_selected_publication_authorizations" + + " (operation_id, fence_id, actor_account_uuid, tenant_uuid, publish_request_id," + + " input_digest, binding, issuance_operation_id, issuance_fence," + + " source_payload, issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + input.actorAccountId(), + binding.tenantId(), + binding.publishRequestId(), + input.digest(), + binding.canonicalBytes(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints())); + for (var source : binding.sources()) { + dsl.execute( + "INSERT INTO account_selected_publication_sources" + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + source.key(), + source.canonicalBytes()); + } + Record retained = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations WHERE operation_id = ? FOR UPDATE", + binding.operationId()); + requireExact(retained, binding, input, current); + return binding; + } + + /** Exact owner read; caller-carried structure alone can never establish HELD. */ + public void readHeld(AccountPublicationAuthorizationBinding requested) { + readOriginal(requested); + if (dsl.fetchOne( + "SELECT 1 FROM account_selected_publication_settlements WHERE operation_id = ?", + requested.operationId()) + != null) { + throw new IllegalArgumentException("Publication authorization is already settled"); + } + } + + /** Historical validation uses the original committed issuance, never current credentials. */ + private void readOriginal(AccountPublicationAuthorizationBinding requested) { + requireTransaction(); + Objects.requireNonNull(requested); + // Sources precede the operation. No transport is permitted in this owner transaction. + for (var source : + requested.sources().stream() + .sorted( + java.util.Comparator.comparing(DraftAuthorizationFenceBinding.SourceEvidence::key)) + .toList()) { + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks" + + " WHERE source_key = ? FOR UPDATE", + source.key()) + == null) { + throw new IllegalArgumentException("Original publication source lock is absent"); + } + } + Record row = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations" + + " WHERE operation_id = ? FOR UPDATE", + requested.operationId()); + if (row == null + || !Arrays.equals(requested.canonicalBytes(), row.get("binding", byte[].class))) { + throw new IllegalArgumentException("Exact held publication authorization is absent"); + } + var retained = + AccountPublicationAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + validateRetainedWorldIfPresent(row, retained); + // Issuance producers acquire this row before source capture. Do not wait backwards while + // holding sources; a concurrent issuer/source writer must cause a retry, never a lock cycle. + Record issuance = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations" + + " WHERE operation_id = ? FOR UPDATE NOWAIT", + row.get("issuance_operation_id", UUID.class)); + if (issuance == null) { + throw new IllegalArgumentException("Original committed issuance is absent"); + } + var originalIssuer = new AccountControlUiIssuanceRepository.Stored(issuance); + var bundle = AccountControlUiIssuanceRepository.object(originalIssuer.bundle); + var sources = AccountControlUiIssuanceRepository.object(originalIssuer.sources); + var rawVector = sources.get("sources"); + if (!"COMMITTED".equals(originalIssuer.status) + || !retained.operationId().equals(row.get("operation_id", UUID.class)) + || !retained.fenceId().equals(row.get("fence_id", UUID.class)) + || !retained.input().actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !retained.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !retained.publishRequestId().equals(row.get("publish_request_id", String.class)) + || !retained.input().digest().equals(row.get("input_digest", String.class)) + || !retained.input().actorAccountId().equals(originalIssuer.accountId) + || !retained.tenantId().equals(originalIssuer.tenantId) + || !originalIssuer.operationId.equals(row.get("issuance_operation_id", UUID.class)) + || !Arrays.equals(originalIssuer.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(originalIssuer.bundle, row.get("issuance_bundle", byte[].class)) + || !(bundle.get("issuanceFence") instanceof Number fence) + || fence.longValue() != row.get("issuance_fence", Long.class) + || !Arrays.equals( + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + bundle.get("outboxCheckpoints")), + row.get("outbox_checkpoints", byte[].class)) + || !originalIssuer.accountId.toString().equals(sources.get("accountId")) + || !originalIssuer.tenantId.toString().equals(sources.get("tenantId")) + || !(rawVector instanceof java.util.List vector) + || vector.size() != retained.sources().size()) { + throw new IllegalArgumentException("Changed original publication issuance evidence"); + } + var participation = + dsl + .fetch( + "SELECT source_key, source_evidence FROM account_selected_publication_sources" + + " WHERE operation_id = ?", + retained.operationId()) + .stream() + .sorted(java.util.Comparator.comparing(r -> r.get("source_key", String.class))) + .toList(); + if (participation.size() != retained.sources().size()) { + throw new IllegalArgumentException("Incomplete original publication source participation"); + } + for (int i = 0; i < retained.sources().size(); i++) { + var source = retained.sources().get(i); + if (!(vector.get(i) instanceof String encoded) + || !Arrays.equals(source.canonicalBytes(), java.util.Base64.getDecoder().decode(encoded)) + || !source.key().equals(participation.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), participation.get(i).get("source_evidence", byte[].class))) { + throw new IllegalArgumentException("Changed original publication source participation"); + } + } + } + + /** + * Persist only after strict authenticated reads from both owners, outside this transaction. + * Structure alone is not owner authentication. World retains the same complete terminal bytes + * with PUBLISHED or ABORTED phase. Transport request IDs deliberately do not enter identity. + */ + public byte[] settle( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence gameDesign, + String worldOutcome, + byte[] worldTerminalEvidence) { + requireTransaction(); + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(gameDesign, "gameDesign"); + byte[] retainedWorldTerminal = + Objects.requireNonNull(worldTerminalEvidence, "worldTerminalEvidence").clone(); + String expectedPhase = + gameDesign.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + if (!expectedPhase.equals(worldOutcome) + || !Arrays.equals(operation.canonicalBytes(), gameDesign.operationBytes()) + || !Arrays.equals(gameDesign.canonicalBytes(), retainedWorldTerminal)) { + throw new IllegalArgumentException("Exact publication owner outcomes disagree"); + } + readOriginal(operation.account()); + byte[] receipt = settlementReceipt(operation, gameDesign, worldOutcome, retainedWorldTerminal); + Record prior = + dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + operation.account().operationId()); + if (prior != null) { + if (!Arrays.equals(receipt, prior.get("receipt", byte[].class))) { + throw new IllegalArgumentException("Changed original publication settlement"); + } + return prior.get("receipt", byte[].class); + } + dsl.execute( + "INSERT INTO account_selected_publication_settlements" + + " (operation_id, fence_id, account_binding, publication_operation," + + " game_design_outcome, game_design_terminal, world_outcome, world_terminal, receipt)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + operation.account().operationId(), + operation.account().fenceId(), + operation.account().canonicalBytes(), + operation.canonicalBytes(), + gameDesign.outcome().name(), + gameDesign.canonicalBytes(), + worldOutcome, + retainedWorldTerminal, + receipt); + Record retained = + dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + operation.account().operationId()); + if (retained == null || !Arrays.equals(receipt, retained.get("receipt", byte[].class))) { + throw new IllegalStateException("Exact publication settlement readback is absent"); + } + return retained.get("receipt", byte[].class); + } + + private static byte[] settlementReceipt( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence gameDesign, + String worldOutcome, + byte[] worldTerminalEvidence) { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, gameDesign.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, worldOutcome); + DraftAuthorizationFenceBinding.frame(out, worldTerminalEvidence); + return out.toByteArray(); + } + + private void requireExact( + Record row, + AccountPublicationAuthorizationBinding binding, + AccountPublicationAuthorizationBinding.PreallocationInput input, + AccountControlUiActorService.Current current) { + validateRetainedWorldIfPresent(row, binding); + if (row == null + || !binding.operationId().equals(row.get("operation_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class)) + || !input.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !binding.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !binding.publishRequestId().equals(row.get("publish_request_id", String.class)) + || !input.digest().equals(row.get("input_digest", String.class)) + || !Arrays.equals(input.canonicalBytes(), binding.input().canonicalBytes()) + || !Arrays.equals(binding.canonicalBytes(), row.get("binding", byte[].class)) + || !current.stored().operationId.equals(row.get("issuance_operation_id", UUID.class)) + || current.source().issuanceFence() != row.get("issuance_fence", Long.class) + || !Arrays.equals(current.stored().sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(current.stored().bundle, row.get("issuance_bundle", byte[].class)) + || !Arrays.equals( + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints()), + row.get("outbox_checkpoints", byte[].class))) { + throw new IllegalArgumentException("Changed immutable selected-publication authorization"); + } + var stored = + dsl + .fetch( + "SELECT source_key, source_evidence FROM account_selected_publication_sources" + + " WHERE operation_id = ?", + binding.operationId()) + .stream() + .sorted(java.util.Comparator.comparing(r -> r.get("source_key", String.class))) + .toList(); + if (stored.size() != binding.sources().size() + || stored.size() != current.source().sources().size()) { + throw new IllegalStateException("Incomplete publication source participation"); + } + for (int i = 0; i < stored.size(); i++) { + var source = binding.sources().get(i); + if (!source.key().equals(stored.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), stored.get(i).get("source_evidence", byte[].class)) + || !Arrays.equals( + source.canonicalBytes(), current.source().sources().get(i).canonicalBytes())) { + throw new IllegalArgumentException("Changed original publication source vector"); + } + } + } + + /** + * Historical pre-freeze World evidence remains immutable and is checked when a row contains it. + */ + private static void validateRetainedWorldIfPresent( + Record row, AccountPublicationAuthorizationBinding binding) { + byte[] worldEvidence = row == null ? null : row.get("world_evidence", byte[].class); + if (worldEvidence != null) { + GameDesignPublicationOperationBinding.requireAccountWorldCorrelation( + binding, WorldPublishedStartLocationEvidence.fromStored(worldEvidence)); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Objects.equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(), + Connection.TRANSACTION_READ_COMMITTED)) { + throw new IllegalStateException("Writable READ_COMMITTED Account owner transaction required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java new file mode 100644 index 0000000000..6e51691691 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Objects; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; + +/** + * Unregistered Account producer for a distinct selected-publication order. Authenticates the + * current initial creator through the real issuance owner and retains the immutable Draft selection + * before World freezes it. World capture and correlation are a separate later boundary. No remote + * calls, terminalization, or activation occur here. + */ +public final class AccountPublicationAuthorizationService { + private final AccountControlUiActorService actors; + private final DraftAuthorizationFenceRepository fences; + private final AccountPublicationAuthorizationRepository publications; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner transaction collaborators.") + public AccountPublicationAuthorizationService( + AccountControlUiActorService actors, + DraftAuthorizationFenceRepository fences, + AccountPublicationAuthorizationRepository publications) { + this.actors = Objects.requireNonNull(actors); + this.fences = Objects.requireNonNull(fences); + this.publications = Objects.requireNonNull(publications); + } + + public AccountPublicationAuthorizationBinding authorize( + String compactJwt, + AuthoredDraftPublishSelectionBinding selection, + CapturedEnvironmentBoundary environment) { + Objects.requireNonNull(selection); + return actors.withCurrent( + compactJwt, + selection.intent().canonicalTenantId(), + environment, + current -> { + fences.lockProducerSourcesNowait(current.source().sources()); + return publications.authorize( + new AccountPublicationAuthorizationBinding.PreallocationInput( + current.stored().accountId, selection), + current, + () -> fences.requirePublicationAdmission(current.source().sources())); + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java new file mode 100644 index 0000000000..3e26220f58 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.BindableService; +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone, unregistered producer; Account obtains environment authority internally. */ +public final class AccountSelectedDraftPublicationOrderGrpcService implements BindableService { + private final AccountSelectedDraftPublicationOrderService owner; + private final AccountHostedTermsService terms; + private final String namespace; + + public AccountSelectedDraftPublicationOrderGrpcService( + AccountSelectedDraftPublicationOrderService owner, + AccountHostedTermsService terms, + String namespace) { + this.owner = Objects.requireNonNull(owner); + this.terms = Objects.requireNonNull(terms); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + /** + * Binding always includes the method-local credential interceptor; peer identity runs outside it. + */ + @Override + public ServerServiceDefinition bindService() { + var handler = + new AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceImplBase() { + @Override + public void authorizeSelectedPublication( + AuthorizeSelectedPublicationRequest request, + StreamObserver observer) { + AccountSelectedDraftPublicationOrderGrpcService.this.authorizeSelectedPublication( + request, observer); + } + }; + return ServerInterceptors.intercept( + handler, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Status denied = peerDenial(); + if (denied != null) { + call.close(sanitized(denied), new Metadata()); + return new ServerCall.Listener<>() {}; + } + final AccountSelectedPublicationOrderCredentials.Credential credential; + try { + credential = AccountSelectedPublicationOrderCredentials.readAuthenticated(headers); + } catch (IllegalArgumentException malformed) { + call.close(sanitized(Status.UNAUTHENTICATED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + var context = + Context.current() + .withValue(AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, credential); + return Contexts.interceptCall(context, call, headers, next); + } + }); + } + + public void authorizeSelectedPublication( + AuthorizeSelectedPublicationRequest wire, + StreamObserver observer) { + Status denied = peerDenial(); + if (denied != null) { + deny(observer, denied); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + final AccountSelectedPublicationOrderGrpcCodec.Request request; + final String credential; + try { + var protectedCredential = AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get(); + if (protectedCredential == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + credential = protectedCredential.value(); + } catch (IllegalArgumentException malformed) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + try { + request = AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, credential); + } catch (IllegalArgumentException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + final AuthorizeSelectedPublicationResponse response; + try { + var captured = terms.captureCurrentEnvironmentBoundary(); + var binding = + owner.authorize(request.originalCreatorCredential(), request.selection(), captured); + response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + } catch (StatusRuntimeException failure) { + deny(observer, Status.fromCode(failure.getStatus().getCode())); + return; + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError(sanitized(status).asRuntimeException()); + } + + private Status peerDenial() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) return Status.UNAUTHENTICATED; + return ("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri()) + ? null + : Status.PERMISSION_DENIED; + } + + private static Status sanitized(Status status) { + return status.withDescription("Account selected-publication order denied or unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java new file mode 100644 index 0000000000..45180b793b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Standalone, unregistered composition of authenticated Game Design selection read and distinct + * Account publication ordering. SELECTED attests immutable reservation only; Account's existing + * owner primitive remains the authority for the original creator, currentness and source holds. + * World freeze/capture, settlement and runtime admission are separate boundaries. + */ +public final class AccountSelectedDraftPublicationOrderService { + private final AuthoredDraftPublishSelectionReadClient selectionClient; + private final AccountPublicationAuthorizationService owner; + private final String workloadNamespace; + + public AccountSelectedDraftPublicationOrderService( + AuthoredDraftPublishSelectionReadClient selectionClient, + AccountPublicationAuthorizationService owner, + String workloadNamespace) { + this.selectionClient = Objects.requireNonNull(selectionClient, "selectionClient"); + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * The caller's selection is lookup data. Only the exact authenticated Game Design read is passed + * to Account's local producer, with the original creator JWT and environment unchanged. The + * remote read completes before the producer opens its own owner transaction. + */ + public AccountPublicationAuthorizationBinding authorize( + String compactJwt, + AuthoredDraftPublishSelectionBinding lookupSelection, + CapturedEnvironmentBoundary environment) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(lookupSelection, "lookupSelection"); + var request = + AuthoredDraftPublishSelectionReadEvidence.Request.create( + workloadNamespace, lookupSelection); + var evidence = selectionClient.read(request); + if (evidence == null + || !request.equals(evidence.request()) + || !Arrays.equals( + lookupSelection.canonicalBytes(), evidence.request().binding().canonicalBytes()) + || !lookupSelection.digest().equals(evidence.request().binding().digest())) { + throw new IllegalStateException( + "Authenticated Game Design selection differs from the exact publication order request"); + } + requireNoAmbientTransaction(); + return owner.authorize(compactJwt, evidence.request().binding(), environment); + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected publication ordering requires no ambient transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java new file mode 100644 index 0000000000..14ebe403b7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered composition of two authenticated owner reads and Account's immutable receipt. + * Historical settlement grants neither creator authority nor runtime admission. + */ +public final class AccountSelectedDraftPublicationSettlementService { + private final AccountPublicationAuthorizationRepository repository; + private final GameDesignPublicationTerminalClient gameDesignClient; + private final WorldPublicationTerminalReadClient worldClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal owner persistence and strict mTLS clients.") + public AccountSelectedDraftPublicationSettlementService( + AccountPublicationAuthorizationRepository repository, + GameDesignPublicationTerminalClient gameDesignClient, + WorldPublicationTerminalReadClient worldClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient); + this.worldClient = Objects.requireNonNull(worldClient); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** Caller bytes identify the original order; only independent authenticated owners settle it. */ + public byte[] settle(byte[] originalOperation) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + var operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); + if (!Arrays.equals(originalOperation, operation.canonicalBytes()) + || !workloadNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException("Exact original publication operation namespace required"); + } + var gameDesignRequest = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + workloadNamespace, operation.canonicalBytes()); + var gameDesign = gameDesignClient.read(gameDesignRequest); + var terminal = gameDesign == null ? null : gameDesign.terminalEvidence().orElse(null); + if (gameDesign == null || !gameDesignRequest.equals(gameDesign.request()) || terminal == null) { + throw new IllegalStateException("Game Design terminal differs from exact owner read request"); + } + if (!Arrays.equals(operation.canonicalBytes(), terminal.operationBytes())) { + throw new IllegalStateException("Game Design terminal substitutes original operation"); + } + requireNoAmbientTransaction(); + var worldRequest = + WorldPublicationTerminalReadEvidence.Request.create( + workloadNamespace, operation.canonicalBytes(), terminal.canonicalBytes()); + var world = worldClient.read(worldRequest); + var expectedWorldOutcome = + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED + : WorldPublicationTerminalReadEvidence.WorldOutcome.ABORTED; + if (world == null + || !worldRequest.equals(world.request()) + || world.worldOutcome() != expectedWorldOutcome + || world.terminalEvidence() == null + || !Arrays.equals(operation.canonicalBytes(), world.terminalEvidence().operationBytes()) + || !Arrays.equals(terminal.canonicalBytes(), world.terminalEvidence().canonicalBytes()) + || !Arrays.equals(terminal.canonicalBytes(), world.worldTerminalEvidence())) { + throw new IllegalStateException("World terminal differs from exact independent owner read"); + } + requireNoAmbientTransaction(); + byte[] receipt = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository.settle( + operation, + terminal, + world.worldOutcome().name(), + world.worldTerminalEvidence()))); + // A second transaction establishes post-commit historical readback; no new issuer or + // credential capture is involved. Neither SQL phase can contain an owner RPC. + requireNoAmbientTransaction(); + byte[] committed = + ownerTransaction.execute( + ignored -> + repository.settle( + operation, + terminal, + world.worldOutcome().name(), + world.worldTerminalEvidence())); + if (!Arrays.equals(receipt, committed)) { + throw new IllegalStateException("Committed Account settlement readback differs from receipt"); + } + return receipt; + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Publication settlement requires no ambient transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java new file mode 100644 index 0000000000..56eb571a39 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementGrpcCodec; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementGrpcCodec.Request; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone unregistered authenticated ingress for exact selected-publication settlement. */ +public final class AccountSelectedPublicationSettlementGrpcService + extends AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceImplBase { + private final AccountSelectedDraftPublicationSettlementService owner; + private final String namespace; + + public AccountSelectedPublicationSettlementGrpcService( + AccountSelectedDraftPublicationSettlementService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-publication settlement owner required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void settleSelectedPublication( + SettleSelectedPublicationRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + if (SessionContext.hasAuthenticatedCallerContext() + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + if (wire == null + || wire.getSerializedSize() + > AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + + final Request request; + try { + request = AccountSelectedPublicationSettlementGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + + try { + byte[] receipt = owner.settle(request.originalOperation()); + observer.onNext(AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.INVALID_ARGUMENT + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + deny(observer, Status.fromCode(code)); + } catch (IllegalArgumentException invalidEvidence) { + deny(observer, Status.FAILED_PRECONDITION); + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + } + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError( + status + .withDescription("Account selected-publication settlement denied or unavailable") + .asRuntimeException()); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V1011__selected_publication_closure_inventory.sql b/services/account-service/src/main/resources/db/migration/V1011__selected_publication_closure_inventory.sql new file mode 100644 index 0000000000..2168ef26f4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1011__selected_publication_closure_inventory.sql @@ -0,0 +1,73 @@ +-- Preserve retained Account settlement rows and the original v1 inventory profile. Admit only the explicit closure-qualified v2 +-- profile. Publication-operation bytes and historical migration definitions remain immutable. +-- [jooq ignore start] +DO $migration$ +DECLARE + inventory_function REGPROCEDURE := + '"${serviceSchema}".require_selected_inventory_operation_v2(bytea)'::REGPROCEDURE; + original_definition TEXT; + model_shape_anchor TEXT := $anchor$ (model, ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'])$anchor$; + model_shape_replacement TEXT := $replacement$ (model, CASE + WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + THEN ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs','inboundSourceClosure'] + ELSE ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'] + END)$replacement$; + profile_anchor TEXT := $anchor$ OR inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$anchor$; + profile_replacement TEXT := $replacement$ OR (( + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v1' + AND inventory->'schemaVersion' = '1'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + AND model->'graphSchemaVersion' = '2'::JSONB + AND checkpoint->'digestSchemaVersion' = '3'::JSONB + AND selector->'request'->'digestSchemaVersion' = '3'::JSONB + AND NOT (model ? 'inboundSourceClosure') + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 16) + OR + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1' + AND model->'graphSchemaVersion' = '3'::JSONB + AND checkpoint->'digestSchemaVersion' = '4'::JSONB + AND selector->'request'->'digestSchemaVersion' = '4'::JSONB + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 17 + AND model ?& ARRAY['modelId', 'graphSchemaVersion', 'graphDigest', + 'topologyResultDigest', 'familyCounts', 'regionGeneratorInputs', + 'generationRuleFields', 'regionFields', 'zoneFields', 'roomFields', + 'roomExitFields', 'spawnBindingFields', 'spawnBindingInputs', + 'generationRuleInputCount', 'spawnBindingCount', 'appliedEpochs', + 'inboundSourceClosure'] + AND model->'inboundSourceClosure' IS NOT DISTINCT FROM + '{"schemaVersion":1,"familyCounts":[{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING","count":0}]}'::JSONB) + ) IS NOT TRUE) OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$replacement$; + model_count_anchor TEXT := $anchor$ OR (SELECT count(*) FROM jsonb_object_keys(model)) <> 16$anchor$; + model_count_replacement TEXT := $replacement$ OR (SELECT count(*) FROM jsonb_object_keys(model)) <> (CASE + WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB THEN 17 ELSE 16 END)$replacement$; + legacy_model_anchor TEXT := $anchor$ OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB$anchor$; +BEGIN + SELECT pg_get_functiondef(inventory_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, model_shape_anchor, ''))) + / length(model_shape_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, profile_anchor, ''))) + / length(profile_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, legacy_model_anchor, ''))) + / length(legacy_model_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, model_count_anchor, ''))) + / length(model_count_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact Account V94 inventory profile and complete model guards'; + END IF; + original_definition := replace(original_definition, model_shape_anchor, model_shape_replacement); + original_definition := replace(original_definition, profile_anchor, profile_replacement); + -- The paired profile guard above checks both model identifiers and graph schemas. Keep the + -- generation-rule and artifact-decision restrictions below unchanged for both profiles. + original_definition := replace(original_definition, legacy_model_anchor, ''); + original_definition := replace(original_definition, model_count_anchor, model_count_replacement); + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..5984a479e7 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java @@ -0,0 +1,390 @@ +package integration.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +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; + +/** Retained V75 storage only; source capture and World terminal authority are test stipulations. */ +class AccountDraftFenceHistoryPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private static final List TABLES = + List.of( + "account_draft_authorization_source_locks", + "account_draft_authorization_fences", + "account_draft_authorization_sources", + "account_draft_authorization_owner_readbacks", + "account_draft_authorization_source_changes", + "account_draft_authorization_changed_scopes"); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @Test + void retainedV1OrderReadbackAndPendingChangeSurviveRequiredOwnerAndCurrentMigrations() { + String schema = "account_fence_history_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = POSTGRES.dataSource(schema); + migrate(source, schema, "75"); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + // V75 predates restriction birth. Let PostgreSQL generate the UUID and its real provenance; + // current AccountRepository insertion must not be used to invent a historical birth receipt. + UUID account = insertHistoricalAccount(dsl); + DraftAuthorizationFenceBinding binding = binding(account); + SourceEvidence legacyKey = binding.sources().get(1); + assertThat(legacyKey.key().getBytes(StandardCharsets.UTF_8)).hasSize(512); + var world = + new OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {8}); + var change = new SourceChange(UUID.randomUUID(), binding.sources(), new byte[] {12}); + seedHistoricalState(dsl, transaction, binding, world, change); + + // Freeze the original columns so later additions cannot disguise a rewrite of retained data. + Map queries = originalRowQueries(dsl); + Map> rows = rows(dsl, queries); + assertThat(rows.values()).allSatisfy(tableRows -> assertThat(tableRows).isNotEmpty()); + int rank75 = historyRank(dsl); + List history75 = history(dsl, rank75); + migrate(source, schema, "76"); + assertThat(rows(dsl, queries)).isEqualTo(rows); + assertThat(history(dsl, rank75)).isEqualTo(history75); + assertRetained(dsl, transaction, binding, world, change, legacyKey); + assertThat(rows(dsl, queries)).isEqualTo(rows); + + int rank76 = historyRank(dsl); + List history76 = history(dsl, rank76); + Flyway current = migrate(source, schema, null); + assertThat(current.info().pending()).isEmpty(); + assertThat(historyRank(dsl)).isGreaterThan(rank76); + assertThat(history(dsl, rank76)).isEqualTo(history76); + Map> currentRows = rows(dsl, queries); + rows.forEach( + (table, originalRows) -> { + if (table.equals("account_draft_authorization_source_locks")) { + // V87 adds a serialization lock from the real Account scope, never authority evidence. + assertThat(currentRows.get(table)) + .containsAll(originalRows) + .hasSize(originalRows.size() + 1); + } else { + assertThat(currentRows.get(table)).isEqualTo(originalRows); + } + }); + assertThat( + dsl.fetch("SELECT source_key FROM account_draft_authorization_source_locks") + .getValues(0, String.class)) + .containsExactlyInAnyOrder( + binding.sources().get(0).key(), legacyKey.key(), "GLOBAL_ROLES:" + account); + assertRetained(dsl, transaction, binding, world, change, legacyKey); + transaction.executeWithoutResult( + ignored -> + assertThat(new DraftAuthorizationFenceRepository(dsl).sourceMutationPermitted(change)) + .isFalse()); + assertThat(rows(dsl, queries)).isEqualTo(currentRows); + assertHistoricalProvenance(dsl, account); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_draft_authorization_fences SET binding = ? WHERE operation_id = ?", + new byte[] {99}, + binding.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM account_draft_authorization_owner_readbacks WHERE operation_id = ?", + binding.operationId())) + .isInstanceOf(DataAccessException.class); + assertThat(rows(dsl, queries)).isEqualTo(currentRows); + } + + private static void assertRetained( + DSLContext dsl, + TransactionTemplate transaction, + DraftAuthorizationFenceBinding binding, + OwnerReadback world, + SourceChange change, + SourceEvidence legacyKey) { + var repository = new DraftAuthorizationFenceRepository(dsl); + transaction.executeWithoutResult( + ignored -> { + assertThat( + repository + .readOriginalBinding(binding.operationId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(binding.canonicalBytes()); + assertThat(repository.reserve(binding).binding()) + .containsExactly(binding.canonicalBytes()); + assertThat(repository.read(binding).ordering()).isEqualTo(Ordering.COMMIT_ORDER); + assertThat(repository.readOwnerResult(binding, Owner.WORLD).orElseThrow().readback()) + .containsExactly(world.canonicalBytes()); + assertThat(repository.readOwnerResult(binding, Owner.GAME_DESIGN)).isEmpty(); + assertThat(repository.readSettlement(binding)).isEqualTo(Settlement.PENDING); + assertThat(repository.readSourceChange(change).status()).isEqualTo("WAITING"); + }); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ?", + legacyKey.key())) + .get(0, String.class)) + .isEqualTo(legacyKey.key()); + } + + private static void seedHistoricalState( + DSLContext dsl, + TransactionTemplate transaction, + DraftAuthorizationFenceBinding binding, + OwnerReadback world, + SourceChange change) { + // Preserve V75's actual guarded insert/order lifecycle. Current source-change APIs also + // inspect later publication owners, which do not exist in this predecessor schema. + transaction.executeWithoutResult( + ignored -> { + for (SourceEvidence evidence : binding.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT DO NOTHING", + evidence.key()); + } + dsl.execute( + "INSERT INTO account_draft_authorization_fences (operation_id, request_id, commit_id, fence_id, binding, ordering) VALUES (?, ?, ?, ?, ?, 'RESERVED')", + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.canonicalBytes()); + for (SourceEvidence evidence : binding.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + evidence.key(), + evidence.canonicalBytes()); + } + dsl.execute( + "UPDATE account_draft_authorization_fences SET ordering = 'COMMIT_ORDER', ordered_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + binding.operationId()); + dsl.execute( + "INSERT INTO account_draft_authorization_owner_readbacks (operation_id, owner, outcome, readback) VALUES (?, 'WORLD', 'COMMITTED', ?)", + binding.operationId(), + world.canonicalBytes()); + dsl.execute( + "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change.changeId(), + change.canonicalBytes()); + for (SourceEvidence evidence : change.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", + change.changeId(), + evidence.key()); + } + }); + } + + private static UUID insertHistoricalAccount(DSLContext dsl) { + UUID suffix = UUID.randomUUID(); + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash, role, email_verified, " + + "login_auth_modes, lifecycle_state) VALUES (?, ?, 'historical-test-verifier', " + + "'player', FALSE, 'PASSWORD,EMAIL_OTP', 'active') RETURNING account_uuid", + "fence-history-" + suffix, + suffix + "@example.test")); + UUID account = Objects.requireNonNull(row.get(0, UUID.class)); + assertThat(account.version()).isEqualTo(4); + assertHistoricalProvenance(dsl, account); + return account; + } + + private static void assertHistoricalProvenance(DSLContext dsl, UUID account) { + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, account_uuid_provenance, account_uuid_source_numeric_id, " + + "account_repository_insert_transaction_id FROM accounts WHERE account_uuid = ?", + account)); + assertThat(row.get("id", Long.class)).isPositive(); + assertThat(row.get("account_uuid_provenance", String.class)) + .isEqualTo("ACCOUNT_DATABASE_INSERT"); + assertThat(row.get("account_uuid_source_numeric_id", Long.class)) + .isEqualTo(row.get("id", Long.class)); + assertThat(row.get("account_repository_insert_transaction_id", Long.class)).isNull(); + } + + private static DraftAuthorizationFenceBinding binding(UUID account) { + var complete = + DraftCommitBinding.create( + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "tenant-key", + 2, + "tenant-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "historical/base:9007199254740993", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "historical-world-payload")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + account, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "2", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + "3", + "5", + "stream/" + account, + "2", + new byte[] {7}), + new SourceEvidence( + SourceKind.ISSUER, + "x".repeat(505), + "3", + "5", + "stream/legacy512", + "2", + new byte[] {9}))); + } + + private static Map originalRowQueries(DSLContext dsl) { + Map queries = new LinkedHashMap<>(); + for (String table : TABLES) { + List columns = + dsl.fetch( + "SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position", + table) + .getValues(0, String.class); + assertThat(columns).isNotEmpty(); + String projection = + String.join(",", columns.stream().map(name -> "\"" + name + "\"").toList()); + queries.put( + table, + "SELECT to_jsonb(original)::text FROM (SELECT " + + projection + + ",xmin::text AS row_xmin FROM " + + table + + ") original ORDER BY to_jsonb(original)::text"); + } + return queries; + } + + private static Map> rows(DSLContext dsl, Map queries) { + Map> rows = new LinkedHashMap<>(); + queries.forEach((table, query) -> rows.put(table, dsl.fetch(query).getValues(0, String.class))); + return rows; + } + + private static int historyRank(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT max(installed_rank) FROM flyway_schema_history")) + .get(0, Integer.class); + } + + private static List history(DSLContext dsl, int rank) { + return dsl.fetch( + "SELECT to_jsonb(h)::text FROM flyway_schema_history h WHERE installed_rank <= ? ORDER BY installed_rank", + rank) + .getValues(0, String.class); + } + + private static Flyway migrate(DriverManagerDataSource source, String schema, String target) { + Path root = Path.of("").toAbsolutePath(); + while (root != null && !Files.isRegularFile(root.resolve("gradlew"))) root = root.getParent(); + root = Objects.requireNonNull(root, "Repository filesystem migrations required"); + var configuration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + root.resolve("services/account-service/src/main/resources/db/migration"), + "filesystem:" + + root.resolve("services/common-saga/src/main/resources/db/migration/saga")); + if (target != null) configuration.target(target); + Flyway flyway = configuration.load(); + flyway.migrate(); + return flyway; + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java index 627d60ce9d..012428b62e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java @@ -915,7 +915,7 @@ private static void exerciseSelectedPublicationV2Settlement( "publishWorkflowId", jsonString(workflowId.toString()), "appliedCommitId", jsonString(selectedCommit.commitId().toString()), "contentDigest", jsonString(contentDigest), - "digestSchemaVersion", "1", + "digestSchemaVersion", "3", "worldAffectedTuples", expectedTuples); String selectorJson = jsonObject( @@ -1021,7 +1021,7 @@ private static void exerciseSelectedPublicationV2Settlement( jsonObject( "appliedCommitId", jsonString(selectedCommit.commitId().toString()), "contentDigest", jsonString(contentDigest), - "digestSchemaVersion", "1"), + "digestSchemaVersion", "3"), "sourceModel", modelJson, "artifactDecisions", "[{\"artifactKind\":\"NAVMESH\",\"state\":\"NOT_REQUIRED\"," 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 index 9cb3db2f17..b73c907fc6 100644 --- 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 @@ -2,6 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -17,17 +21,23 @@ import java.util.Locale; import java.util.Map; import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository.StoredProtection; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; 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.common.world.WorldOriginalStartSessionActivationTerminalEvidence; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; +import org.jooq.ExecuteListener; import org.jooq.Field; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -54,6 +64,134 @@ class AccountStartSessionActivationProtectionPostgresIntegrationTest { private static final JsonMapper JSON = JsonMapper.builder().build(); + @Test + void settlementLocksCanonicalSourceKeysBeforeProtectionRowAccess() throws Exception { + Fixture fixture = fixture(); + var first = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + "activation-\uD800\uDC00", + null, + "1", + null, + null, + bytes("first")); + var last = + new SourceEvidence( + SourceKind.HOSTED_TERMS, "activation-\uE000", null, "1", null, null, bytes("last")); + for (var source : List.of(first, last)) { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + source.key()); + } + UUID protectionId = UUID.randomUUID(); + var evidence = mock(AccountStartSessionActivationProtectionEvidence.class); + when(evidence.accountProtectionId()).thenReturn(protectionId); + when(evidence.accountProtectionFence()).thenReturn(7L); + when(evidence.canonicalBytes()).thenReturn(bytes("controlled protection lookup")); + when(evidence.sourceEvidenceVector()).thenReturn(List.of(last, first)); + var terminal = mock(WorldOriginalStartSessionActivationTerminalEvidence.class); + when(terminal.accountProtectionEvidence()).thenReturn(evidence); + var repository = spy(new AccountStartSessionActivationProtectionRepository(fixture.dsl())); + // Only the lock boundary is physical here; historical lookup and terminal authority are + // controlled. + doReturn(java.util.Optional.of(new StoredProtection(evidence, 1L))) + .when(repository) + .findHistoricalExact(protectionId, 7L); + var sourceLocks = new java.util.ArrayList(); + var protectionLocks = new java.util.ArrayList(); + fixture + .dsl() + .configuration() + .setAppending( + new DefaultExecuteListenerProvider( + ExecuteListener.onExecuteStart( + context -> { + String sql = context.sql(); + var query = context.query(); + if (sql == null || query == null || !sql.contains("FOR UPDATE NOWAIT")) + return; + if (sql.contains("account_draft_authorization_source_locks")) { + sourceLocks.add((String) query.getBindValues().getFirst()); + } else if (sql.contains("account_start_session_activation_protections")) { + protectionLocks.add(query.getBindValues().getFirst()); + } + }))); + for (var contended : List.of(first, last)) { + sourceLocks.clear(); + protectionLocks.clear(); + try (var holder = fixture.dataSource().getConnection()) { + holder.setAutoCommit(false); + try (var statement = + holder.prepareStatement( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE")) { + statement.setString(1, contended.key()); + try (var rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + } + } + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult(ignored -> repository.settleExact(terminal))) + .hasRootCauseInstanceOf(org.postgresql.util.PSQLException.class) + .satisfies( + failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(((org.postgresql.util.PSQLException) root).getSQLState()) + .isEqualTo("55P03"); + }); + assertThat(protectionLocks).isEmpty(); + assertThat(sourceLocks) + .containsExactlyElementsOf( + contended == first ? List.of(first.key()) : List.of(first.key(), last.key())); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + holder.rollback(); + } + } + sourceLocks.clear(); + protectionLocks.clear(); + // Once both sources are available, row lookup follows them; no parent is manufactured by this + // test. + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult(ignored -> repository.settleExact(terminal))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact original StartSession activation protection unavailable"); + assertThat(sourceLocks).containsExactly(first.key(), last.key()); + assertThat(protectionLocks).containsExactly(protectionId); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + try (var verifier = fixture.dataSource().getConnection()) { + verifier.setAutoCommit(false); + try (var statement = + verifier.prepareStatement( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE NOWAIT")) { + for (var source : List.of(first, last)) { + statement.setString(1, source.key()); + try (var rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + } + } + } + verifier.rollback(); + } + } + @Test void digestAlignmentUpgradePreservesRetainedParentAndRequiresCanonicalWorldPrefix() throws Exception { @@ -1342,6 +1480,59 @@ void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() thro expiredFixture, expired.requestBytes(), expired.operationIdentityBytes()); } + @Test + void fullTupleDoesNotBypassIndependentActivationIssuanceOperationBinding() throws Exception { + Fixture fixture = fixture(); + CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(60)); + Map request = readJson(current.requestBytes()); + byte[] tuple = + Base64.getDecoder() + .decode((String) request.get("originalPostAuthorizationTupleBytesBase64")); + byte[] projection = + Base64.getDecoder().decode((String) request.get("accountRedemptionProjectionBytesBase64")); + assertThat(projection).containsExactly(tuple); + String requestId = (String) readJson(tuple).get("controlPlaneRequestId"); + + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + current.requestBytes(), + current.operationIdentityBytes(), + current.operationIdentityDigest())); + // Stipulate one contradictory retained owner row to isolate the independent SQL conjunct. + // Current activation/acquisition guards stay enabled; this is not authenticated producer proof. + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + assertThat( + fixture + .dsl() + .execute( + "UPDATE account_start_session_operator_authorizations SET issuance_operation_id = ? " + + "WHERE control_plane_request_id = ?", + UUID.randomUUID(), + requestId)) + .isEqualTo(1); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + assertThatThrownBy(() -> acquireProtection(fixture, current)) + .hasMessageContaining( + "Activation protection differs from original Account redemption or capture"); + for (String table : + List.of( + "account_start_session_activation_protections", + "account_start_session_activation_protection_sources")) { + assertThat(fixture.dsl().fetchCount(DSL.table(table))).as(table).isZero(); + } + } + @Test void abortedSettlementPreservesTerminalCodeFenceWithoutRequiringActiveLifecycle() throws Exception { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java index 56dca09c66..2736f558c8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -2,8 +2,6 @@ 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.when; import com.google.protobuf.ByteString; import io.grpc.Context; @@ -19,15 +17,18 @@ import io.grpc.StatusRuntimeException; import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.codec.ByteArrayCodec; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; @@ -49,14 +50,15 @@ import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; @@ -110,7 +112,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest { @Container static final PostgreSQLContainer postgres = - AccountControlUiOwnerWorkflowPostgresIntegrationTest.postgres; + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static final GenericContainer redis = @@ -150,7 +152,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest { @TempDir Path temporary; - private InProcessLoggingTransport loggingTransport; + private MtlsLoggingTransport loggingTransport; @AfterEach void clearLoggingTransport() throws Exception { @@ -414,21 +416,25 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() var reservationFixture = StartSessionReservationMutationTestFixtures.forRunOwnedPostgres(postgres, loggingSchema); var reservationService = reservationFixture.service(); - var approvedAccountLeaf = testAccountLeafEvidence(); + var loggingPki = + AccountStartSessionReservationProofPki.create( + temporary.resolve("logging-claim-pki"), "control-ui-owner-proof"); + String approvedAccountLeaf = + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(loggingPki.accountIdentity().certificate().getEncoded())); Path approvedLeafFile = temporary.resolve("account-reservation-evidence-approved-test-leaf.txt"); Files.writeString( - approvedLeafFile, - "active=" + approvedAccountLeaf.leafSha256() + "\n", - StandardCharsets.US_ASCII); + approvedLeafFile, "active=" + approvedAccountLeaf + "\n", StandardCharsets.US_ASCII); loggingTransport = - inProcessLoggingTransport( + mtlsLoggingTransport( new StartSessionReservationEvidenceGrpcService( reservationService, new StartSessionReservationEvidenceLeafApproval(approvedLeafFile.toString()), "control-ui-owner-proof"), - "spiffe://firemud/ns/control-ui-owner-proof/sa/account-service", - approvedAccountLeaf); + loggingPki); var acquisition = reservationService.acquire(loggingTuple); assertThat(acquisition.newlyAcquired()).isTrue(); @@ -862,69 +868,43 @@ private static Path loggingMigrations() { } /** - * Test-only in-process composition supplies the Account URI and a run-owned approved leaf; it - * exercises receiver authorization, not a TLS handshake or mTLS certificate binding. + * Controlled Logging socket uses certificate-derived Account identity and actual approved leaf. */ - private static InProcessLoggingTransport inProcessLoggingTransport( + private static MtlsLoggingTransport mtlsLoggingTransport( StartSessionReservationEvidenceGrpcService receiver, - String accountPeerUri, - GrpcPeerCertificateEvidence accountLeafEvidence) + AccountStartSessionReservationProofPki pki) throws Exception { - String serverName = InProcessServerBuilder.generateName(); - var peer = GrpcPeerIdentity.parseUri(accountPeerUri).orElseThrow(); + var identity = pki.server("logging"); Server server = - InProcessServerBuilder.forName(serverName) - .directExecutor() - .addService( - ServerInterceptors.intercept( - receiver, - new ServerInterceptor() { - @Override - public ServerCall.Listener interceptCall( - ServerCall call, - Metadata headers, - ServerCallHandler next) { - Context peerContext = - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .withValue( - GrpcPeerCertificateEvidence.CONTEXT_KEY, accountLeafEvidence); - return Contexts.interceptCall(peerContext, call, headers, next); - } - })) + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) .build() .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService("localhost:" + server.getPort()); + var tls = pki.clientProperties(); + var factory = new GrpcChannelFactory(); ManagedChannel receiverChannel = - InProcessChannelBuilder.forName(serverName).directExecutor().build(); - ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); - endpoints.setLoggingAdminService(serverName); - CommonGrpcClientProperties testTransport = new CommonGrpcClientProperties(); - testTransport.setPlaintext(true); - GrpcChannelFactory channelFactory = - new GrpcChannelFactory() { - @Override - public ManagedChannel buildChannel( - String target, - int defaultPort, - CommonGrpcClientProperties properties, - boolean keepAlive) { - if (!serverName.equals(target) || !properties.isPlaintext()) { - throw new IllegalArgumentException( - "Only the named in-process test transport is valid"); - } - return InProcessChannelBuilder.forName(serverName).directExecutor().build(); - } - }; - StartSessionReservationEvidenceClient accountClient = + factory.buildChannel(endpoints.getLoggingAdminService(), 6565, tls, true); + var accountClient = new StartSessionReservationEvidenceClient( - endpoints, testTransport, channelFactory, BlockingGrpcStubCustomizer.noop()); + endpoints, tls, factory, "control-ui-owner-proof"); try { ReflectionTestUtils.invokeMethod(accountClient, "init"); - return new InProcessLoggingTransport( + String loggingUri = "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; + return new MtlsLoggingTransport( server, receiverChannel, accountClient, - StartSessionReservationEvidenceServiceGrpc.newBlockingStub(receiverChannel)); + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(receiverChannel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(loggingUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(loggingUri))); } catch (RuntimeException | Error failure) { accountClient.close(); receiverChannel.shutdownNow(); @@ -933,18 +913,6 @@ public ManagedChannel buildChannel( } } - private static GrpcPeerCertificateEvidence testAccountLeafEvidence() { - X509Certificate leaf = mock(X509Certificate.class); - try { - when(leaf.getEncoded()) - .thenReturn( - "run-owned Account test leaf certificate".getBytes(StandardCharsets.US_ASCII)); - } catch (CertificateEncodingException exception) { - throw new AssertionError(exception); - } - return GrpcPeerCertificateEvidence.fromCertificate(leaf).orElseThrow(); - } - private static InProcessAccountTransport inProcessAccountTransport( StartSessionOperatorAuthorizationGrpcService receiver, String namespace) throws Exception { return new InProcessAccountTransport( @@ -1060,10 +1028,10 @@ public void close() { } /** - * Test-only in-process composition. Its injected peer context exercises receiver authorization; - * it is deliberately not a TLS or mTLS proof. + * Controlled Logging socket composition with actual workload certificates and leaf approval. + * Account's separate inbound owner transport remains explicitly controlled. */ - private static final class InProcessLoggingTransport implements AutoCloseable { + private static final class MtlsLoggingTransport implements AutoCloseable { private final Server server; private final ManagedChannel receiverChannel; private final StartSessionReservationEvidenceClient accountClient; @@ -1071,7 +1039,7 @@ private static final class InProcessLoggingTransport implements AutoCloseable { .StartSessionReservationEvidenceServiceBlockingStub receiverStub; - private InProcessLoggingTransport( + private MtlsLoggingTransport( Server server, ManagedChannel receiverChannel, StartSessionReservationEvidenceClient accountClient, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java index b5baf98e77..437d5cb329 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import io.grpc.Context; import java.nio.file.Path; @@ -12,15 +13,23 @@ import java.time.ZoneOffset; import java.util.List; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.ExecuteContext; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.PostgreSQLContainer; @@ -78,6 +87,351 @@ class AccountOriginalDraftOrderPostgresIntegrationTest { @TempDir Path temporary; + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void originalCreatorExpiryAtFinalOwnerLockDeniesCurrentCallback( + boolean signedCredential, @TempDir Path proofDirectory) throws Exception { + assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( + signedCredential, proofDirectory, Duration.ofMinutes(10)); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void originalCreatorNotBeforeAtFinalOwnerLockDeniesCurrentCallback( + boolean signedCredential, @TempDir Path proofDirectory) throws Exception { + assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( + signedCredential, proofDirectory, Duration.ofMinutes(-10)); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void originalCreatorIssuedAtEqualityAtFinalOwnerLockAllowsCurrentCallback( + boolean signedCredential, @TempDir Path proofDirectory) throws Exception { + assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( + signedCredential, proofDirectory, Duration.ZERO); + } + + private void assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( + boolean signedCredential, Path proofDirectory, Duration clockChange) throws Exception { + var clock = new ActorClock(); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + proofDirectory, + UUID.randomUUID(), + clock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + String tokenHash = + AccountControlUiCoordination.digest( + "SHA-256", issued.compact().getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + var jti = + f.tx( + () -> + f.dsl + .fetchSingle( + "SELECT token_jti FROM account_control_ui_issuance_operations " + + "WHERE token_hash=? AND status='COMMITTED'", + tokenHash) + .get("token_jti", UUID.class)); + long issuedAt = + java.util.Objects.requireNonNull( + f.tx( + () -> + f.dsl + .fetchSingle( + "SELECT issued_at_epoch_second FROM account_control_ui_issuance_operations " + + "WHERE token_jti=?", + jti) + .get("issued_at_epoch_second", Long.class))); + var before = + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_jti=?", + jti)); + var callback = new AtomicBoolean(); + var clockChanged = new AtomicBoolean(); + var originalListeners = f.dsl.configuration().executeListenerProviders(); + var timeChangeAtOwnerLock = + new DefaultExecuteListenerProvider( + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && sql.contains("account_control_ui_issuance_operations") + && sql.contains("FOR UPDATE") + && clockChanged.compareAndSet(false, true)) { + // The real locking read has completed; simulate elapsed time at this precise + // boundary. + // This is deterministic temporal-boundary proof, not physical lock-contention + // proof. + if (clockChange.isZero()) { + clock.freezeAt(Instant.ofEpochSecond(issuedAt)); + } else { + clock.advance(clockChange); + } + } + } + }); + var listeners = java.util.Arrays.copyOf(originalListeners, originalListeners.length + 1); + listeners[originalListeners.length] = timeChangeAtOwnerLock; + f.dsl.configuration().set(listeners); + try { + Throwable failure = + catchThrowable( + () -> { + if (signedCredential) { + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + } else { + issued + .actors() + .withCurrentCommitted( + f.account.getAccountUuid(), + f.tenant, + jti, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + } + }); + assertThat(clockChanged).isTrue(); + assertThat(clock.instant().isBefore(Instant.ofEpochSecond(issuedAt))) + .isEqualTo(clockChange.isNegative()); + assertThat(callback.get()).isEqualTo(clockChange.isZero()); + if (clockChange.isZero()) { + assertThat(clock.instant()).isEqualTo(Instant.ofEpochSecond(issuedAt)); + assertThat(failure).isNull(); + } else { + assertThat(failure).isInstanceOf(IllegalStateException.class); + } + assertThat( + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_jti=?", + jti))) + .isEqualTo(before); + } finally { + f.dsl.configuration().set(originalListeners); + } + } + } + + @ParameterizedTest + @CsvSource({ + "true, ABSENT", "false, ABSENT", "true, REPLACED", "false, REPLACED", + "true, RETAINED", "false, RETAINED", "true, UNTRUSTED", "false, UNTRUSTED", + "true, SOURCE_FAILURE", "false, SOURCE_FAILURE", "true, SQL", "false, SQL", + "true, SYNCHRONIZATION", "false, SYNCHRONIZATION" + }) + void originalCreatorRequiresExactKeyInCurrentProtectedSnapshot( + boolean signedCredential, String keyState, @TempDir Path proofDirectory) throws Exception { + var clock = new ActorClock(); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + proofDirectory, + UUID.randomUUID(), + clock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + clock.freezeAt(clock.instant()); + var originalSnapshot = fixture.publicSource.load(); + var pin = fixture.publicSource.sourceIdentity(); + String tokenHash = + AccountControlUiCoordination.digest( + "SHA-256", issued.compact().getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + var original = + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT token_jti, signer_receipt, row_to_json(a)::TEXT AS payload, " + + "a.xmin::TEXT AS row_version FROM account_control_ui_issuance_operations a " + + "WHERE token_hash=? AND status='COMMITTED'", + tokenHash)); + UUID jti = original.get("token_jti", UUID.class); + var receipt = + AccountControlUiIssuanceRepository.object(original.get("signer_receipt", byte[].class)); + String originalKid = (String) receipt.get("kid"); + assertThat( + AccountJwtJwksTrustedSource.publicKeyFingerprint(originalSnapshot, pin, originalKid)) + .contains((String) receipt.get("publicKeyFingerprint")); + byte[] changed = originalSnapshot.jwksBytes(); + if (java.util.Set.of("ABSENT", "REPLACED", "RETAINED").contains(keyState)) { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + var replacement = + AccountControlUiSignerFixture.publicJwk( + "REPLACED".equals(keyState) ? originalKid : "other-accepted-key", + (java.security.interfaces.RSAPublicKey) generator.generateKeyPair().getPublic()); + var keys = new java.util.ArrayList(); + keys.add( + AccountControlUiIssuanceRepository.object( + replacement.json().getBytes(java.nio.charset.StandardCharsets.UTF_8))); + if ("RETAINED".equals(keyState)) { + // Controlled retiring-key membership: another current key precedes the accepted original. + // This is not a real signer-rotation or publication proof. + var originalKeys = + (List) + AccountControlUiIssuanceRepository.object(originalSnapshot.jwksBytes()) + .get("keys"); + keys.addAll(originalKeys); + } + changed = AccountControlUiAuthority.canonical(java.util.Map.of("keys", keys)); + } + var observedPin = + "UNTRUSTED".equals(keyState) + ? new net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity( + pin.environmentId(), + pin.clusterId(), + pin.clusterIncarnationUid(), + pin.namespace(), + pin.namespaceUid(), + UUID.randomUUID().toString(), + pin.bindingRevision(), + pin.apiServerOrigin(), + pin.servingCaSha256()) + : pin; + var controlledCurrent = + new net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot( + observedPin, changed); + var protectedFailures = new java.util.concurrent.atomic.AtomicInteger(); + if ("SOURCE_FAILURE".equals(keyState)) { + org.mockito.Mockito.doAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + protectedFailures.incrementAndGet(); + throw new IllegalStateException("controlled protected-source transport failure"); + }) + .when(fixture.signerFixture.client) + .observe(); + } + var reads = new java.util.concurrent.atomic.AtomicInteger(); + // Current snapshot membership is an explicit upstream stipulation here; this does not prove + // a production key withdrawal or publication. Original issuance, SQL and Redis remain real. + org.mockito.Mockito.doAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + reads.incrementAndGet(); + if ("SOURCE_FAILURE".equals(keyState) + || "SQL".equals(keyState) + || "SYNCHRONIZATION".equals(keyState)) { + return invocation.callRealMethod(); + } + return controlledCurrent; + }) + .when(fixture.publicSource) + .load(); + var callback = new AtomicBoolean(); + java.util.function.Supplier action = + () -> { + if (signedCredential) { + return issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + } + return issued + .actors() + .withCurrentCommitted( + f.account.getAccountUuid(), + f.tenant, + jti, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + }; + Throwable failure = + catchThrowable( + () -> { + if ("SQL".equals(keyState)) { + f.tx(action::get); + } else if ("SYNCHRONIZATION".equals(keyState)) { + org.springframework.transaction.support.TransactionSynchronizationManager + .initSynchronization(); + try { + action.get(); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager + .clearSynchronization(); + } + } else { + action.get(); + } + }); + var after = + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_hash=?", + tokenHash)); + assertThat(after.get("payload", String.class)) + .isEqualTo(original.get("payload", String.class)); + assertThat(after.get("row_version", String.class)) + .isEqualTo(original.get("row_version", String.class)); + assertThat(callback.get()).isEqualTo("RETAINED".equals(keyState)); + if ("RETAINED".equals(keyState)) { + assertThat(failure).isNull(); + } else { + assertThat(failure).isInstanceOf(RuntimeException.class); + } + if ("SQL".equals(keyState) || "SYNCHRONIZATION".equals(keyState)) { + assertThat(reads.get()).isZero(); + } else { + assertThat(reads.get()).isGreaterThanOrEqualTo(1); + } + if ("SOURCE_FAILURE".equals(keyState)) { + assertThat(protectedFailures.get()).isGreaterThanOrEqualTo(1); + } + } + } + @Test void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrSubstitute() throws Exception { @@ -355,6 +709,11 @@ private static void asPeer(String namespace, String workload, Runnable action) { private static final class ActorClock extends Clock { private Duration offset = Duration.ZERO; + private Instant frozen; + + void freezeAt(Instant value) { + frozen = value; + } void advance(Duration amount) { offset = offset.plus(amount); @@ -365,11 +724,11 @@ public ZoneId getZone() { } public Clock withZone(ZoneId zone) { - return Clock.offset(Clock.system(zone), offset); + return frozen == null ? Clock.offset(Clock.system(zone), offset) : Clock.fixed(frozen, zone); } public Instant instant() { - return Instant.now().plus(offset); + return frozen == null ? Instant.now().plus(offset) : frozen; } } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java new file mode 100644 index 0000000000..3bd11eb575 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -0,0 +1,1082 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Genuine Account issuance/current actor, publication producer/storage, loopback mutual TLS and + * production read client. Trust provisioning, legal sources, synchronized Draft and World APPLIED + * descriptors are explicitly stipulated test inputs. No real World handoff, Game Design release, + * deployed workload trust, public wiring, or activation is established by this isolated proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountPublicationAuthorizationMtlsPostgresIntegrationTest { + private static final String NAMESPACE = "test"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("publication-mtls-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "publication-mtls-primary", + "6379"); + + @TempDir Path temporary; + + /** + * Real creator issuance, automatic Account environment capture and publication transaction over + * loopback mTLS. The strict upstream Game Design reader serves a stipulated immutable selection, + * not an actual Game Design reservation/database. Platform/legal/trust inputs remain fixtures. + */ + @Test + void selectedOrderProducerTransportUsesOriginalCreatorAndReplaysOneDurableHeldOrder() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("producer-pki"))); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve("producer-owner")))) { + // Exactly one issuance/OTP consumption; no owner order is fabricated or preseeded. + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var selection = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()) + .selection(); + var issuance = + sources.dsl.fetchSingle( + "SELECT operation_id, token_hash FROM account_control_ui_issuance_operations WHERE status = 'COMMITTED'"); + var reads = new java.util.concurrent.CopyOnWriteArrayList(); + var upstream = + new net.firedevops.firemud.gamedesign.v1.GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceImplBase() { + @Override + public void readSelectedDraftPublication( + net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse> + observer) { + try { + requireAccountClient(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var request = AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest(wire); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.originalSelection()).isEqualTo(selection.canonicalBytes()); + reads.add(wire.getReadRequestId()); + observer.onNext( + AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(request)); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + Server gdServer = terminalServer(pki.gameDesignServer, pki.ca, upstream); + try (var selectionClient = selectionClient(gdServer.getPort(), pki.accountClient, pki.ca)) { + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var owner = + new AccountSelectedDraftPublicationOrderService( + selectionClient, + new AccountPublicationAuthorizationService( + issued.actors(), sources.fences, repository), + NAMESPACE); + var producer = + new AccountSelectedDraftPublicationOrderGrpcService(owner, sources.terms, NAMESPACE); + var held = + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE), + NAMESPACE); + Server accountServer = terminalServer(pki.server, pki.ca, producer, held); + try { + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, issued.compact()); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + assertThat(wire.toString()).doesNotContain(issued.compact()); + var rawKey = + io.grpc.Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + io.grpc.Metadata.BINARY_BYTE_MARSHALLER); + var malformed = new io.grpc.Metadata(); + malformed.put(rawKey, new byte[] {(byte) 128}); + var duplicate = new io.grpc.Metadata(); + duplicate.put(rawKey, issued.compact().getBytes(StandardCharsets.US_ASCII)); + duplicate.put(rawKey, issued.compact().getBytes(StandardCharsets.US_ASCII)); + for (var wrongPeer : List.of(pki.worldManagement, pki.otherNamespace)) { + assertProducerHeaderDenied( + accountServer.getPort(), + wrongPeer, + pki.ca, + wire, + malformed, + Status.Code.PERMISSION_DENIED); + } + for (var headers : List.of(new io.grpc.Metadata(), malformed, duplicate)) { + assertProducerHeaderDenied( + accountServer.getPort(), + pki.gameDesign, + pki.ca, + wire, + headers, + Status.Code.UNAUTHENTICATED); + } + assertThat(reads).isEmpty(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isZero(); + for (var wrongPeer : List.of(pki.worldManagement, pki.otherNamespace)) { + try (var client = producerClient(accountServer.getPort(), wrongPeer, pki.ca)) { + assertCode(Status.Code.PERMISSION_DENIED, () -> client.authorize(request)); + } + assertThat(reads).isEmpty(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isZero(); + } + try (var client = producerClient(accountServer.getPort(), pki.gameDesign, pki.ca)) { + var first = client.authorize(request); + var retry = client.authorize(request); + var fresh = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, issued.compact()); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat(fresh.originalCreatorCredential()) + .isEqualTo(request.originalCreatorCredential()); + var correlatedRetry = client.authorize(fresh); + assertThat(retry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + assertThat(correlatedRetry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + assertThat(first.input().selection().canonicalBytes()) + .isEqualTo(selection.canonicalBytes()); + assertThat(first.input().actorAccountId()).isEqualTo(sources.account.getAccountUuid()); + assertThat(reads).hasSize(3).doesNotHaveDuplicates(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isEqualTo(first.sources().size()); + var stored = + sources.dsl.fetchSingle( + "SELECT binding, issuance_operation_id FROM account_selected_publication_authorizations WHERE operation_id = ?", + first.operationId()); + assertThat(stored.get("binding", byte[].class)).isEqualTo(first.canonicalBytes()); + assertThat(stored.get("issuance_operation_id", UUID.class)) + .isEqualTo(issuance.get("operation_id", UUID.class)); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_control_ui_issuance_operations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchSingle( + "SELECT operation_id, token_hash FROM account_control_ui_issuance_operations WHERE status = 'COMMITTED'")) + .isEqualTo(issuance); + assertPending(sources, repository, first); + try (var reader = client(accountServer.getPort(), pki.worldManagement, pki.ca)) { + var exactHeld = + AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, first); + assertThat(reader.read(exactHeld).request()).isEqualTo(exactHeld); + } + } + } finally { + accountServer.shutdownNow(); + assertThat(accountServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } finally { + gdServer.shutdownNow(); + assertThat(gdServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static AccountSelectedPublicationOrderClient producerClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var client = + new AccountSelectedPublicationOrderClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + /** Negative transport only: deliberately bypasses the production credential emitter. */ + private static void assertProducerHeaderDenied( + int port, + TestIdentity identity, + Path ca, + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest wire, + io.grpc.Metadata headers, + Status.Code expected) + throws Exception { + var channel = + new GrpcChannelFactory() + .buildChannel("127.0.0.1:" + port, 6565, identity.properties(ca), true); + try { + var peer = "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service"; + var stub = + net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc + .newBlockingStub(channel) + .withCallCredentials( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( + peer)) + .withInterceptors( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( + peer), + io.grpc.stub.MetadataUtils.newAttachHeadersInterceptor(headers)) + .withDeadlineAfter(5, TimeUnit.SECONDS); + assertCode(expected, () -> stub.authorizeSelectedPublication(wire)); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static AuthoredDraftPublishSelectionReadClient selectionClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + port); + var client = + new AuthoredDraftPublishSelectionReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + /** + * Real Account storage and two strict loopback mTLS clients. Remote immutable terminals and the + * incoming Game Design request context are stipulated; remote owner databases are not exercised. + */ + @Test + void twoAuthenticatedTerminalOwnersSettleActualAccountOrderAndReadBackAfterCommit() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("settlement-pki"))); + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve(outcome.name())))) { + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var descriptor = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()); + var repository = + org.mockito.Mockito.spy(new AccountPublicationAuthorizationRepository(sources.dsl)); + var order = + new AccountPublicationAuthorizationService(issued.actors(), sources.fences, repository) + .authorize(issued.compact(), descriptor.selection(), issued.environment()); + var operation = + AccountPublicationAuthorizationPostgresIntegrationTest.operation( + order, descriptor.world()); + var terminal = + AccountPublicationAuthorizationPostgresIntegrationTest.terminal(operation, outcome); + var mode = new AtomicReference<>("exact"); + var gdReads = new java.util.concurrent.CopyOnWriteArrayList(); + var worldReads = new java.util.concurrent.CopyOnWriteArrayList(); + var gdEndpoint = + new net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceImplBase() { + @Override + public void readGameDesignPublicationTerminal( + net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest + wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.gamedesign.v1 + .ReadGameDesignPublicationTerminalResponse> + observer) { + try { + requireAccountClient(); + var request = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wire); + gdReads.add(request.readRequestId().toString()); + if (mode.get().equals("gd-missing")) throw Status.NOT_FOUND.asRuntimeException(); + if (mode.get().equals("gd-unavailable")) + throw Status.UNAVAILABLE.asRuntimeException(); + var result = + new net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadResult( + request, + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.Status.valueOf( + terminal.outcome().name()), + java.util.Optional.of(terminal)); + var response = + GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result) + .toBuilder(); + if (mode.get().startsWith("gd-") + && !mode.get().equals("gd-missing") + && !mode.get().equals("gd-unavailable")) { + byte[] echoedRequest = request.canonicalBytes(); + byte[] terminalBytes = terminal.canonicalBytes(); + if (mode.get().equals("gd-correlation")) { + echoedRequest = + new net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadRequest( + 1, + request.targetNamespace(), + UUID.randomUUID(), + request.operationBytes()) + .canonicalBytes(); + } else if (mode.get().equals("gd-operation")) { + var invalidRequest = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + invalidRequest, + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadRequest.SCHEMA); + DraftAuthorizationFenceBinding.frame(invalidRequest, "1"); + DraftAuthorizationFenceBinding.frame( + invalidRequest, request.targetNamespace()); + DraftAuthorizationFenceBinding.frame( + invalidRequest, request.readRequestId().toString()); + DraftAuthorizationFenceBinding.frame(invalidRequest, new byte[0]); + echoedRequest = invalidRequest.toByteArray(); + } else if (mode.get().equals("gd-unknown")) { + var invalid = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + invalid, GameDesignPublicationTerminalEvidence.SCHEMA); + DraftAuthorizationFenceBinding.frame(invalid, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(invalid, "UNKNOWN"); + terminalBytes = invalid.toByteArray(); + } + var invalidResponse = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + invalidResponse, + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadResult.SCHEMA); + DraftAuthorizationFenceBinding.frame(invalidResponse, echoedRequest); + DraftAuthorizationFenceBinding.frame( + invalidResponse, terminal.outcome().name()); + DraftAuthorizationFenceBinding.frame(invalidResponse, terminalBytes); + response.setCanonicalResponseBytes( + com.google.protobuf.ByteString.copyFrom(invalidResponse.toByteArray())); + } + observer.onNext(response.build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + var worldEndpoint = + new net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadServiceGrpc + .WorldPublicationTerminalReadServiceImplBase() { + @Override + public void readPublicationTerminal( + net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalRequest wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalResponse> + observer) { + try { + requireAccountClient(); + var request = WorldPublicationTerminalReadGrpcCodec.fromRequest(wire); + worldReads.add(wire.getReadRequestId()); + if (mode.get().equals("world-missing")) + throw Status.NOT_FOUND.asRuntimeException(); + if (mode.get().equals("world-unavailable")) + throw Status.UNAVAILABLE.asRuntimeException(); + var response = + WorldPublicationTerminalReadGrpcCodec.toResponse(request, terminal) + .toBuilder(); + if (mode.get().equals("world-correlation")) + response.setReadRequestId(UUID.randomUUID().toString()); + if (mode.get().equals("world-operation")) + response.setOriginalOperation(com.google.protobuf.ByteString.EMPTY); + if (mode.get().equals("world-terminal")) + response.setWorldTerminalEvidence(com.google.protobuf.ByteString.EMPTY); + if (mode.get().equals("world-unknown")) response.setWorldOutcomeValue(99); + if (mode.get().equals("world-phase")) + response.setWorldOutcomeValue( + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED ? 2 : 1); + observer.onNext(response.build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + Server gdServer = terminalServer(pki.gameDesignServer, pki.ca, gdEndpoint); + Server worldServer = terminalServer(pki.worldServer, pki.ca, worldEndpoint); + Server wrongServer = terminalServer(pki.server, pki.ca, gdEndpoint, worldEndpoint); + try (var gdClient = gameDesignClient(gdServer.getPort(), pki.accountClient, pki.ca); + var worldClient = worldClient(worldServer.getPort(), pki.accountClient, pki.ca)) { + var composition = + new AccountSelectedDraftPublicationSettlementService( + repository, gdClient, worldClient, sources.manager, NAMESPACE); + for (String failure : + List.of( + "gd-missing", + "gd-unavailable", + "gd-correlation", + "gd-operation", + "gd-unknown", + "world-missing", + "world-unavailable", + "world-correlation", + "world-operation", + "world-terminal", + "world-unknown", + "world-phase")) { + mode.set(failure); + assertThatThrownBy( + () -> asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + } + mode.set("exact"); + try (var wrongGd = gameDesignClient(wrongServer.getPort(), pki.accountClient, pki.ca); + var wrongWorld = worldClient(wrongServer.getPort(), pki.accountClient, pki.ca)) { + var wrongGdComposition = + new AccountSelectedDraftPublicationSettlementService( + repository, wrongGd, worldClient, sources.manager, NAMESPACE); + var wrongWorldComposition = + new AccountSelectedDraftPublicationSettlementService( + repository, gdClient, wrongWorld, sources.manager, NAMESPACE); + assertThatThrownBy( + () -> asGameDesign(() -> wrongGdComposition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + assertThatThrownBy( + () -> + asGameDesign( + () -> wrongWorldComposition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + } + var invocations = new AtomicInteger(); + var corruptReadback = new java.util.concurrent.atomic.AtomicBoolean(); + String schema = + java.util.Objects.requireNonNull( + sources.dsl.fetchOne("SELECT current_schema() AS schema")) + .get("schema", String.class); + org.mockito.Mockito.doAnswer( + call -> { + int invocation = invocations.incrementAndGet(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_READ_COMMITTED); + if (invocation == 2) { + // Independent connection cannot see the first transaction's uncommitted + // insert. + // Seeing its exact row before the second owner invocation proves prior + // commit. + try (var connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword())) { + connection.setSchema(schema); + try (var statement = + connection.prepareStatement( + "SELECT game_design_terminal FROM account_selected_publication_settlements WHERE operation_id = ?")) { + statement.setObject(1, order.operationId()); + try (var result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getBytes(1)).isEqualTo(terminal.canonicalBytes()); + assertThat(result.next()).isFalse(); + } + } + } + } + byte[] readback = (byte[]) call.callRealMethod(); + return corruptReadback.get() && invocation % 2 == 0 + ? new byte[] {99} + : readback; + }) + .when(repository) + .settle( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + gdReads.clear(); + worldReads.clear(); + byte[] receipt = asGameDesign(() -> composition.settle(operation.canonicalBytes())); + assertThat(asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isEqualTo(receipt); + assertThat(invocations).hasValue(4); + assertThat(gdReads).hasSize(2).doesNotHaveDuplicates(); + assertThat(worldReads).hasSize(2).doesNotHaveDuplicates(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isEqualTo(1); + var heldReader = + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + asGameDesign( + () -> { + heldReader.requireHeld( + AccountPublicationAuthorizationReadEvidence.Request.create( + NAMESPACE, order)); + return null; + })); + assertThat(sources.tx(sources::changeRoleToAdmin).getRole()).isEqualTo("admin"); + corruptReadback.set(true); + assertThatThrownBy( + () -> asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs"); + assertThat( + java.util.Objects.requireNonNull( + sources.dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + order.operationId())) + .get("receipt", byte[].class)) + .isEqualTo(receipt); + } finally { + for (Server server : List.of(gdServer, worldServer, wrongServer)) server.shutdownNow(); + for (Server server : List.of(gdServer, worldServer, wrongServer)) + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + } + + private static void assertPending( + AccountControlUiOwnerSourcesFixture sources, + AccountPublicationAuthorizationRepository repository, + AccountPublicationAuthorizationBinding order) { + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + sources.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy(() -> sources.tx(sources::changeRoleToAdmin)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + } + + private static void requireAccountClient() { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !("spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private static T asGameDesign(Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static Server terminalServer( + TestIdentity identity, Path ca, io.grpc.BindableService... endpoints) throws Exception { + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + for (var endpoint : endpoints) + builder.addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())); + return builder.build().start(); + } + + private static GameDesignPublicationTerminalClient gameDesignClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + port); + var client = + new GameDesignPublicationTerminalClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + private static WorldPublicationTerminalReadClient worldClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + port); + var client = + new WorldPublicationTerminalReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + @Test + void genuineProducerToGameDesignAndWorldMtlsReadersReplaysExactlyAndRejectsSubstitution() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("pki"))); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve("owner")))) { + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var descriptor = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var producer = + new AccountPublicationAuthorizationService(issued.actors(), sources.fences, repository); + var original = + producer.authorize(issued.compact(), descriptor.selection(), issued.environment()); + var request = AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, original); + var endpoint = + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE), + NAMESPACE); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + pki.server.certificate().toFile(), pki.server.key().toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + try { + try (var client = client(server.getPort(), pki.gameDesign, pki.ca)) { + var first = client.read(request); + var retry = client.read(request); + assertThat(first.request()).isEqualTo(request); + assertThat(retry.request()).isEqualTo(first.request()); + assertThat(first.request().originalPublicationAuthorizationBinding()) + .isEqualTo(original.canonicalBytes()); + var freshRead = + AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, original); + assertThat(client.read(freshRead).request()).isEqualTo(freshRead); + var unknown = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), original.fenceId(), original.input(), original.sources()); + var changedFence = + new AccountPublicationAuthorizationBinding( + original.operationId(), UUID.randomUUID(), original.input(), original.sources()); + for (var rejected : List.of(unknown, changedFence)) { + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + client.read( + AccountPublicationAuthorizationReadEvidence.Request.create( + NAMESPACE, rejected))); + } + // A negative read cannot change the exact held owner row or prevent its next read. + assertThat(client.read(request).request()).isEqualTo(request); + } + try (var client = client(server.getPort(), pki.worldManagement, pki.ca)) { + var first = client.read(request); + var retry = client.read(request); + assertThat(first.request()).isEqualTo(request); + assertThat(retry.request()).isEqualTo(first.request()); + assertThat(first.request().originalPublicationAuthorizationBinding()) + .isEqualTo(original.canonicalBytes()); + } + for (var wrongPeer : + List.of(pki.wrongWorkload, pki.otherNamespace, pki.otherWorldNamespace)) { + try (var client = client(server.getPort(), wrongPeer, pki.ca)) { + assertCode(Status.Code.PERMISSION_DENIED, () -> client.read(request)); + } + } + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat( + java.util.Objects.requireNonNull( + sources.dsl.fetchOne( + "SELECT binding FROM account_selected_publication_authorizations WHERE operation_id = ?", + original.operationId()), + "Expected exact retained publication after transport reads") + .get("binding", byte[].class)) + .isEqualTo(original.canonicalBytes()); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static AccountPublicationAuthorizationReadClient client( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var client = + new AccountPublicationAuthorizationReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private record TestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + } + + /** Ephemeral keytool PKI, following Account's existing loopback test; no runtime credentials. */ + private static final class TestPki { + private static final String PASSWORD = "test-only-publication-mtls-password"; + final Path ca; + final TestIdentity server, + accountClient, + gameDesignServer, + worldServer, + gameDesign, + worldManagement, + wrongWorkload, + otherNamespace, + otherWorldNamespace; + + TestPki(Path root) throws Exception { + Path caStore = root.resolve("ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=Account publication test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + ca = root.resolve("ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + ca.toString(), + "-rfc"); + server = issue(root, caStore, "account-server", NAMESPACE, "account-service", true); + accountClient = issue(root, caStore, "account-client", NAMESPACE, "account-service", false); + gameDesignServer = + issue(root, caStore, "game-design-server", NAMESPACE, "game-design-service", true); + worldServer = + issue(root, caStore, "world-server", NAMESPACE, "world-management-service", true); + gameDesign = + issue(root, caStore, "game-design-client", NAMESPACE, "game-design-service", false); + worldManagement = + issue(root, caStore, "world-client", NAMESPACE, "world-management-service", false); + wrongWorkload = + issue(root, caStore, "game-session-client", NAMESPACE, "game-session-service", false); + otherNamespace = + issue( + root, + caStore, + "other-game-design-client", + "other-test", + "game-design-service", + false); + otherWorldNamespace = + issue( + root, caStore, "other-world-client", "other-test", "world-management-service", false); + } + + private static TestIdentity issue( + Path root, Path caStore, String alias, String namespace, String workload, boolean server) + throws Exception { + Path store = root.resolve(alias + ".p12"), + request = root.resolve(alias + ".csr"), + certificate = root.resolve(alias + ".crt"); + String san = + "URI:spiffe://firemud/ns/" + + namespace + + "/sa/" + + workload + + ",DNS:localhost,IP:127.0.0.1"; + String eku = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san); + var keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, PASSWORD.toCharArray()); + } + byte[] privateKey = + java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull( + keyStore.getKey(alias, PASSWORD.toCharArray()), + "Expected ephemeral test private key") + .getEncoded(), + "Expected encoded ephemeral test private key"); + Path key = root.resolve(alias + ".key"); + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(privateKey); + Files.writeString( + key, + "-----BEGIN PRIVATE KEY-----\n" + body + "\n-----END PRIVATE KEY-----\n", + StandardCharsets.US_ASCII); + java.util.Arrays.fill(privateKey, (byte) 0); + return new TestIdentity(certificate, key); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("Ephemeral test certificate generation timed out"); + } + try (var output = process.getInputStream()) { + String details = new String(output.readAllBytes(), StandardCharsets.UTF_8); + if (process.exitValue() != 0) + throw new IllegalStateException("Test keytool failed: " + details); + } + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java new file mode 100644 index 0000000000..74f59e9470 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -0,0 +1,1396 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Account signer/issuance/Redis/current-actor and PostgreSQL ordering. World APPLIED and + * synchronized selection bytes below are explicitly test-only upstream stipulations. This does not + * prove authenticated World transport, publication terminalization or runtime activation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountPublicationAuthorizationPostgresIntegrationTest { + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("publication-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "publication-primary", + "6379"); + + @TempDir Path temporary; + + /** + * Both owner readbacks here are upstream authenticated-owner stipulations, not transport proof. + */ + @Test + void exactTwoOwnerSettlementRollsBackAtomicallyThenReplaysAfterLostAcknowledgement() + throws Exception { + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var order = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var terminal = terminal(operation, outcome); + String phase = + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.settle(operation, terminal, phase, terminal.canonicalBytes()); + throw new IllegalStateException("rollback before owner commit"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy(() -> f.tx(f::changeRoleToAdmin)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + + byte[] originalBinding = order.canonicalBytes(); + byte[] receipt = + f.tx(() -> repository.settle(operation, terminal, phase, terminal.canonicalBytes())); + // A committed response may be lost. Fresh outside transport correlations never enter + // settlement identity; historical replay does not authenticate a new creator credential. + UUID firstTransportRead = UUID.randomUUID(), retryTransportRead = UUID.randomUUID(); + assertThat(firstTransportRead).isNotEqualTo(retryTransportRead); + assertThat( + f.tx( + () -> repository.settle(operation, terminal, phase, terminal.canonicalBytes()))) + .isEqualTo(receipt); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isEqualTo(1); + assertThat( + f.dsl + .fetchSingle( + "SELECT binding FROM account_selected_publication_authorizations WHERE operation_id = ?", + order.operationId()) + .get("binding", byte[].class)) + .isEqualTo(originalBinding); + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.readHeld(order); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("already settled"); + var readOwner = + new AccountPublicationAuthorizationReadService(repository, f.manager, "test"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + readOwner.requireHeld( + net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadEvidence.Request.create( + "test", order)))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + assertThat(f.tx(f::changeRoleToAdmin).getRole()).isEqualTo("admin"); + // Even after the source changes, the original committed issuance and receipt replay. + assertThat( + f.tx( + () -> repository.settle(operation, terminal, phase, terminal.canonicalBytes()))) + .isEqualTo(receipt); + for (String mutation : + List.of( + "UPDATE account_selected_publication_settlements SET world_outcome = 'ABORTED'", + "DELETE FROM account_selected_publication_settlements", + "TRUNCATE account_selected_publication_settlements")) { + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(mutation))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + } + } + + @Test + void missingAmbiguousSubstitutedAndDisagreeingOwnersKeepOriginalSourcesHeld() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var order = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var noPublication = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var published = terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED); + var wrongFence = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + order.operationId(), UUID.randomUUID(), order.input(), order.sources()); + var wrongOperation = operation(wrongFence, proof.world()); + for (Runnable rejected : + List.of( + () -> + repository.settle( + operation, noPublication, "PUBLISHED", noPublication.canonicalBytes()), + () -> + repository.settle( + operation, noPublication, "ABORTED", published.canonicalBytes()), + () -> + repository.settle( + operation, + noPublication, + "RECONCILIATION_REQUIRED", + noPublication.canonicalBytes()), + () -> repository.settle(operation, noPublication, "ABORTED", new byte[0]), + () -> repository.settle(operation, noPublication, "ABORTED", null), + () -> + repository.settle( + wrongOperation, + terminal( + wrongOperation, + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION), + "ABORTED", + terminal( + wrongOperation, + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION) + .canonicalBytes()))) { + assertThatThrownBy( + () -> + f.tx( + () -> { + rejected.run(); + return null; + })) + .isInstanceOf(RuntimeException.class); + } + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThat( + f.dsl.fetchCount(org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + + byte[] receipt = + f.tx( + () -> + repository.settle( + operation, noPublication, "ABORTED", noPublication.canonicalBytes())); + assertThatThrownBy( + () -> + f.tx( + () -> + repository.settle( + operation, published, "PUBLISHED", published.canonicalBytes()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed original"); + assertThat( + f.dsl + .fetchSingle( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + order.operationId()) + .get("receipt", byte[].class)) + .isEqualTo(receipt); + } + } + + @Test + void settlingOneOrderLeavesEveryOtherOriginalSourceParticipationPending() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var first = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var secondSelection = + selection(proof.selection().selectedCommit(), "other order", "another-publication"); + var second = service.authorize(issued.compact(), secondSelection, issued.environment()); + var operation = operation(first, proof.world()); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + f.tx(() -> repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes())); + f.tx( + () -> { + repository.readHeld(second); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + var captured = + f.tx( + () -> + f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), captured.sources(), new byte[] {1}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + } + } + + static GameDesignPublicationTerminalEvidence terminal( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence.Outcome outcome) { + if (outcome == GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION) { + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), outcome, null, null); + } + var request = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + request.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner) ? "sha256:" + "a".repeat(64) : null, + null, + null)) + .toList(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + operation.account().tenantId(), + request.canonicalVersionId(), + "release-exact", + 1, + "v2", + request.publishWorkflowId(), + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of("look"), + "generation-1", + operation.world()); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + outcome, + release, + Math.addExact(request.versionStateEpoch(), 1)); + } + + static GameDesignPublicationOperationBinding operation( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world) { + return new GameDesignPublicationOperationBinding( + account, world, IsolatedWorldPublicationInventoryFixtures.stipulated(account, world)); + } + + private static byte[] rawOperation( + String schema, byte[] accountBytes, byte[] worldBytes, byte[] inventoryBytes, String digest) { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, schema); + DraftAuthorizationFenceBinding.frame(out, accountBytes); + DraftAuthorizationFenceBinding.frame(out, worldBytes); + if (schema.equals(GameDesignPublicationOperationBinding.SCHEMA)) { + DraftAuthorizationFenceBinding.frame(out, inventoryBytes); + DraftAuthorizationFenceBinding.frame(out, digest); + } + return out.toByteArray(); + } + + private static void assertSqlState(Throwable failure, String expectedState) { + String sqlState = null; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sqlException) { + sqlState = sqlException.getSQLState(); + } + } + assertThat(sqlState).isEqualTo(expectedState); + } + + @Test + void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + Integer selectedSourceKeyWidth = + f.dsl + .fetchSingle( + "SELECT character_maximum_length FROM information_schema.columns" + + " WHERE table_schema = current_schema()" + + " AND table_name = 'account_selected_publication_sources'" + + " AND column_name = 'source_key'") + .get(0, Integer.class); + assertThat(selectedSourceKeyWidth).isEqualTo(2048); + String inventoryGuard = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('require_selected_inventory_operation_v2(bytea)'::regprocedure)") + .get(0, String.class); + assertThat(inventoryGuard) + .contains("coalesce(jsonb_agg(entry ORDER BY entry->>'regionTemplateId'), '[]'::JSONB)") + .contains("coalesce(jsonb_agg(entry ORDER BY entry->>'bindingTemplateId'), '[]'::JSONB)") + .contains( + "OR selector->'request'->'worldAffectedTuples' IS DISTINCT FROM expected_tuples") + .contains( + "OR model->'appliedEpochs' IS DISTINCT FROM expected_epochs OR expected_epochs = '[]'::JSONB") + .contains( + "Inventory differs from exact original selected Account, APPLIED graph or freeze"); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, order.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, "ABORTED"); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + byte[] receipt = out.toByteArray(); + String insert = + "INSERT INTO account_selected_publication_settlements" + + " (operation_id, fence_id, account_binding, publication_operation, game_design_outcome," + + " game_design_terminal, world_outcome, world_terminal, receipt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; + List malformed = + List.of( + new Object[] { + order.operationId(), + UUID.randomUUID(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + new byte[] {0}, + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + new byte[] {0}, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + new byte[] {0}, + "ABORTED", + new byte[] {0}, + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "PUBLISHED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + new byte[] {0} + }); + for (Object[] values : malformed) { + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, values))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + String publicInventoryJson = + new String( + operation.inventory().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + String graphDigest = operation.inventory().publicEvidence().sourceModel().graphDigest(); + byte[] substitutedInventory = + publicInventoryJson + .replace( + "\"graphDigest\":\"" + graphDigest + "\"", + "\"graphDigest\":\"sha256:" + "0".repeat(64) + "\"") + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] validOperation = operation.canonicalBytes(); + String tenantId = proof.world().request().canonicalTenantId().toString(); + String versionId = proof.world().request().canonicalVersionId().toString(); + String originalRegionTemplateId = + operation + .inventory() + .publicEvidence() + .sourceModel() + .regionGeneratorInputs() + .get(0) + .regionTemplateId() + .toString(); + String originalRegionInputs = + "\"regionGeneratorInputs\":[" + + inventoryRegionGeneratorInput(originalRegionTemplateId) + + "]"; + String unsortedRegionInputs = + "[" + + inventoryRegionGeneratorInput("00000000-0000-0000-0000-000000000002") + + "," + + inventoryRegionGeneratorInput("00000000-0000-0000-0000-000000000001") + + "]"; + assertThat(publicInventoryJson) + .contains("\"family\":\"REGION\",\"rowCount\":1") + .contains(originalRegionInputs); + byte[] unsortedRegionInventory = + publicInventoryJson + .replace( + "\"family\":\"REGION\",\"rowCount\":1", "\"family\":\"REGION\",\"rowCount\":2") + .replace(originalRegionInputs, "\"regionGeneratorInputs\":" + unsortedRegionInputs) + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] unsortedRegionOperation = + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + unsortedRegionInventory, + DraftAuthorizationFenceBinding.digest(unsortedRegionInventory)); + Object[] unsortedRegionSettlement = { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + unsortedRegionOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }; + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, unsortedRegionSettlement))) + .satisfies( + failure -> + assertSqlFailure( + failure, "23514", "Unsupported or unordered region generator input")); + String unsortedSpawnInputs = + "[" + + inventorySpawnBindingInput( + "00000000-0000-0000-0000-000000000002", + "00000000-0000-0000-0000-000000000003", + "00000000-0000-0000-0000-000000000004", + tenantId, + versionId) + + "," + + inventorySpawnBindingInput( + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000005", + "00000000-0000-0000-0000-000000000006", + tenantId, + versionId) + + "]"; + assertThat(publicInventoryJson) + .contains("\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":0") + .contains("\"spawnBindingCount\":0") + .contains("\"spawnBindingInputs\":[]"); + byte[] unsortedSpawnInventory = + publicInventoryJson + .replace( + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":0", + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":2") + .replace("\"spawnBindingCount\":0", "\"spawnBindingCount\":2") + .replace("\"spawnBindingInputs\":[]", "\"spawnBindingInputs\":" + unsortedSpawnInputs) + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] unsortedSpawnOperation = + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + unsortedSpawnInventory, + DraftAuthorizationFenceBinding.digest(unsortedSpawnInventory)); + Object[] unsortedSpawnSettlement = { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + unsortedSpawnOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }; + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, unsortedSpawnSettlement))) + .satisfies( + failure -> + assertSqlFailure( + failure, "23514", "Unsupported or unordered scoped spawn input")); + List invalidOperations = + List.of( + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + new byte[0], + DraftAuthorizationFenceBinding.digest(new byte[0])), + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + operation.inventory().canonicalBytes(), + "sha256:" + "0".repeat(64)), + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + substitutedInventory, + DraftAuthorizationFenceBinding.digest(substitutedInventory)), + rawOperation( + "game-design-publication-operation/v1", + order.canonicalBytes(), + proof.world().canonicalBytes(), + null, + null), + java.util.Arrays.copyOf(validOperation, validOperation.length + 1)); + for (byte[] invalidOperation : invalidOperations) { + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + insert, + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + invalidOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt))) + .satisfies(failure -> assertSqlState(failure, "23514")); + } + assertThat( + f.dsl.fetchCount(org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + + @Test + void sourceWriterCannotPassUncommittedSettlementAndCanRetryAfterItsCommit() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var executor = java.util.concurrent.Executors.newSingleThreadExecutor(); + try { + f.tx( + () -> { + repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes()); + int settlementPid = + f.dsl.fetchSingle("SELECT pg_backend_pid() AS pid").get("pid", Integer.class); + var writer = + executor.submit( + () -> + f.tx( + () -> { + int writerPid = + f.dsl + .fetchSingle("SELECT pg_backend_pid() AS pid") + .get("pid", Integer.class); + assertThat(writerPid).isNotEqualTo(settlementPid); + // The actual source trigger takes the same source locks NOWAIT. A + // pending + // transaction cannot release its protection to a different writer + // connection. + return f.changeRoleToAdmin(); + })); + assertThatThrownBy(() -> writer.get(10, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(org.jooq.exception.DataAccessException.class); + return null; + }); + assertThat(f.tx(f::changeRoleToAdmin).getRole()).isEqualTo("admin"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + } + + @Test + void authenticatesPreFreezeDistinctOrderReplaysExactlyAndBlocksSourceWritersAndDisclosure() + throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + var original = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var replay = service.authorize(issued.compact(), proof.selection(), issued.environment()); + assertThat(replay.canonicalBytes()).isEqualTo(original.canonicalBytes()); + assertThat(original.operationId()).isNotEqualTo(proof.original().operationId()); + assertThat(original.fenceId()).isNotEqualTo(proof.original().fenceId()); + assertThat(f.dsl.fetchCount(org.jooq.impl.DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat( + java.util.Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT world_evidence FROM account_selected_publication_authorizations" + + " WHERE operation_id = ?", + original.operationId()), + "Expected exact pre-freeze Account order") + .get("world_evidence", byte[].class)) + .isNull(); + // The immutable Account order is available before the separate World capture is correlated. + operation(original, proof.world()); + assertThat(original.sources()).hasSize(8); + var readOwner = + new AccountPublicationAuthorizationReadService( + new AccountPublicationAuthorizationRepository(f.dsl), f.manager, "test"); + var readRequest = + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence + .Request.create("test", original); + asGameDesign(() -> readOwner.requireHeld(readRequest)); + var mismatched = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + original.operationId(), UUID.randomUUID(), original.input(), original.sources()); + var unknown = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + UUID.randomUUID(), original.fenceId(), original.input(), original.sources()); + for (var rejected : List.of(mismatched, unknown)) { + assertThatThrownBy( + () -> + asGameDesign( + () -> + readOwner.requireHeld( + net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadEvidence.Request.create( + "test", rejected)))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + } + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(original.sources()); + return null; + })) + .hasMessageContaining("selected-publication"); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), original.sources(), new byte[] {1}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + // An exact retained replay remains possible while a later source change waits. + assertThat( + service + .authorize(issued.compact(), proof.selection(), issued.environment()) + .canonicalBytes()) + .isEqualTo(original.canonicalBytes()); + asGameDesign(() -> readOwner.requireHeld(readRequest)); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_authorizations SET fence_id = ?", + UUID.randomUUID()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> f.tx(() -> f.dsl.execute("DELETE FROM account_selected_publication_sources"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + var changed = selection(proof.selection().selectedCommit(), "changed notes"); + assertThatThrownBy(() -> service.authorize(issued.compact(), changed, issued.environment())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.authorize( + issued.compact() + "changed", proof.selection(), issued.environment())) + .isInstanceOf(RuntimeException.class); + // Original source/issuance identity is immutable even if a privileged SQL caller tries it. + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_authorizations SET issuance_fence = issuance_fence + 1"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_sources SET source_evidence = ?", + new byte[] {9}))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + + @Test + void earlierWaitingSourceChangeWinsAndDeniedAuthenticationCreatesNoOperation() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var source = + f.tx( + () -> + f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), source.sources(), new byte[] {2}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isTrue(); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + assertThatThrownBy( + () -> service.authorize(issued.compact(), proof.selection(), issued.environment())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source change is waiting"); + assertThatThrownBy( + () -> + service.authorize( + "unsigned-caller-claim", proof.selection(), issued.environment())) + .isInstanceOf(RuntimeException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isTrue(); + } + } + + @Test + void actualSourceWriterBlocksCreatorCaptureThenWinsBeforePublication() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + var accounts = new net.firedevops.firemud.accountservice.repository.AccountRepository(f.dsl); + var executor = java.util.concurrent.Executors.newSingleThreadExecutor(); + var attempt = + new java.util.concurrent.atomic.AtomicReference>(); + try { + f.tx( + () -> { + int blockerPid = + java.util.Objects.requireNonNull( + f.dsl.fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected PostgreSQL source-writer connection") + .get("pid", Integer.class); + var account = + java.util.Objects.requireNonNull( + accounts.findByIdForUpdate(f.account.getId()).orElseThrow(), + "Expected locked Account source before canonical role mutation"); + assertThat(account.getRole()).isNotEqualTo("player"); + attempt.set( + executor.submit( + () -> + service.authorize( + issued.compact(), proof.selection(), issued.environment()))); + long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); + Integer blockedPid = null; + while (System.nanoTime() < deadline && blockedPid == null) { + if (attempt.get().isDone()) { + try { + attempt.get().get(); + } catch (java.util.concurrent.ExecutionException failure) { + throw new AssertionError( + "Creator authorization failed before the Account-row wait was observed", + failure.getCause()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError( + "Interrupted while diagnosing completed creator authorization", + interrupted); + } + throw new AssertionError( + "Creator authorization succeeded before the source writer committed"); + } + // Activity snapshots are otherwise frozen for this blocker transaction. + f.dsl.fetch("SELECT pg_stat_clear_snapshot()"); + var blocked = + f.dsl.fetchOne( + "SELECT pid FROM pg_stat_activity WHERE datname = current_database()" + + " AND ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' LIMIT 1", + blockerPid); + if (blocked != null) blockedPid = blocked.get("pid", Integer.class); + else Thread.onSpinWait(); + } + assertThat(blockedPid) + .as("Distinct creator connection physically waits on source-writer Account row") + .isNotNull(); + assertThat(blockedPid).isNotEqualTo(blockerPid); + assertThat(attempt.get().isDone()).isFalse(); + // Actual guarded source write, held until this transaction commits. The old signed + // credential cannot authorize a publication from the newly changed Account state. + account.setRole("player"); + assertThat(accounts.save(account).getRole()).isEqualTo("player"); + return null; + }); + assertThatThrownBy(() -> attempt.get().get(10, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(RuntimeException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat(accounts.findById(f.account.getId()).orElseThrow().getRole()) + .isEqualTo("player"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + } + + @Test + void closureInventoryUpgradePreservesOriginalLegacySettlementsAndExactReplay() throws Exception { + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + java.time.Clock.systemUTC(), + "1010")) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var terminal = terminal(operation, outcome); + String phase = + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + byte[] receipt = + f.tx(() -> repository.settle(operation, terminal, phase, terminal.canonicalBytes())); + var before = publicationRetentionRows(f.dsl); + f.upgradeToCurrent(); + assertThat(publicationRetentionRows(f.dsl)).isEqualTo(before); + f.dsl.fetch( + "SELECT require_selected_inventory_operation_v2(?::bytea)", operation.canonicalBytes()); + assertThat( + f.tx( + () -> repository.settle(operation, terminal, phase, terminal.canonicalBytes()))) + .containsExactly(receipt); + assertThat(publicationRetentionRows(f.dsl)).isEqualTo(before); + } + } + } + + private static java.util.Map> publicationRetentionRows( + org.jooq.DSLContext dsl) { + var result = new java.util.LinkedHashMap>(); + for (String table : + java.util.List.of( + "account_selected_publication_authorizations", + "account_selected_publication_sources", + "account_selected_publication_settlements", + "account_control_ui_issuance_operations", + "flyway_schema_history")) { + String filter = + table.equals("flyway_schema_history") ? " WHERE version IS DISTINCT FROM '1011'" : ""; + result.put( + table, + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM " + + table + + " r" + + filter + + " ORDER BY 1") + .getValues(0, String.class)); + } + return result; + } + + private AccountControlUiOriginalOrderFixture fixture() throws Exception { + return new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary); + } + + private static void asGameDesign(Runnable action) { + io.grpc.Context.current() + .withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()) + .run(action); + } + + record Proof( + AuthoredDraftPublishSelectionBinding selection, + WorldPublishedStartLocationEvidence world, + DraftAuthorizationFenceBinding original) {} + + /** Closed World codec bytes copied in spirit from the existing isolated selector fixtures. */ + static Proof proof( + AccountControlUiOwnerSourcesFixture f, + net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService + .CapturedEnvironmentBoundary + environment) + throws Exception { + UUID version = UUID.randomUUID(), request = UUID.randomUUID(), commit = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + f.tenant, + version, + 17, + "test-private-tenant", + 11, + "test-private-tenant", + "NEW_GAME_ROW"); + List families = List.of("REGION", "ZONE", "ROOM"); + List templates = List.of(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); + List revisions = new ArrayList<>(); + List affected = new ArrayList<>(); + for (int i = 0; i < families.size(); i++) { + UUID revision = UUID.randomUUID(); + var mutation = new LinkedHashMap(); + mutation.put("logicalRevisionId", revision.toString()); + mutation.put("commitId", commit.toString()); + mutation.put("aggregateType", "WORLD_DESIGN_AGGREGATE_TYPE_" + families.get(i)); + mutation.put("aggregateId", templates.get(i).toString()); + if (i == 0) + mutation.put( + "freshGraphDeclaration", + Map.of( + "tenantId", + f.tenant.toString(), + "versionId", + version.toString(), + "startLocation", + Map.of( + "tenantId", + f.tenant.toString(), + "versionId", + version.toString(), + "roomTemplateId", + templates.get(2).toString()), + "familyCounts", + List.of( + "REGION", + "ZONE", + "ROOM", + "ROOM_EXIT", + "GENERATION_RULE", + "WORLD_ENTITY_SPAWN_BINDING") + .stream() + .map( + family -> + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_" + family, + "count", + families.contains(family) ? 1 : 0)) + .toList())); + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + revision, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + new tools.jackson.databind.ObjectMapper().writeValueAsString(mutation))); + affected.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + families.get(i), + templates.get(i).toString(), + "AGGREGATE", + templates.get(i).toString(), + "0")); + } + var draft = DraftCommitBinding.create(target, request, commit, "base-1", revisions, affected); + var selection = selection(draft, "selected publication proof"); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + request, + commit, + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + version, + "base-1", + "0", + draft.canonicalBytes(), + draft.canonicalBytes(), + draft.digest(), + f.tx(() -> f.authority.capture(f.account.getAccountUuid(), f.tenant, environment)) + .sources()); + UUID intake = UUID.randomUUID(); + var operation = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(operation, "world-draft-terminal-operation/v1"); + for (UUID id : + List.of(original.operationId(), request, commit, original.fenceId(), f.tenant, version)) + DraftAuthorizationFenceBinding.frame(operation, id.toString()); + DraftAuthorizationFenceBinding.frame(operation, draft.canonicalBytes()); + for (String value : + List.of( + "test", + f.tenant.toString(), + version.toString(), + original.operationId().toString(), + "17", + intake.toString(), + UUID.randomUUID().toString(), + "a".repeat(64), + UUID.randomUUID().toString(), + "b".repeat(64), + "c".repeat(64), + DraftAuthorizationFenceBinding.digest(original.canonicalBytes()))) + DraftAuthorizationFenceBinding.frame(operation, value); + DraftAuthorizationFenceBinding.frame(operation, original.canonicalBytes()); + List> rows = new ArrayList<>(); + for (int i = 0; i < revisions.size(); i++) { + var mapping = new LinkedHashMap(); + mapping.put("id", i + 1); + mapping.put("target_namespace", "test"); + mapping.put("canonical_tenant_id", f.tenant.toString()); + mapping.put("canonical_version_id", version.toString()); + mapping.put("family", families.get(i)); + mapping.put("template_id", templates.get(i).toString()); + mapping.put("private_row_key", 101 + i); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", original.operationId().toString()); + mapping.put("request_id", request.toString()); + mapping.put("commit_id", commit.toString()); + mapping.put("revision_id", revisions.get(i).revisionId().toString()); + mapping.put("revision_order", Integer.toString(i)); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + byte[] graph = + AccountControlUiAuthority.canonical( + Map.of( + "schemaVersion", + "2", + "canonicalTenantId", + f.tenant.toString(), + "canonicalVersionId", + version.toString(), + "rows", + rows)); + String graphDigest = DraftAuthorizationFenceBinding.digest(graph); + var receipt = + WorldDraftStartLocationEvidence.create( + "test", + original.operationId(), + request, + commit, + original.fenceId(), + DraftAuthorizationFenceBinding.digest(original.canonicalBytes()), + draft.digest(), + new RoomTemplateRef(f.tenant, version, templates.get(2)), + graphDigest); + var applied = new LinkedHashMap(); + applied.put("schema", "world-draft-graph-applied/v2"); + applied.put("status", "APPLIED"); + applied.put("operationBytesBase64", b64(operation.toByteArray())); + applied.put("graphBytesBase64", b64(graph)); + applied.put("graphDigest", graphDigest); + applied.put("startLocationReceiptBase64", b64(receipt.canonicalBytes())); + applied.put("startLocationReceiptDigest", receipt.receiptDigest()); + applied.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + Map.of( + "aggregateType", + u.aggregateType(), + "aggregateId", + u.aggregateId(), + "scopeType", + u.scopeType(), + "scopeId", + u.scopeId(), + "expectedEpoch", + "0", + "resultingEpoch", + "1")) + .toList()); + var worldRequest = + new WorldPublishedStartLocationEvidence.Request( + "test", + f.tenant, + version, + intake, + UUID.randomUUID(), + selection.intent().publishRequestId(), + selection.digest().substring(7), + 5, + PublicationDigestRequestBinding.full( + f.tenant.toString(), "17", selection.intent().publishRequestId()) + .derivedWorkflowIdentity(), + commit.toString(), + "b".repeat(64), + 3, + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList()); + return new Proof( + selection, + new WorldPublishedStartLocationEvidence( + worldRequest, + receipt.canonicalBytes(), + original.canonicalBytes(), + AccountControlUiAuthority.canonical(applied)), + original); + } + + private static String b64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static String inventorySpawnBindingInput( + String bindingTemplateId, + String roomTemplateId, + String entityTemplateId, + String tenantId, + String versionId) { + return "{\"bindingTemplateId\":\"" + + bindingTemplateId + + "\",\"entityReferenceKind\":\"ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID\",\"entityTemplateId\":\"" + + entityTemplateId + + "\",\"entityTemplateType\":\"ITEM\",\"entityTenantId\":\"" + + tenantId + + "\",\"entityVersionId\":\"" + + versionId + + "\",\"respawnDelaySeconds\":0,\"roomTemplateId\":\"" + + roomTemplateId + + "\",\"spawnCount\":1}"; + } + + private static String inventoryRegionGeneratorInput(String regionTemplateId) { + return "{\"generatorParams\":\"\",\"generatorType\":\"\",\"regionTemplateId\":\"" + + regionTemplateId + + "\"}"; + } + + private static void assertSqlFailure( + Throwable failure, String expectedState, String expectedMessage) { + java.sql.SQLException sqlFailure = null; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sqlException) sqlFailure = sqlException; + } + assertThat((Throwable) sqlFailure).isNotNull(); + var exactSqlFailure = + java.util.Objects.requireNonNull(sqlFailure, "Expected SQL failure from direct insert"); + assertThat(exactSqlFailure.getSQLState()).isEqualTo(expectedState); + assertThat(exactSqlFailure.getMessage()).contains(expectedMessage); + } + + private static AuthoredDraftPublishSelectionBinding selection( + DraftCommitBinding draft, String notes) { + return selection(draft, notes, "publication-request"); + } + + private static AuthoredDraftPublishSelectionBinding selection( + DraftCommitBinding draft, String notes, String publishRequestId) { + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + publishRequestId, + "5", + notes, + draft.requestId(), + draft.commitId(), + draft.digest()), + draft.target(), + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + draft.target(), + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java index 110290b1c5..53396c39fb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java @@ -148,19 +148,30 @@ void pendingWorldParticipationBlocksSourceMutationAndAbortWhileSettledKeepsPrior } @Test - void disclosureSourceLockPreservesTheExisting512ByteBoundWithoutAliasing() throws Exception { + void disclosureSourceLocksRetainCompleteCanonicalKeysThrough2048Utf8Bytes() throws Exception { Fixture fixture = new Fixture(false); fixture.begin(); - SourceEvidence boundary = source("x".repeat(499)); - assertThat(boundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(512); + SourceEvidence legacy = source("x".repeat(499)); + SourceEvidence longer = source("x".repeat(500)); + SourceEvidence boundary = source("x".repeat(2035)); + SourceEvidence unicodeBoundary = source("😀".repeat(508) + "xxx"); + assertThat(legacy.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(512); + assertThat(longer.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(513); + assertThat(boundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(2048); + assertThat(unicodeBoundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .hasSize(2048); - fixture.repository.lockDisclosureSources(List.of(boundary)); + // V76 and the shared SourceEvidence already own this exact byte bound; retain the whole key. + for (var source : List.of(legacy, longer, boundary, unicodeBoundary)) { + fixture.repository.lockDisclosureSources(List.of(source)); + } - assertThat(fixture.lockedKeys).containsExactly(boundary.key()); - assertThatThrownBy( - () -> fixture.repository.lockDisclosureSources(List.of(source("x".repeat(500))))) + assertThat(fixture.lockedKeys) + .containsExactly(legacy.key(), longer.key(), boundary.key(), unicodeBoundary.key()); + assertThat(longer.key()).startsWith(legacy.key()).isNotEqualTo(legacy.key()); + assertThatThrownBy(() -> source("x".repeat(2036))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("existing Account source-lock bound"); + .hasMessageContaining("2048 UTF-8 bytes"); } private static SourceChange sourceChange(SourceEvidence source) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java index b674202308..e9f6ee1030 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java @@ -10,14 +10,17 @@ import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; -import io.grpc.ManagedChannel; import io.grpc.Server; +import io.grpc.ServerInterceptors; import io.grpc.Status; import io.grpc.StatusRuntimeException; -import io.grpc.inprocess.InProcessChannelBuilder; -import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.stub.StreamObserver; import java.io.InputStream; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -26,23 +29,29 @@ import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; class StartSessionReservationEvidenceClientTest { private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; @@ -59,18 +68,34 @@ class StartSessionReservationEvidenceClientTest { Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC); private static final String LOGGING_ADMIN_TARGET = "logging-admin.internal:6565"; + @TempDir static Path pkiDirectory; + private static AccountStartSessionReservationProofPki pki; + private static CommonGrpcClientProperties accountTls; + + @BeforeAll + static void createControlledPki() throws Exception { + pki = AccountStartSessionReservationProofPki.create(pkiDirectory, "world-runtime"); + accountTls = pki.clientProperties(); + } + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + @Test - void repeatedInProcessReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exception { + void repeatedMtlsReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); List requests = new ArrayList<>(); - try (InProcessFixture fixture = - inProcessFixture( + try (MtlsFixture fixture = + mtlsFixture( request -> { requests.add(request); assertThat(io.grpc.Context.current().getDeadline()).isNotNull(); return validResponse(request, tuple.mutationDigest()); })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + StartSessionReservationEvidenceClient client = fixture.client(); ReadCurrentClaimEvidenceResponse issueFirst = client.readCurrentClaimEvidence( @@ -137,8 +162,8 @@ void repeatedInProcessReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exc void rejectsEveryResponseIdentityFieldUnknownFieldsAndStaleTimes() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicReference response = new AtomicReference<>(); - try (InProcessFixture fixture = inProcessFixture(request -> response.get())) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + try (MtlsFixture fixture = mtlsFixture(request -> response.get())) { + StartSessionReservationEvidenceClient client = fixture.client(); ReadCurrentClaimEvidenceResponse valid = validResponse( request(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE), @@ -193,8 +218,8 @@ void acceptsProducerObservationAfterLocalNowWhenClaimRemainsOrderedAndUnexpired( throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicReference response = new AtomicReference<>(); - try (InProcessFixture fixture = inProcessFixture(request -> response.get())) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + try (MtlsFixture fixture = mtlsFixture(request -> response.get())) { + StartSessionReservationEvidenceClient client = fixture.client(); ReadCurrentClaimEvidenceResponse futureObservation = validResponse( request(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE), @@ -221,13 +246,13 @@ void acceptsProducerObservationAfterLocalNowWhenClaimRemainsOrderedAndUnexpired( void invalidInputIsRejectedBeforeAnyRpc() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicInteger calls = new AtomicInteger(); - try (InProcessFixture fixture = - inProcessFixture( + try (MtlsFixture fixture = + mtlsFixture( request -> { calls.incrementAndGet(); return validResponse(request, tuple.mutationDigest()); })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + StartSessionReservationEvidenceClient client = fixture.client(); assertThatThrownBy( () -> @@ -278,12 +303,12 @@ void propagatesUnavailableAndStaleOwnerStatusesWithoutInterpretingThemAsEvidence throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicReference status = new AtomicReference<>(Status.UNAVAILABLE); - try (InProcessFixture fixture = - inProcessFixture( + try (MtlsFixture fixture = + mtlsFixture( request -> { throw status.get().asRuntimeException(); })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + StartSessionReservationEvidenceClient client = fixture.client(); assertThatThrownBy( () -> @@ -315,24 +340,14 @@ void propagatesUnavailableAndStaleOwnerStatusesWithoutInterpretingThemAsEvidence } @Test - void usesConfiguredLoggingEndpointTlsChannelAndStubCustomizer(@TempDir Path directory) - throws Exception { + void usesConfiguredLoggingEndpointAndTlsChannel(@TempDir Path directory) throws Exception { ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); endpoints.setLoggingAdminService(LOGGING_ADMIN_TARGET); CommonGrpcClientProperties tls = tlsProperties(directory); GrpcChannelFactory channelFactory = spy(new GrpcChannelFactory()); - AtomicInteger customizerCalls = new AtomicInteger(); - BlockingGrpcStubCustomizer customizer = - new BlockingGrpcStubCustomizer() { - @Override - public > T customize(T stub) { - customizerCalls.incrementAndGet(); - return stub; - } - }; StartSessionReservationEvidenceClient client = new StartSessionReservationEvidenceClient( - endpoints, tls, channelFactory, customizer, CLOCK); + endpoints, tls, channelFactory, "world-runtime", CLOCK); try { client.init(); @@ -340,59 +355,182 @@ public > T customize(T stub) { verify(channelFactory) .buildChannel( eq(LOGGING_ADMIN_TARGET), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); - assertThat(customizerCalls).hasValue(1); } finally { client.close(); } } - private static StartSessionReservationEvidenceClient client( - StartSessionReservationEvidenceServiceGrpc.StartSessionReservationEvidenceServiceBlockingStub - stub) - throws Exception { - StartSessionReservationClientTestAccess client = newClient(); - client.installStub(stub); - return client.client(); + @Test + void pinsConfiguredLoggingServerIndependentlyOfMutationTargetNamespace() throws Exception { + var targetTuple = tuple("other-target-runtime"); + try (var fixture = + mtlsFixture(request -> validResponse(request, targetTuple.mutationDigest()))) { + var evidence = + fixture + .client() + .readCurrentClaimEvidence( + targetTuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE); + assertThat(evidence.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(targetTuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + } } - private static StartSessionReservationClientTestAccess newClient() { - ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); - CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); - tls.setPlaintext(true); - StartSessionReservationEvidenceClient client = - new StartSessionReservationEvidenceClient( - endpoints, - tls, - mock(GrpcChannelFactory.class), - BlockingGrpcStubCustomizer.noop(), - CLOCK); - return new StartSessionReservationClientTestAccess(client); + @Test + void rejectsWrongAndMissingAuthenticatedServerIdentityBeforeRequestDelivery() throws Exception { + var calls = new AtomicInteger(); + for (String identity : List.of("wrong-workload", "wrong-namespace", "missing-identity")) { + try (var fixture = + mtlsFixture( + identity, + request -> { + calls.incrementAndGet(); + return validResponse(request, tuple().mutationDigest()); + })) { + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)) + .hasMessageContaining("exact authenticated server workload identity"); + } + } + assertThat(calls).hasValue(0); + } + + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeAnyRpc() throws Exception { + var calls = new AtomicInteger(); + try (var fixture = + mtlsFixture( + request -> { + calls.incrementAndGet(); + return validResponse(request, tuple().mutationDigest()); + })) { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + SessionContext.setContext("caller", List.of(), Map.of()); + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only caller"); + SessionContext.clear(); + assertThat(calls).hasValue(0); + assertThat(readIssue(fixture.client()).getControlPlaneRequestId()).isEqualTo(REQUEST_ID); + assertThat(calls).hasValue(1); + } + } + + @Test + void requiresUsableMutualTlsBeforeAnyTransportUse() throws Exception { + var plaintext = accountTls.copy(); + plaintext.setPlaintext(true); + var missing = accountTls.copy(); + missing.setCertChain(pkiDirectory.resolve("missing-certificate.pem").toString()); + var absentClientKey = accountTls.copy(); + absentClientKey.setPrivateKey(null); + var absentClientCertificate = accountTls.copy(); + absentClientCertificate.setCertChain(null); + for (var tls : List.of(plaintext, missing, absentClientKey, absentClientCertificate)) { + var factory = mock(GrpcChannelFactory.class); + try (var client = + new StartSessionReservationEvidenceClient( + new ServiceEndpointsProperties(), tls, factory, "world-runtime", CLOCK)) { + assertThatThrownBy(() -> readIssue(client)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mTLS"); + org.mockito.Mockito.verifyNoInteractions(factory); + } + } } - private static InProcessFixture inProcessFixture(EvidenceHandler handler) throws Exception { - String serverName = InProcessServerBuilder.generateName(); + private static ReadCurrentClaimEvidenceResponse readIssue( + StartSessionReservationEvidenceClient client) { + return client.readCurrentClaimEvidence( + tuple(), + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE); + } + + private static MtlsFixture mtlsFixture(EvidenceHandler handler) throws Exception { + return mtlsFixture("logging", handler); + } + + private static MtlsFixture mtlsFixture(String identity, EvidenceHandler handler) + throws Exception { + var serverIdentity = pki.server(identity); Server server = - InProcessServerBuilder.forName(serverName) - .directExecutor() + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) .addService( - new StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceImplBase() { - @Override - public void readCurrentClaimEvidence( - ReadCurrentClaimEvidenceRequest request, - StreamObserver responseObserver) { - try { - responseObserver.onNext(handler.read(request)); - responseObserver.onCompleted(); - } catch (StatusRuntimeException exception) { - responseObserver.onError(exception); - } - } - }) + ServerInterceptors.intercept( + new StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceImplBase() { + @Override + public void readCurrentClaimEvidence( + ReadCurrentClaimEvidenceRequest request, + StreamObserver responseObserver) { + assertThat(GrpcPeerIdentity.current().uri()) + .isEqualTo("spiffe://firemud/ns/world-runtime/sa/account-service"); + try { + responseObserver.onNext(handler.read(request)); + responseObserver.onCompleted(); + } catch (StatusRuntimeException exception) { + responseObserver.onError(exception); + } + } + }, + new GrpcPeerIdentityInterceptor(), + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + assertThat( + headers.get( + io.grpc.Metadata.Key.of( + "authorization", io.grpc.Metadata.ASCII_STRING_MARSHALLER))) + .isNull(); + return next.startCall(call, headers); + } + })) .build() .start(); - ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); - return new InProcessFixture(server, channel); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService("localhost:" + server.getPort()); + var client = + new StartSessionReservationEvidenceClient( + endpoints, accountTls, new GrpcChannelFactory(), "world-runtime", CLOCK); + try { + client.init(); + return new MtlsFixture(server, client); + } catch (Exception failure) { + client.close(); + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + throw failure; + } } private static ReadCurrentClaimEvidenceRequest request( @@ -440,11 +578,15 @@ private static StartSessionReservationEvidencePurpose toWirePurpose( } private static StartSessionPreAuthorizationReservationTuple tuple() { + return tuple("world-runtime"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String targetNamespace) { StartSessionOperatorAction action = new StartSessionOperatorAction( StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Scope(TENANT_ID, targetNamespace), new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), StartSessionOperatorAction.ExpectedVersion.ABSENT, new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), @@ -477,30 +619,12 @@ private interface EvidenceHandler { ReadCurrentClaimEvidenceResponse read(ReadCurrentClaimEvidenceRequest request); } - private record InProcessFixture(Server server, ManagedChannel channel) implements AutoCloseable { - private StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceBlockingStub - stub() { - return StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel); - } - + private record MtlsFixture(Server server, StartSessionReservationEvidenceClient client) + implements AutoCloseable { @Override public void close() throws Exception { - channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + client.close(); server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } } - - private record StartSessionReservationClientTestAccess( - StartSessionReservationEvidenceClient client) { - private void installStub( - StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceBlockingStub - stub) - throws Exception { - var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); - field.setAccessible(true); - field.set(client, stub); - } - } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java index 196f0f5945..19826e2a31 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java @@ -421,6 +421,13 @@ void owner(String compact) { AccountControlUiAuthority.canonical( Map.ofEntries( Map.entry("kid", "test-only-control"), + Map.entry( + "publicKeyFingerprint", + AccountJwtJwksTrustedSource.publicKeyFingerprint( + new AccountPublicJwksCache.PublicJwksSnapshot(pin, jwks), + pin, + "test-only-control") + .orElseThrow()), Map.entry("environmentId", pin.environmentId()), Map.entry("clusterId", pin.clusterId()), Map.entry("clusterIncarnationUid", pin.clusterIncarnationUid()), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java new file mode 100644 index 0000000000..98b3fce42e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java @@ -0,0 +1,246 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.Mockito.doThrow; +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 io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Context-level owner tests; supplied peer contexts are not actual TLS-positive proof. */ +class AccountPublicationAuthorizationReadServiceTest { + private final AccountPublicationAuthorizationRepository repository = + mock(AccountPublicationAuthorizationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final TransactionStatus status = mock(TransactionStatus.class); + private final AccountPublicationAuthorizationReadService service = + new AccountPublicationAuthorizationReadService(repository, transactions, "test"); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void commitsAnIndependentOwnerReadBeforeReturningHeld() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + asPeer("test", "game-design-service", () -> service.requireHeld(request)); + verify(repository).readHeld(any()); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(transactions).commit(status); + } + + @Test + void commitsAnIndependentWorldOwnerReadBeforeReturningHeld() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + asPeer("test", "world-management-service", () -> service.requireHeld(request)); + verify(repository).readHeld(any()); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(transactions).commit(status); + } + + @Test + void rejectsUnverifiedWrongWorkloadCrossNamespaceAndAmbientTransactionBeforeLookup() { + var request = request("test"); + assertCode(Status.Code.UNAUTHENTICATED, () -> service.requireHeld(request)); + for (String workload : + List.of("account-service", "game-session-service", "spring-cloud-gateway")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", workload, () -> service.requireHeld(request))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "game-design-service", () -> service.requireHeld(request))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "world-management-service", () -> service.requireHeld(request))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request("other")))); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + verifyNoInteractions(repository, transactions); + } + + @Test + void absentOrChangedOwnerStateCannotProduceHeldAndStorageFailureFailsClosed() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + doThrow(new IllegalArgumentException("absent or changed")).when(repository).readHeld(any()); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + doThrow(new org.jooq.exception.DataAccessException("offline")).when(repository).readHeld(any()); + assertCode( + Status.Code.UNAVAILABLE, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + } + + @Test + void grpcAuthenticatesBeforeDecodingMalformedCallerCarriers() { + var endpoint = new AccountPublicationAuthorizationReadGrpcService(service, "test"); + var error = new AtomicReference(); + StreamObserver observer = + new StreamObserver<>() { + @Override + public void onNext(ReadHeldPublicationAuthorizationResponse value) { + throw new AssertionError("Malformed request cannot return HELD"); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() { + throw new AssertionError("Malformed request cannot complete"); + } + }; + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer); + assertThat(Status.fromThrowable(error.get()).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + asPeer( + "test", + "account-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + asPeer( + "other", + "world-management-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + asPeer( + "test", + "world-management-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository, transactions); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(action); + } + + private static AccountPublicationAuthorizationReadEvidence.Request request(String namespace) { + UUID actor = UUID.randomUUID(), + tenant = UUID.randomUUID(), + version = UUID.randomUUID(), + revision = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 17, "test-tenant", 11, "test-tenant", "NEW_GAME_ROW"); + var draft = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", revision, DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "ROOM", + "room", + "ROOM_SCOPE", + "room", + "0"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "proof", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + return AccountPublicationAuthorizationReadEvidence.Request.create(namespace, binding); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java new file mode 100644 index 0000000000..b272b7e034 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountPublicationAuthorizationServiceTest { + @Test + void persistenceCannotBeCalledWithoutTheWritableAccountOwnerTransaction() { + var dsl = mock(DSLContext.class); + var repository = new AccountPublicationAuthorizationRepository(dsl); + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable READ_COMMITTED"); + verifyNoInteractions(dsl); + } + + @Test + void readOnlyOrDifferentIsolationCannotMintPublicationPermission() { + var dsl = mock(DSLContext.class); + var repository = new AccountPublicationAuthorizationRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + java.sql.Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + java.sql.Connection.TRANSACTION_REPEATABLE_READ); + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java new file mode 100644 index 0000000000..ed43b1f7a7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java @@ -0,0 +1,578 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +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.ArgumentMatchers.same; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationOrderGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationOrderService; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Native loopback mTLS transport proof for the unregistered selected-publication producer. */ +class AccountSelectedDraftPublicationOrderGrpcMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_ACCOUNT_URI = + "spiffe://firemud/ns/other-test/sa/account-service"; + private static final String WRONG_SERVER_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String WRONG_CLIENT_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_NAMESPACE_CLIENT_URI = + "spiffe://firemud/ns/other-test/sa/game-design-service"; + + @TempDir static Path temporaryDirectory; + private static TestPki pki; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @Test + void authenticatedGameDesignClientReachesEnvironmentCaptureThenUnresolvedOwner() + throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenThrow(Status.FAILED_PRECONDITION.asRuntimeException()); + + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + var client = newClient(server.port(), pki.gameDesignClient())) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + + assertThat(server.handlerCalls()).hasValue(1); + var calls = inOrder(terms, owner); + calls.verify(terms).captureCurrentEnvironmentBoundary(); + calls.verify(owner).authorize(eq(CREDENTIAL), any(), same(captured)); + } + } + + @Test + void trustedWrongServiceAndNamespaceGameDesignCallersAreDeniedBeforeCapture() throws Exception { + for (TestIdentity identity : List.of(pki.wrongServiceClient(), pki.otherNamespaceClient())) { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + var client = newClient(server.port(), identity)) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(1); + verifyNoInteractions(terms, owner); + } + } + } + + @Test + void missingClientCertificateFailsTlsBeforeReceiverOrOwner() throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + ClientTransport client = newClientWithoutIdentity(server.port())) { + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request()); + + assertThatThrownBy(() -> client.authorize(wire)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "missing client certificate must fail during TLS negotiation: %s", + failure) + .isTrue()); + + assertThat(server.handlerCalls()).hasValue(0); + verifyNoInteractions(terms, owner); + } + } + + @Test + void creatorCredentialMetadataIsRequiredBeforeEnvironmentCapture() throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + ClientTransport client = newClientWithIdentity(server.port(), pki.gameDesignClient())) { + assertThatThrownBy( + () -> client.authorize(AccountSelectedPublicationOrderGrpcCodec.toRequest(request()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + assertThat(server.handlerCalls()).hasValue(1); + verifyNoInteractions(terms, owner); + } + } + + @Test + void clientRejectsTrustedWrongServiceAndNamespaceAccountServerIdentities() throws Exception { + for (TestIdentity identity : List.of(pki.wrongServiceServer(), pki.otherNamespaceServer())) { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(identity, owner, terms); + var client = newClient(server.port(), pki.gameDesignClient())) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(0); + verifyNoInteractions(terms, owner); + } + } + } + + private static TransportServer startServer( + TestIdentity serverIdentity, + AccountSelectedDraftPublicationOrderService owner, + AccountHostedTermsService terms) + throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + ServerInterceptor countHandlerCalls = + new ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + handlerCalls.incrementAndGet(); + return next.startCall(call, headers); + } + }; + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new AccountSelectedDraftPublicationOrderGrpcService(owner, terms, NAMESPACE), + countHandlerCalls, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new TransportServer(server, handlerCalls); + } + + private static AccountSelectedPublicationOrderClient newClient(int port, TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + return new AccountSelectedPublicationOrderClient( + endpoints, + pki.clientProperties(temporaryDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ClientTransport newClientWithoutIdentity(int port) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCaCert(pki.caCertificatePem().toString()); + ManagedChannel channel = + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false); + return new ClientTransport(channel); + } + + private static ClientTransport newClientWithIdentity(int port, TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var channel = + new GrpcChannelFactory() + .buildChannel( + endpoints.getAccountService(), + 6565, + pki.clientProperties(temporaryDirectory, identity), + false); + return new ClientTransport(channel); + } + + private static AccountSelectedPublicationOrderGrpcCodec.Request request() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19, "tenant-key", 42, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "fixture", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, CREDENTIAL); + } + + private static final String CREDENTIAL = "original.secret.credential"; + + private record TransportServer(Server server, AtomicInteger handlerCalls) + implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private void authorize( + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest request) { + AccountSelectedPublicationOrderServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .authorizeSelectedPublication(request); + } + + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback gRPC client did not terminate"); + } + } + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + Path caCertificatePem, + TestIdentity accountServer, + TestIdentity wrongServiceServer, + TestIdentity otherNamespaceServer, + TestIdentity gameDesignClient, + TestIdentity wrongServiceClient, + TestIdentity otherNamespaceClient) { + private static final String STORE_PASSWORD = "test-only-store-password"; + + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("selected-publication-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD selected publication test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("selected-publication-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var ca = readCertificate(caFile); + return new TestPki( + ca, + caFile, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-service-server", WRONG_SERVER_URI, true), + issueIdentity( + directory, caStore, caFile, "other-namespace-server", WRONG_ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false), + issueIdentity( + directory, caStore, caFile, "wrong-service-client", WRONG_CLIENT_URI, false), + issueIdentity( + directory, + caStore, + caFile, + "other-namespace-client", + OTHER_NAMESPACE_CLIENT_URI, + false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + writePem( + directory.resolve(identity.alias() + ".client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + writePem( + directory.resolve(identity.alias() + ".client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()) + .toString()); + tls.setCaCert(caCertificatePem.toString()); + tls.setPlaintext(false); + return tls; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + ArrayList command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java new file mode 100644 index 0000000000..53a1c94d72 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java @@ -0,0 +1,305 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Context-level receiver units, not mounted-certificate or real Account currentness proof. */ +class AccountSelectedDraftPublicationOrderGrpcServiceTest { + private static final String CREDENTIAL = "original.secret.credential"; + private final AccountSelectedDraftPublicationOrderService owner = + mock(AccountSelectedDraftPublicationOrderService.class); + private final AccountHostedTermsService terms = mock(AccountHostedTermsService.class); + private final AccountSelectedDraftPublicationOrderGrpcService receiver = + new AccountSelectedDraftPublicationOrderGrpcService(owner, terms, "test"); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeMalformedDecodeAndCaptureAndDeniesWorld() { + assertThat(invoke(null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String workload : + List.of("world-management-service", "account-service", "game-session-service")) { + assertThat(peer("test", workload, () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(peer("other", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + authorized(() -> invoke(AuthorizeSelectedPublicationRequest.getDefaultInstance())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner, terms); + } + + @Test + void boundInterceptorAuthenticatesBeforeTouchingMalformedCredentialMetadata() { + var headers = mock(io.grpc.Metadata.class); + assertThat(boundCode(headers)).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer("test", "world-management-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(headers, owner, terms); + var malformed = new io.grpc.Metadata(); + malformed.put( + io.grpc.Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + io.grpc.Metadata.BINARY_BYTE_MARSHALLER), + new byte[] {(byte) 128}); + assertThat(peer("test", "game-design-service", () -> boundCode(malformed))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer("test", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(owner, terms); + } + + @SuppressWarnings("unchecked") + private Status.Code boundCode(io.grpc.Metadata headers) { + var method = + (io.grpc.ServerMethodDefinition< + AuthorizeSelectedPublicationRequest, AuthorizeSelectedPublicationResponse>) + receiver.bindService().getMethods().iterator().next(); + io.grpc.ServerCall + call = mock(io.grpc.ServerCall.class); + method.getServerCallHandler().startCall(call, headers); + var status = org.mockito.ArgumentCaptor.forClass(Status.class); + org.mockito.Mockito.verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any()); + return status.getValue().getCode(); + } + + @Test + void deniesAmbientSqlNamespaceAndUnknownFieldsBeforeCapture() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(authorized(() -> invoke(null)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThat(authorized(() -> invoke(null)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clearSynchronization(); + var request = request(); + assertThat( + authorized(() -> invoke(request.toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + authorized( + () -> + invoke( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner, terms); + } + + @Test + void + automaticallyCapturesAccountEnvironmentAndHandsOffOriginalCredentialAndSelectionOutsideSql() { + var request = request(); + var decoded = AccountSelectedPublicationOrderGrpcCodec.fromRequest(request, CREDENTIAL); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + UUID actor = UUID.randomUUID(); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + actor, decoded.selection()), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + when(terms.captureCurrentEnvironmentBoundary()) + .thenAnswer( + call -> { + outsideSql(); + return captured; + }); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenAnswer( + call -> { + outsideSql(); + assertThat( + call.getArgument(1, AuthoredDraftPublishSelectionBinding.class) + .canonicalBytes()) + .isEqualTo(decoded.originalSelection()); + return binding; + }); + var result = authorized(() -> invoke(request)); + assertThat(result.error()).isNull(); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse(decoded, result.response()) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + assertThat(result.response().toString()).doesNotContain(CREDENTIAL); + } + + @Test + void unavailableCaptureReturnsSanitizedFailure() { + when(terms.captureCurrentEnvironmentBoundary()) + .thenThrow(new IllegalStateException(CREDENTIAL)); + var denied = authorized(() -> invoke(request())); + assertThat(denied.code()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + verifyNoInteractions(owner); + } + + @Test + void secretBearingOwnerStatusReturnsOnlyItsCodeAndSanitizedDescription() { + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenThrow(Status.PERMISSION_DENIED.withDescription(CREDENTIAL).asRuntimeException()); + var denied = authorized(() -> invoke(request())); + assertThat(denied.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + assertThat(denied.error().getCause()).isNull(); + } + + private record Result(AuthorizeSelectedPublicationResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private Result invoke(AuthorizeSelectedPublicationRequest request) { + var response = new AtomicReference(); + var error = new AtomicReference(); + receiver.authorizeSelectedPublication( + request, + new io.grpc.stub.StreamObserver<>() { + @Override + public void onNext(AuthorizeSelectedPublicationResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() {} + }); + return new Result(response.get(), error.get()); + } + + private static void outsideSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static T authorized(java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, + AccountSelectedPublicationOrderCredentials.Credential.of(CREDENTIAL)); + var prior = context.attach(); + try { + return peer("test", "game-design-service", action); + } finally { + context.detach(prior); + } + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static AuthorizeSelectedPublicationRequest request() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19, "tenant-key", 42, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "fixture", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return AccountSelectedPublicationOrderGrpcCodec.toRequest( + AccountSelectedPublicationOrderGrpcCodec.Request.create("test", selected, CREDENTIAL)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java new file mode 100644 index 0000000000..375ee54ec9 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java @@ -0,0 +1,292 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.ArgumentMatchers.same; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Composition ordering units with stipulated peer context and mocked owner evidence/producer. These + * fixture values are not genuine cross-owner mTLS, creator or PostgreSQL proof. + */ +class AccountSelectedDraftPublicationOrderServiceTest { + private static final String COMPACT_JWT = "original-compact-creator-jwt"; + private final AuthoredDraftPublishSelectionReadClient client = + mock(AuthoredDraftPublishSelectionReadClient.class); + private final AccountPublicationAuthorizationService owner = + mock(AccountPublicationAuthorizationService.class); + private final CapturedEnvironmentBoundary environment = mock(CapturedEnvironmentBoundary.class); + private final AccountSelectedDraftPublicationOrderService service = + new AccountSelectedDraftPublicationOrderService(client, owner, "test"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void deniesMissingWrongServiceAndCrossNamespacePeerBeforeTransportOrOwner() { + // Null lookup also proves authentication precedes carrier inspection. + assertCode(Status.Code.UNAUTHENTICATED, () -> service.authorize(null, null, null)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", workload, () -> service.authorize(null, null, null))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "game-design-service", () -> service.authorize(null, null, null))); + verifyNoInteractions(client, owner); + } + + @Test + void rejectsActualTransactionAndSynchronizationBeforeRemoteRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + verifyNoInteractions(client, owner); + } + + @Test + void exactReadCompletesBeforeOwnerReceivesUnchangedCreatorJwtEnvironmentAndSelection() { + var lookup = selection(); + var result = mock(AccountPublicationAuthorizationBinding.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var request = + invocation.getArgument( + 0, AuthoredDraftPublishSelectionReadEvidence.Request.class); + assertThat(request.targetNamespace()).isEqualTo("test"); + assertThat(request.originalSelection()).containsExactly(lookup.canonicalBytes()); + assertThat(request.selectionDigest()).isEqualTo(lookup.digest()); + return fixtureEvidence(request); + }); + when(owner.authorize(eq(COMPACT_JWT), eq(lookup), same(environment))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return result; + }); + assertThat(authorized(() -> service.authorize(COMPACT_JWT, lookup, environment))) + .isSameAs(result); + var request = ArgumentCaptor.forClass(AuthoredDraftPublishSelectionReadEvidence.Request.class); + var order = inOrder(client, owner); + order.verify(client).read(request.capture()); + order.verify(owner).authorize(eq(COMPACT_JWT), eq(lookup), same(environment)); + order.verifyNoMoreInteractions(); + assertThat(request.getValue().binding()).isEqualTo(lookup); + } + + @Test + void missingOrSubstitutedReadbackNeverInvokesAccountOwner() { + when(client.read(any())).thenReturn(null); + assertThatThrownBy( + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))) + .isInstanceOf(IllegalStateException.class); + for (String changed : List.of("namespace", "readIdentity", "selection")) { + doAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, AuthoredDraftPublishSelectionReadEvidence.Request.class); + if ("selection".equals(changed)) { + var original = request.binding(); + var intent = original.intent(); + var replaced = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + "changed notes", + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()), + original.target(), + original.selectedCommit(), + new VisibilityFence( + original.target(), + original.fenceRequestId(), + original.fenceCommitId(), + original.fenceInputDigest(), + original.fenceResultVectorJson(), + OffsetDateTime.parse(original.fenceCreatedAt()))); + return fixtureEvidence( + new AuthoredDraftPublishSelectionReadEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + request.readRequestId(), + replaced.canonicalBytes(), + replaced.digest())); + } + return fixtureEvidence( + new AuthoredDraftPublishSelectionReadEvidence.Request( + request.schemaVersion(), + "namespace".equals(changed) ? "other" : request.targetNamespace(), + "readIdentity".equals(changed) + ? UUID.randomUUID() + : request.readRequestId(), + request.originalSelection(), + request.selectionDigest())); + }) + .when(client) + .read(any()); + assertThatThrownBy( + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from the exact publication order request"); + } + verifyNoInteractions(owner); + } + + @Test + void unavailableOrDeniedSelectionReadNeverInvokesOwner() { + for (Status failure : List.of(Status.UNAVAILABLE, Status.NOT_FOUND, Status.PERMISSION_DENIED)) { + doThrow(failure.asRuntimeException()).when(client).read(any()); + assertCode( + failure.getCode(), + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + } + verifyNoInteractions(owner); + } + + @Test + void lowerLevelCreatorDenialPropagatesAfterExactOwnerRead() { + when(client.read(any())).thenAnswer(invocation -> fixtureEvidence(invocation.getArgument(0))); + when(owner.authorize(any(), any(), any())) + .thenThrow(Status.PERMISSION_DENIED.asRuntimeException()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + var order = inOrder(client, owner); + order.verify(client).read(any()); + order.verify(owner).authorize(eq(COMPACT_JWT), eq(selection()), same(environment)); + } + + private static AuthoredDraftPublishSelectionReadEvidence fixtureEvidence( + AuthoredDraftPublishSelectionReadEvidence.Request request) { + var evidence = mock(AuthoredDraftPublishSelectionReadEvidence.class); + when(evidence.request()).thenReturn(request); + return evidence; + } + + private static T authorized(Supplier action) { + return asPeer("test", "game-design-service", action); + } + + private static T asPeer(String namespace, String workload, Supplier action) { + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static AuthoredDraftPublishSelectionBinding selection() { + UUID tenant = uuid("22222222-2222-4222-8222-222222222222"); + UUID version = uuid("33333333-3333-4333-8333-333333333333"); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "5", + "test selection", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return selected; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java new file mode 100644 index 0000000000..bb106f9ad1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java @@ -0,0 +1,403 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Composition seams only: canonical codec outputs, owner results and peer identity are stipulated + * here. Actual PostgreSQL, codec integrity and mounted-certificate mTLS are separate proof. + */ +class AccountSelectedDraftPublicationSettlementServiceTest { + private final AccountPublicationAuthorizationRepository repository = + mock(AccountPublicationAuthorizationRepository.class); + private final GameDesignPublicationTerminalClient gameDesign = + mock(GameDesignPublicationTerminalClient.class); + private final WorldPublicationTerminalReadClient world = + mock(WorldPublicationTerminalReadClient.class); + private final OwnerTransactions transactions = new OwnerTransactions(); + private final AccountSelectedDraftPublicationSettlementService service = + new AccountSelectedDraftPublicationSettlementService( + repository, gameDesign, world, transactions, "test"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeMalformedDecodeOrOwnerReads() { + assertCode(Status.Code.UNAUTHENTICATED, () -> service.settle(null)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("test", workload, () -> service.settle(new byte[] {0}))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("other", "game-design-service", () -> service.settle(null))); + assertThatThrownBy(() -> authorized(() -> service.settle(new byte[] {0}))) + .isInstanceOf(RuntimeException.class); + verifyNoInteractions(repository, gameDesign, world); + assertThat(transactions.begins).isZero(); + } + + @Test + void deniesAmbientTransactionAndSynchronizationBeforeDecode() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null))); + verifyNoInteractions(repository, gameDesign, world); + } + + @Test + void agreeingOwnersCommitThenSeparatelyReadBackAndRetriesUseFreshReadCorrelations() { + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = new CodecOutputs(outcome)) { + var gameDesignReads = new ArrayList(); + var worldReads = new ArrayList(); + doAnswer( + call -> { + assertNoSql(); + var request = + call.getArgument( + 0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class); + gameDesignReads.add(request.readRequestId()); + return gameDesignEvidence(request, fixture.terminal); + }) + .when(gameDesign) + .read(any()); + doAnswer( + call -> { + assertNoSql(); + var request = + call.getArgument(0, WorldPublicationTerminalReadEvidence.Request.class); + worldReads.add(request.readRequestId()); + return worldEvidence(request, fixture.terminal, request.expectedWorldOutcome()); + }) + .when(world) + .read(any()); + var calls = new AtomicInteger(); + int priorCommits = transactions.commits; + byte[] receipt = new byte[] {9, 8}; + doAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_READ_COMMITTED); + assertThat(transactions.commits - priorCommits) + .isEqualTo(calls.getAndIncrement()); + assertThat(call.getArgument(0, GameDesignPublicationOperationBinding.class)) + .isSameAs(fixture.operation); + assertThat(call.getArgument(1, GameDesignPublicationTerminalEvidence.class)) + .isSameAs(fixture.terminal); + assertThat(call.getArgument(2, String.class)).isEqualTo(fixture.phase.name()); + assertThat(call.getArgument(3, byte[].class)) + .containsExactly(fixture.terminalBytes); + return receipt.clone(); + }) + .when(repository) + .settle(any(), any(), anyString(), any()); + assertThat(authorized(() -> service.settle(fixture.operationBytes))) + .containsExactly(receipt); + assertThat(authorized(() -> service.settle(fixture.operationBytes))) + .containsExactly(receipt); + assertThat(calls).hasValue(4); + assertThat(transactions.commits - priorCommits).isEqualTo(4); + assertThat(gameDesignReads).hasSize(2).doesNotHaveDuplicates(); + assertThat(worldReads).hasSize(2).doesNotHaveDuplicates(); + assertNoSql(); + } + } + } + + @Test + void missingSubstitutedOrUnavailableGameDesignResultNeverReadsWorldOrWritesAccount() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(gameDesign.read(any())).thenReturn(null); + assertFailure(fixture); + doAnswer( + call -> { + var request = + call.getArgument( + 0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class); + return gameDesignEvidence( + new GameDesignPublicationTerminalReadEvidence.ReadRequest( + 1, "test", UUID.randomUUID(), request.operationBytes()), + fixture.terminal); + }) + .when(gameDesign) + .read(any()); + assertFailure(fixture); + var substituted = mock(GameDesignPublicationTerminalEvidence.class); + when(substituted.canonicalBytes()).thenReturn(new byte[] {99}); + doAnswer(call -> gameDesignEvidence(call.getArgument(0), substituted)) + .when(gameDesign) + .read(any()); + assertFailure(fixture); + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(gameDesign).read(any()); + assertCode( + Status.Code.UNAVAILABLE, () -> authorized(() -> service.settle(fixture.operationBytes))); + verifyNoInteractions(world, repository); + assertThat(transactions.begins).isZero(); + } + } + + @Test + void + worldNamespaceMismatchMissingChangedRequestTerminalPhaseAndUnavailableKeepAccountUntouched() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(fixture.worldRequest.targetNamespace()).thenReturn("other"); + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(gameDesign, world, repository); + when(fixture.worldRequest.targetNamespace()).thenReturn("test"); + when(gameDesign.read(any())) + .thenAnswer(call -> gameDesignEvidence(call.getArgument(0), fixture.terminal)); + for (String changed : + List.of("missing", "correlation", "namespace", "phase", "terminal", "operation")) { + doAnswer( + call -> { + var request = + call.getArgument(0, WorldPublicationTerminalReadEvidence.Request.class); + if (changed.equals("missing")) return null; + var response = worldEvidence(request, fixture.terminal, fixture.phase); + if (changed.equals("correlation") || changed.equals("namespace")) { + // Mock the returned request itself to exercise a substituted owner echo without + // treating a structurally invalid carrier as a genuine codec result. + when(response.request()) + .thenReturn(mock(WorldPublicationTerminalReadEvidence.Request.class)); + } + if (changed.equals("phase")) + when(response.worldOutcome()) + .thenReturn(WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED); + if (changed.equals("terminal")) + when(response.worldTerminalEvidence()).thenReturn(new byte[] {99}); + if (changed.equals("operation")) { + var other = mock(GameDesignPublicationTerminalEvidence.class); + when(other.operationBytes()).thenReturn(new byte[] {99}); + when(response.terminalEvidence()).thenReturn(other); + } + return response; + }) + .when(world) + .read(any()); + assertFailure(fixture); + } + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(world).read(any()); + assertCode( + Status.Code.UNAVAILABLE, () -> authorized(() -> service.settle(fixture.operationBytes))); + verifyNoInteractions(repository); + assertThat(transactions.begins).isZero(); + } + } + + @Test + void changedPostCommitReadbackCannotReturnSuccess() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(gameDesign.read(any())) + .thenAnswer(call -> gameDesignEvidence(call.getArgument(0), fixture.terminal)); + when(world.read(any())) + .thenAnswer(call -> worldEvidence(call.getArgument(0), fixture.terminal, fixture.phase)); + when(repository.settle(any(), any(), anyString(), any())) + .thenReturn(new byte[] {1}, new byte[] {2}); + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs"); + assertThat(transactions.commits).isEqualTo(2); + assertNoSql(); + } + } + + private void assertFailure(CodecOutputs fixture) { + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(RuntimeException.class); + } + + private static GameDesignPublicationTerminalReadEvidence.ReadResult gameDesignEvidence( + GameDesignPublicationTerminalReadEvidence.ReadRequest request, + GameDesignPublicationTerminalEvidence terminal) { + var result = mock(GameDesignPublicationTerminalReadEvidence.ReadResult.class); + when(result.request()).thenReturn(request); + when(result.terminalEvidence()).thenReturn(java.util.Optional.ofNullable(terminal)); + return result; + } + + private static WorldPublicationTerminalReadEvidence worldEvidence( + WorldPublicationTerminalReadEvidence.Request request, + GameDesignPublicationTerminalEvidence terminal, + WorldPublicationTerminalReadEvidence.WorldOutcome phase) { + byte[] terminalBytes = terminal.canonicalBytes(); + var result = mock(WorldPublicationTerminalReadEvidence.class); + when(result.request()).thenReturn(request); + when(result.terminalEvidence()).thenReturn(terminal); + when(result.worldTerminalEvidence()).thenReturn(terminalBytes); + when(result.worldOutcome()).thenReturn(phase); + return result; + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static T authorized(Supplier action) { + return peer("test", "game-design-service", action); + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static final class CodecOutputs implements AutoCloseable { + final byte[] operationBytes = new byte[] {11}; + final byte[] terminalBytes = new byte[] {22}; + final GameDesignPublicationOperationBinding operation = + mock(GameDesignPublicationOperationBinding.class); + final GameDesignPublicationTerminalEvidence terminal = + mock(GameDesignPublicationTerminalEvidence.class); + final WorldPublishedStartLocationEvidence.Request worldRequest = + mock(WorldPublishedStartLocationEvidence.Request.class); + final WorldPublicationTerminalReadEvidence.WorldOutcome phase; + final org.mockito.MockedStatic operations = + mockStatic(GameDesignPublicationOperationBinding.class); + final org.mockito.MockedStatic terminals = + mockStatic(GameDesignPublicationTerminalEvidence.class); + + CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome outcome) { + var world = mock(WorldPublishedStartLocationEvidence.class); + // Stipulated codec outputs include identities required by the current read correlation. + var account = + mock( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding + .class); + var input = + mock( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding + .PreallocationInput.class); + var selection = + mock( + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.class); + var intent = + mock( + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding + .PublishIntent.class); + when(operation.account()).thenReturn(account); + when(account.operationId()).thenReturn(UUID.randomUUID()); + when(account.fenceId()).thenReturn(UUID.randomUUID()); + when(account.input()).thenReturn(input); + when(input.selection()).thenReturn(selection); + when(selection.intent()).thenReturn(intent); + when(intent.selectedCommitRequestId()).thenReturn(UUID.randomUUID()); + when(intent.selectedCommitId()).thenReturn(UUID.randomUUID()); + when(operation.canonicalBytes()).thenReturn(operationBytes); + when(operation.world()).thenReturn(world); + when(world.request()).thenReturn(worldRequest); + when(worldRequest.targetNamespace()).thenReturn("test"); + when(terminal.canonicalBytes()).thenReturn(terminalBytes); + when(terminal.operationBytes()).thenReturn(operationBytes); + when(terminal.worldEvidence()).thenReturn(world); + when(terminal.outcome()).thenReturn(outcome); + operations + .when(() -> GameDesignPublicationOperationBinding.fromStored(operationBytes)) + .thenReturn(operation); + terminals + .when(() -> GameDesignPublicationTerminalEvidence.fromStored(terminalBytes)) + .thenReturn(terminal); + phase = + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED + : WorldPublicationTerminalReadEvidence.WorldOutcome.ABORTED; + } + + @Override + public void close() { + terminals.close(); + operations.close(); + } + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java new file mode 100644 index 0000000000..285cca35ad --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java @@ -0,0 +1,142 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationSettlementService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedPublicationSettlementGrpcService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Receiver identity/ordering units; synthetic peer context is not authenticated TLS proof. */ +class AccountSelectedPublicationSettlementGrpcServiceTest { + private static final String NAMESPACE = "publication-runtime"; + private static final String GAME_DESIGN_URI = + "spiffe://firemud/ns/publication-runtime/sa/game-design-service"; + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactGameDesignBeforeMalformedRequestOrOwnerAccess() { + var owner = mock(AccountSelectedDraftPublicationSettlementService.class); + var receiver = new AccountSelectedPublicationSettlementGrpcService(owner, NAMESPACE); + var malformed = SettleSelectedPublicationRequest.getDefaultInstance(); + + assertCode(Status.Code.UNAUTHENTICATED, invoke(receiver, null, malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, + identity("spiffe://firemud/ns/other-runtime/sa/game-design-service"), + malformed)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, + identity("spiffe://firemud/ns/publication-runtime/sa/" + workload), + malformed)); + } + SessionContext.setContext("test-user", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, invoke(receiver, identity(GAME_DESIGN_URI), malformed)); + verifyNoInteractions(owner); + } + + @Test + void deniesAmbientSqlAndClosedEnvelopeErrorsBeforeOwnerCall() { + var owner = mock(AccountSelectedDraftPublicationSettlementService.class); + var receiver = new AccountSelectedPublicationSettlementGrpcService(owner, NAMESPACE); + var peer = identity(GAME_DESIGN_URI); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, peer, null)); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, peer, null)); + TransactionSynchronizationManager.clearSynchronization(); + + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, peer, null)); + var unknown = + SettleSelectedPublicationRequest.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, peer, unknown)); + verifyNoInteractions(owner); + } + + private static Invocation invoke( + AccountSelectedPublicationSettlementGrpcService receiver, + GrpcPeerIdentity peer, + SettleSelectedPublicationRequest request) { + var result = new Invocation(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + receiver.settleSelectedPublication(request, result); + } finally { + context.detach(previous); + } + return result; + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, Invocation invocation) { + assertThat(invocation.error).isNotNull(); + assertThat(invocation.error.statusRuntimeException()).isTrue(); + assertThat(invocation.error.code()).isEqualTo(expected); + assertThat(invocation.response).isNull(); + assertThat(invocation.completed).isFalse(); + } + + private record ObservedError(boolean statusRuntimeException, Status.Code code) {} + + private static final class Invocation + implements StreamObserver { + private SettleSelectedPublicationResponse response; + private ObservedError error; + private boolean completed; + + @Override + public void onNext(SettleSelectedPublicationResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = + new ObservedError( + failure instanceof StatusRuntimeException, Status.fromThrowable(failure).getCode()); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java index a1cca68f6d..9b2d8c5a80 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java @@ -50,6 +50,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -78,6 +79,70 @@ void clearThreadState() { TransactionSynchronizationManager.clear(); } + @Test + @Timeout(15) + void keytoolTimeoutTerminatesAndReapsTheStalledChild() throws Exception { + Process process = keytoolAwaitingPassword(); + try { + assertThatThrownBy(() -> TestPki.awaitKeytoolExit(process, 1, TimeUnit.SECONDS)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("execution deadline"); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + cleanupKeytool(process); + } + } + + @Test + @Timeout(15) + void keytoolInterruptionReapsTheChildAndPreservesTheInterruptFlag() throws Exception { + Process process = keytoolAwaitingPassword(); + try { + Thread.currentThread().interrupt(); + assertThatThrownBy(() -> TestPki.awaitKeytoolExit(process, 30, TimeUnit.SECONDS)) + .isInstanceOf(InterruptedException.class); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + Thread.interrupted(); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + Thread.interrupted(); + cleanupKeytool(process); + } + } + + private Process keytoolAwaitingPassword() throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + return new ProcessBuilder( + keytool.toString(), + "-genkeypair", + "-alias", + "controlled-timeout", + "-keyalg", + "RSA", + "-keystore", + temporaryDirectory.resolve("pending-password.p12").toString(), + "-storetype", + "PKCS12") + .redirectErrorStream(true) + .start(); + } + + private static void cleanupKeytool(Process process) throws Exception { + if (process.isAlive()) process.destroyForcibly(); + assertThat(process.waitFor(5, TimeUnit.SECONDS)).isTrue(); + process.getOutputStream().close(); + process.getInputStream().close(); + process.getErrorStream().close(); + } + @Test void exactWorldClientReachesReceiverAndPassesOnlyTheRetainedLookupToOwner() throws Exception { var owner = mock(AccountStartSessionWorldParticipationSettlementService.class); @@ -294,6 +359,7 @@ private record TestPki( private static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("world-participation-settlement-test-ca.p12"); runKeytool( + directory, "-genkeypair", "-alias", "world-participation-settlement-ca", @@ -319,6 +385,7 @@ private static TestPki create(Path directory) throws Exception { STORE_PASSWORD); Path caFile = directory.resolve("world-participation-settlement-test-ca.crt"); runKeytool( + directory, "-exportcert", "-alias", "world-participation-settlement-ca", @@ -394,6 +461,7 @@ private static TestIdentity issueIdentity( String san = "URI:" + workloadUri + (server ? ",DNS:localhost,IP:127.0.0.1" : ""); String usage = server ? "serverAuth" : "clientAuth"; runKeytool( + directory, "-genkeypair", "-alias", alias, @@ -420,6 +488,7 @@ private static TestIdentity issueIdentity( "-keypass", STORE_PASSWORD); runKeytool( + directory, "-certreq", "-alias", alias, @@ -434,6 +503,7 @@ private static TestIdentity issueIdentity( "-ext", "SAN=" + san); runKeytool( + directory, "-gencert", "-alias", "world-participation-settlement-ca", @@ -459,6 +529,7 @@ private static TestIdentity issueIdentity( "-ext", "SAN=" + san); runKeytool( + directory, "-importcert", "-alias", "world-participation-settlement-ca", @@ -472,6 +543,7 @@ private static TestIdentity issueIdentity( caFile.toString(), "-noprompt"); runKeytool( + directory, "-importcert", "-alias", alias, @@ -494,7 +566,7 @@ private static TestIdentity issueIdentity( (X509Certificate) keyStore.getCertificate(alias)); } - private static void runKeytool(String... arguments) throws Exception { + private static void runKeytool(Path directory, String... args) throws Exception { Path keytool = Path.of( System.getProperty("java.home"), @@ -502,17 +574,55 @@ private static void runKeytool(String... arguments) throws Exception { System.getProperty("os.name").toLowerCase().contains("windows") ? "keytool.exe" : "keytool"); - var command = new ArrayList(); + ArrayList command = new ArrayList<>(); command.add(keytool.toString()); - command.addAll(List.of(arguments)); - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); - String output; - try (var stream = process.getInputStream()) { - output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + command.addAll(List.of(args)); + Path output = Files.createTempFile(directory, "keytool-output-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(output.toFile()) + .start(); + awaitKeytoolExit(process, 30, TimeUnit.SECONDS); + if (process.exitValue() != 0) { + throw new IllegalStateException("test keytool failed: " + Files.readString(output)); + } + } finally { + Files.deleteIfExists(output); } - if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { - process.destroyForcibly(); - throw new IllegalStateException("test keytool failed: " + output); + } + + /** Waits before reading child output, then terminates and reaps on timeout or interruption. */ + static void awaitKeytoolExit(Process process, long timeout, TimeUnit unit) + throws InterruptedException { + try { + if (!process.waitFor(timeout, unit)) { + throw new IllegalStateException("test keytool exceeded its execution deadline"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } finally { + boolean restoreInterrupt = Thread.interrupted(); + try { + if (process.isAlive()) process.destroyForcibly(); + long cleanupDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + boolean reaped = false; + while (!reaped) { + long remaining = cleanupDeadline - System.nanoTime(); + if (remaining <= 0) { + throw new IllegalStateException("test keytool could not be reaped after termination"); + } + try { + reaped = process.waitFor(remaining, TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + restoreInterrupt = true; + } + } + } finally { + if (restoreInterrupt) Thread.currentThread().interrupt(); + } } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java new file mode 100644 index 0000000000..e738bd42f4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.accountservice.testsupport; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +/** Actual stalled JDK children exercise only this fixture's process deadline and cleanup. */ +class AccountStartSessionReservationProofPkiTest { + @TempDir Path directory; + + @Test + @Timeout(15) + void timeoutTerminatesAndReapsTheStalledChild() throws Exception { + Process process = awaitingPassword(); + try { + assertThatThrownBy( + () -> + AccountStartSessionReservationProofPki.awaitKeytoolExit( + process, 1, TimeUnit.SECONDS)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("execution deadline"); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + cleanup(process); + } + } + + @Test + @Timeout(15) + void interruptionTerminatesAndReapsTheChildAndRestoresTheInterruptFlag() throws Exception { + Process process = awaitingPassword(); + try { + Thread.currentThread().interrupt(); + assertThatThrownBy( + () -> + AccountStartSessionReservationProofPki.awaitKeytoolExit( + process, 30, TimeUnit.SECONDS)) + .isInstanceOf(InterruptedException.class); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + Thread.interrupted(); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + Thread.interrupted(); + cleanup(process); + } + } + + private Process awaitingPassword() throws Exception { + var keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + return new ProcessBuilder( + keytool.toString(), + "-genkeypair", + "-alias", + "controlled-timeout", + "-keyalg", + "RSA", + "-keystore", + directory.resolve("pending-password.p12").toString(), + "-storetype", + "PKCS12") + .redirectErrorStream(true) + .start(); + } + + private static void cleanup(Process process) throws Exception { + if (process.isAlive()) process.destroyForcibly(); + assertThat(process.waitFor(5, TimeUnit.SECONDS)).isTrue(); + process.getOutputStream().close(); + process.getInputStream().close(); + process.getErrorStream().close(); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index a9bdc9d9ff..bd43e21388 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -35,6 +35,8 @@ public final class AccountControlUiOriginalOrderFixture implements AutoCloseable { private final AccountControlUiOwnerSourcesFixture f; private final AccountControlUiActorService actors; + final AccountJwtJwksTrustedSource publicSource; + final AccountControlUiSignerFixture signerFixture; private final AccountControlUiIssuanceService issuance; private final AccountControlUiCoordination coordination; private final RedisClient accountClient; @@ -113,7 +115,8 @@ public AccountControlUiOriginalOrderFixture( f = new AccountControlUiOwnerSourcesFixture( jdbcUrl, username, password, temporary, false, gameDesignTenant, migrationTarget); - var lifecycle = new AccountControlUiSignerFixture(f, temporary); + signerFixture = new AccountControlUiSignerFixture(f, temporary); + var lifecycle = signerFixture; lifecycle.commit(); var originalSigner = f.tx(lifecycle.signer::captureCurrent); assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) @@ -174,9 +177,14 @@ public AccountControlUiOriginalOrderFixture( new AcknowledgementRequirements(1, 1, 5000), testCatalog()); var operations = new AccountControlUiIssuanceRepository(f.dsl); - var publicSource = - new AccountJwtJwksTrustedSource( - lifecycle.client, lifecycle.trust, lifecycle.desired, lifecycle.publication, f.manager); + publicSource = + org.mockito.Mockito.spy( + new AccountJwtJwksTrustedSource( + lifecycle.client, + lifecycle.trust, + lifecycle.desired, + lifecycle.publication, + f.manager)); actors = new AccountControlUiActorService( operations, diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 94bcb6acc7..0e668aa749 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -138,9 +138,10 @@ final class AccountControlUiOwnerSourcesFixture { && !"160.1".equals(migrationTarget) && !"1006".equals(migrationTarget) && !"1007".equals(migrationTarget) - && !"1009".equals(migrationTarget)) { + && !"1009".equals(migrationTarget) + && !"1010".equals(migrationTarget)) { throw new IllegalArgumentException( - "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, or 1009 selected-owner predecessor is supported"); + "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, 1009 selected-owner predecessor, or 1010 selected-publication closure predecessor is supported"); } this.tenant = Objects.requireNonNull(tenant); String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java index d296be3853..6f4c7637b8 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java @@ -478,7 +478,7 @@ public void onCompleted() { return java.util.Objects.requireNonNull(result.get()); } - private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} private static Instant now() { return Instant.ofEpochSecond(Instant.now().getEpochSecond()); @@ -519,7 +519,7 @@ private static String privateBundleJson( return JSON.writeValueAsString(bundle); } - private static PublicJwk publicJwk(String kid, RSAPublicKey key) throws Exception { + static PublicJwk publicJwk(String kid, RSAPublicKey key) throws Exception { String modulus = encodeUnsigned(key.getModulus()); String exponent = encodeUnsigned(key.getPublicExponent()); Map jwk = new LinkedHashMap<>(); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java new file mode 100644 index 0000000000..9cf669c274 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java @@ -0,0 +1,346 @@ +package net.firedevops.firemud.accountservice.testsupport; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; + +/** Controlled loopback PKI for the original Logging claim-read client; no production authority. */ +public final class AccountStartSessionReservationProofPki { + private static final String PASSWORD = "test-only-reservation-pki-password"; + private final Path directory; + private final X509Certificate ca; + private final Map servers; + private final Identity account; + + private AccountStartSessionReservationProofPki( + Path directory, X509Certificate ca, Map servers, Identity account) { + this.directory = directory; + this.ca = ca; + this.servers = servers; + this.account = account; + } + + public static AccountStartSessionReservationProofPki create(Path directory, String namespace) + throws Exception { + Files.createDirectories(directory); + Path caStore = directory.resolve("reservation-test-ca.p12"); + Path caFile = directory.resolve("reservation-test-ca.crt"); + runKeytool( + directory, + "-genkeypair", + "-alias", + "reservation-test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=Controlled Logging claim-read test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + runKeytool( + directory, + "-exportcert", + "-alias", + "reservation-test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + Map servers = + Map.of( + "logging", + issue( + directory, + caStore, + caFile, + "logging-server", + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + true), + "wrong-workload", + issue( + directory, + caStore, + caFile, + "wrong-workload-server", + "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", + true), + "missing-identity", + issue( + directory, + caStore, + caFile, + "missing-identity-server", + "https://localhost/controlled-test", + true), + "wrong-namespace", + issue( + directory, + caStore, + caFile, + "wrong-namespace-server", + "spiffe://firemud/ns/other-runtime/sa/logging-admin-service", + true)); + Identity account = + issue( + directory, + caStore, + caFile, + "account-client", + "spiffe://firemud/ns/" + namespace + "/sa/account-service", + false); + return new AccountStartSessionReservationProofPki( + directory, readCertificate(caFile), servers, account); + } + + public Identity accountIdentity() { + return account; + } + + public X509Certificate caCertificate() { + return ca; + } + + public Identity server(String name) { + return java.util.Objects.requireNonNull(servers.get(name)); + } + + public CommonGrpcClientProperties clientProperties() throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain( + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + account.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + account.privateKey().getEncoded()) + .toString()); + tls.setCaCert( + writePem(directory.resolve("account-client-trust.crt"), "CERTIFICATE", ca.getEncoded()) + .toString()); + return tls; + } + + private static Identity issue( + Path directory, Path caStore, Path caFile, String alias, String uri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path csr = directory.resolve(alias + ".csr"); + Path cert = directory.resolve(alias + "-signed.crt"); + String san = server ? "URI:" + uri + ",DNS:localhost,IP:127.0.0.1" : "URI:" + uri; + String usage = server ? "serverAuth" : "clientAuth"; + runKeytool( + directory, + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + runKeytool( + directory, + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + csr.toString(), + "-ext", + "SAN=" + san); + runKeytool( + directory, + "-gencert", + "-alias", + "reservation-test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-infile", + csr.toString(), + "-outfile", + cert.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san); + runKeytool( + directory, + "-importcert", + "-alias", + "reservation-test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + directory, + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + cert.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, PASSWORD.toCharArray()); + } + return new Identity( + alias, + (PrivateKey) keyStore.getKey(alias, PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(Path directory, String... args) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + ArrayList command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(args)); + Path output = Files.createTempFile(directory, "keytool-output-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(output.toFile()) + .start(); + awaitKeytoolExit(process, 30, TimeUnit.SECONDS); + if (process.exitValue() != 0) { + throw new IllegalStateException("test keytool failed: " + Files.readString(output)); + } + } finally { + Files.deleteIfExists(output); + } + } + + /** Waits before reading child output, then terminates and reaps on timeout or interruption. */ + static void awaitKeytoolExit(Process process, long timeout, TimeUnit unit) + throws InterruptedException { + try { + if (!process.waitFor(timeout, unit)) { + throw new IllegalStateException("test keytool exceeded its execution deadline"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } finally { + boolean restoreInterrupt = Thread.interrupted(); + try { + if (process.isAlive()) process.destroyForcibly(); + long cleanupDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + boolean reaped = false; + while (!reaped) { + long remaining = cleanupDeadline - System.nanoTime(); + if (remaining <= 0) { + throw new IllegalStateException("test keytool could not be reaped after termination"); + } + try { + reaped = process.waitFor(remaining, TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + restoreInterrupt = true; + } + } + } finally { + if (restoreInterrupt) Thread.currentThread().interrupt(); + } + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + public record Identity(String alias, PrivateKey privateKey, X509Certificate certificate) {} +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java index a562ded108..5f248d7ebc 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Explicit mTLS client for the exact Game Design publication terminal read. */ public final class GameDesignPublicationTerminalClient @@ -64,6 +65,11 @@ public synchronized void init() throws SSLException, IOException { */ public GameDesignPublicationTerminalReadEvidence.ReadResult read( GameDesignPublicationTerminalReadEvidence.ReadRequest request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Game Design publication terminal read requires no owner transaction"); + } Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( @@ -104,9 +110,11 @@ protected String defaultTarget() { } @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } super.close(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java new file mode 100644 index 0000000000..0fdcb5c9a2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.CompositeCallCredentials; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Strict explicit mTLS client; never registers or enables the Account producer. */ +public final class AccountSelectedPublicationOrderClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub> { + private final String namespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountSelectedPublicationOrderClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory factory, + String namespace) { + super(endpoints, requireMtls(tls), factory, AccountSelectedPublicationOrderClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account selected-publication client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account selected-publication stub unavailable"); + initialized = true; + } + + public AccountPublicationAuthorizationBinding authorize( + AccountSelectedPublicationOrderGrpcCodec.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException( + "Account selected-publication transport requires no owner transaction"); + Objects.requireNonNull(request); + if (!namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Account selected-publication namespace mismatch"); + var current = stub(); + if (closed || !initialized || current == null) + throw new IllegalStateException("Account selected-publication client unavailable"); + try { + var response = + current + .withCallCredentials( + new CompositeCallCredentials( + new GrpcServerPeerIdentityCallCredentials( + "spiffe://firemud/ns/" + namespace + "/sa/account-service"), + AccountSelectedPublicationOrderCredentials.forCall( + request.originalCreatorCredential()))) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .authorizeSelectedPublication( + AccountSelectedPublicationOrderGrpcCodec.toRequest(request)); + return AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, response); + } catch (StatusRuntimeException unavailable) { + // Remote diagnostics are not trusted to exclude credential-bearing request data. + throw Status.fromCode(unavailable.getStatus().getCode()) + .withDescription("Account selected-publication order denied or unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Account returned invalid selected-publication order evidence"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + return AccountSelectedPublicationOrderServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withCompression("gzip"); + } + + @Override + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } + super.close(); + } + + private static CommonGrpcClientProperties requireMtls(CommonGrpcClientProperties tls) { + if (tls == null || tls.isPlaintext()) + throw new IllegalArgumentException("Account selected-publication requires workload mTLS"); + for (String configured : + new String[] {tls.getCertChain(), tls.getPrivateKey(), tls.getCaCert()}) { + if (configured == null || configured.isBlank() || configured.trim().startsWith("classpath:")) + throw new IllegalArgumentException( + "Account selected-publication requires readable file-backed TLS material"); + Path file; + try { + file = Path.of(configured.trim()); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Account selected-publication requires file-backed TLS material"); + } + if (!Files.isRegularFile(file) || !Files.isReadable(file)) + throw new IllegalArgumentException( + "Account selected-publication requires readable file-backed TLS material"); + } + return tls; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java new file mode 100644 index 0000000000..a62175efec --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.CallCredentials; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Executor; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; + +/** + * Purpose-specific protected metadata for the original creator credential. Never log metadata: + * metadata's wire serialization necessarily contains the secret, unlike this redacted wrapper. The + * receiver must authenticate its workload peer before reading or decoding this header. + */ +public final class AccountSelectedPublicationOrderCredentials { + public static final Context.Key CONTEXT_KEY = + Context.key("account-selected-publication-original-creator"); + public static final Metadata.Key HEADER = + Metadata.Key.of( + "firemud-selected-publication-creator-bin", + new Metadata.BinaryMarshaller<>() { + @Override + public byte[] toBytes(Credential value) { + return value.bytes.clone(); + } + + // Parsing deliberately defers all credential validation until after workload + // authentication. + @Override + public Credential parseBytes(byte[] serialized) { + return new Credential(serialized); + } + }); + + private AccountSelectedPublicationOrderCredentials() {} + + public static final class Credential { + private final byte[] bytes; + + private Credential(byte[] bytes) { + this.bytes = bytes.clone(); + } + + public static Credential of(String value) { + if (value == null + || value.isEmpty() + || value.length() > AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES + || value.chars().anyMatch(c -> c <= 32 || c >= 127)) throw invalid(); + return new Credential(value.getBytes(StandardCharsets.US_ASCII)); + } + + public String value() { + if (bytes.length == 0 + || bytes.length > AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES) + throw invalid(); + for (byte value : bytes) if (value <= 32 || value >= 127) throw invalid(); + return new String(bytes, StandardCharsets.US_ASCII); + } + + @Override + public String toString() { + return "SelectedPublicationCredential[redacted]"; + } + } + + /** Only after authenticating the exact same-namespace Game Design peer. */ + public static Credential readAuthenticated(Metadata headers) { + var values = headers.getAll(HEADER); + if (values == null) throw invalid(); + var iterator = values.iterator(); + if (!iterator.hasNext()) throw invalid(); + Credential credential = iterator.next(); + if (iterator.hasNext()) throw invalid(); + credential.value(); + return credential; + } + + public static CallCredentials forCall(String value) { + var credential = Credential.of(value); + return new CallCredentials() { + @Override + public void applyRequestMetadata( + RequestInfo info, Executor executor, MetadataApplier applier) { + if (info.getSecurityLevel() != SecurityLevel.PRIVACY_AND_INTEGRITY + || !AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod() + .getFullMethodName() + .equals(info.getMethodDescriptor().getFullMethodName())) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Protected selected-publication transport required")); + return; + } + var headers = new Metadata(); + headers.put(HEADER, credential); + applier.apply(headers); + } + + @Override + public void thisUsesUnstableApi() {} + + @Override + public String toString() { + return "SelectedPublicationCallCredentials[redacted]"; + } + }; + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-publication credential metadata"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java new file mode 100644 index 0000000000..93c01ecb90 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed producer transport. Credential data never appears in responses or diagnostics. */ +public final class AccountSelectedPublicationOrderGrpcCodec { + public static final int MAX_CREDENTIAL_BYTES = 16384; + public static final int MAX_SELECTION_BYTES = 1048576; + + private AccountSelectedPublicationOrderGrpcCodec() {} + + public record Request( + int schemaVersion, + String targetNamespace, + UUID requestId, + byte[] originalSelection, + String originalCreatorCredential) { + public Request { + if (schemaVersion != 1 + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || requestId == null + || requestId.equals(new UUID(0, 0))) { + throw invalid(); + } + if (originalSelection == null + || originalSelection.length == 0 + || originalSelection.length > MAX_SELECTION_BYTES + || originalCreatorCredential == null + || originalCreatorCredential.isEmpty() + || originalCreatorCredential.length() > MAX_CREDENTIAL_BYTES + || originalCreatorCredential.chars().anyMatch(c -> c <= 32 || c >= 127)) { + throw invalid(); + } + originalSelection = originalSelection.clone(); + var selection = decodeSelection(originalSelection); + if (!Arrays.equals(originalSelection, selection.canonicalBytes())) throw invalid(); + } + + public static Request create( + String namespace, AuthoredDraftPublishSelectionBinding selection, String credential) { + return new Request(1, namespace, UUID.randomUUID(), selection.canonicalBytes(), credential); + } + + @Override + public byte[] originalSelection() { + return originalSelection.clone(); + } + + public AuthoredDraftPublishSelectionBinding selection() { + return decodeSelection(originalSelection); + } + + @Override + public String toString() { + return "AccountSelectedPublicationOrder.Request[redacted]"; + } + } + + public static AuthorizeSelectedPublicationRequest toRequest(Request request) { + Objects.requireNonNull(request); + return AuthorizeSelectedPublicationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .build(); + } + + /** Invoke only after authenticating the exact same-namespace Game Design workload. */ + public static Request fromRequest(AuthorizeSelectedPublicationRequest wire, String credential) { + try { + noUnknown(wire); + UUID id = UUID.fromString(wire.getRequestId()); + if (!id.toString().equals(wire.getRequestId())) throw invalid(); + return new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + id, + wire.getOriginalSelection().toByteArray(), + credential); + } catch (RuntimeException malformed) { + // Do not retain a parsing cause that could contain credential-bearing request data. + throw invalid(); + } + } + + public static AuthorizeSelectedPublicationResponse toResponse( + Request request, AccountPublicationAuthorizationBinding binding) { + requireSelection(request, binding); + return AuthorizeSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .setPublicationAuthorizationBinding(ByteString.copyFrom(binding.canonicalBytes())) + .build(); + } + + public static AccountPublicationAuthorizationBinding fromResponse( + Request request, AuthorizeSelectedPublicationResponse wire) { + try { + noUnknown(wire); + if (wire.getSchemaVersion() != request.schemaVersion() + || !wire.getTargetNamespace().equals(request.targetNamespace()) + || !wire.getRequestId().equals(request.requestId().toString()) + || !Arrays.equals(wire.getOriginalSelection().toByteArray(), request.originalSelection()) + || wire.getPublicationAuthorizationBinding().size() > MAX_SELECTION_BYTES) + throw invalid(); + var binding = + AccountPublicationAuthorizationBinding.fromStored( + wire.getPublicationAuthorizationBinding().toByteArray()); + requireSelection(request, binding); + return binding; + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static void requireSelection( + Request request, AccountPublicationAuthorizationBinding binding) { + if (binding == null + || !Arrays.equals( + request.originalSelection(), binding.input().selection().canonicalBytes())) + throw invalid(); + } + + private static AuthoredDraftPublishSelectionBinding decodeSelection(byte[] bytes) { + try { + return AuthoredDraftPublishSelectionBinding.fromStored( + new String(bytes, StandardCharsets.UTF_8), DraftAuthorizationFenceBinding.digest(bytes)); + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static void noUnknown(Message wire) { + if (wire == null || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-publication order transport evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java new file mode 100644 index 0000000000..8ac8526d31 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java @@ -0,0 +1,160 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationSettlementServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for Account-owned selected-publication settlement. */ +public final class AccountSelectedPublicationSettlementClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceBlockingStub> { + // Covers both bounded owner reads plus Account persistence, receipt construction, and readback. + private static final long CALL_DEADLINE_SECONDS = 30L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountSelectedPublicationSettlementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountSelectedPublicationSettlementClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account publication settlement client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account publication settlement stub unavailable"); + } + initialized = true; + } + + /** Returns the exact original six-frame receipt after Account peer and receipt validation. */ + public byte[] settle(AccountSelectedPublicationSettlementGrpcCodec.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account publication settlement requires no owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account publication settlement must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .settleSelectedPublication( + AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); + try { + return AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned an invalid publication settlement receipt", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountSelectedPublicationSettlementServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip") + .withMaxInboundMessageSize(AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES); + } + + @Override + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } + super.close(); + } + + private AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account publication settlement client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Account publication settlement requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account publication settlement requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account publication settlement requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account publication settlement " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account publication settlement " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java new file mode 100644 index 0000000000..22085d2767 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java @@ -0,0 +1,246 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed Account-owned selected-publication settlement transport and receipt validation. */ +public final class AccountSelectedPublicationSettlementGrpcCodec { + /** Shared per-message protobuf budget; oversized complete six-frame receipts fail closed. */ + public static final int MAX_MESSAGE_BYTES = 32 * 1024 * 1024; + + private static final int MESSAGE_ENVELOPE_OVERHEAD_RESERVE = 256; + private static final String RECEIPT_SCHEMA = "account-selected-publication-settlement/v1"; + + private AccountSelectedPublicationSettlementGrpcCodec() {} + + public static SettleSelectedPublicationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var wire = + SettleSelectedPublicationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .build(); + requireWireBudget(wire); + return wire; + } + + /** Receiver authenticates the exact Game Design peer before decoding this request. */ + public static Request fromRequest(SettleSelectedPublicationRequest request) { + Objects.requireNonNull(request, "request"); + requireWireBudget(request); + noUnknownFields(request); + try { + return new Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + canonicalUuid(request.getRequestId()), + request.getOriginalOperation().toByteArray()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Account publication settlement request is invalid", malformed); + } + } + + /** Emits only an exact original receipt whose six canonical frames agree with the request. */ + public static SettleSelectedPublicationResponse toResponse(Request request, byte[] receipt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(receipt, "receipt"); + if ((long) receipt.length + request.originalOperation().length + > MAX_MESSAGE_BYTES - MESSAGE_ENVELOPE_OVERHEAD_RESERVE) { + throw new IllegalArgumentException( + "Account publication settlement response exceeds the 32 MiB wire budget"); + } + var response = + SettleSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setSettlementReceipt(ByteString.copyFrom(receipt)) + .build(); + requireWireBudget(response); + validateReceipt(request, receipt); + return response; + } + + /** Verifies the full echo and returns the exact canonical Account settlement receipt. */ + public static byte[] fromResponse(Request request, SettleSelectedPublicationResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireWireBudget(response); + noUnknownFields(response); + if (response.getSchemaVersion() != request.schemaVersion() + || !request.targetNamespace().equals(response.getTargetNamespace()) + || !request.requestId().toString().equals(response.getRequestId()) + || !Arrays.equals( + request.originalOperation(), response.getOriginalOperation().toByteArray())) { + throw new IllegalArgumentException( + "Account changed the exact publication settlement request"); + } + byte[] receipt = response.getSettlementReceipt().toByteArray(); + validateReceipt(request, receipt); + return receipt.clone(); + } + + private static void validateReceipt(Request request, byte[] receipt) { + if (receipt == null || receipt.length == 0 || receipt.length > MAX_MESSAGE_BYTES) { + throw new IllegalArgumentException( + "Complete bounded Account publication settlement receipt required"); + } + final byte[] accountBinding; + final byte[] originalOperation; + final byte[] gameDesignTerminalBytes; + final String worldOutcome; + final byte[] worldTerminalBytes; + try { + var reader = new DraftAuthorizationFenceBinding.FrameReader(receipt); + reader.expect(RECEIPT_SCHEMA); + accountBinding = reader.bytes(); + originalOperation = reader.bytes(); + gameDesignTerminalBytes = reader.bytes(); + worldOutcome = reader.text(); + worldTerminalBytes = reader.bytes(); + reader.requireEnd(); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Canonical six-frame Account publication settlement receipt required", malformed); + } + + GameDesignPublicationOperationBinding operation; + GameDesignPublicationTerminalEvidence terminal; + try { + operation = GameDesignPublicationOperationBinding.fromStored(request.originalOperation()); + terminal = GameDesignPublicationTerminalEvidence.fromStored(gameDesignTerminalBytes); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Account receipt lacks complete canonical publication evidence", malformed); + } + String expectedWorldOutcome = + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + if (!Arrays.equals(accountBinding, operation.account().canonicalBytes()) + || !Arrays.equals(originalOperation, request.originalOperation()) + || !Arrays.equals(terminal.operationBytes(), originalOperation) + || !Arrays.equals(gameDesignTerminalBytes, terminal.canonicalBytes()) + || !Arrays.equals(worldTerminalBytes, gameDesignTerminalBytes) + || !expectedWorldOutcome.equals(worldOutcome)) { + throw new IllegalArgumentException( + "Account settlement receipt differs from the exact operation, terminal, or World outcome"); + } + + var canonical = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(canonical, RECEIPT_SCHEMA); + DraftAuthorizationFenceBinding.frame(canonical, accountBinding); + DraftAuthorizationFenceBinding.frame(canonical, originalOperation); + DraftAuthorizationFenceBinding.frame(canonical, gameDesignTerminalBytes); + DraftAuthorizationFenceBinding.frame(canonical, worldOutcome); + DraftAuthorizationFenceBinding.frame(canonical, worldTerminalBytes); + if (!Arrays.equals(receipt, canonical.toByteArray())) { + throw new IllegalArgumentException("Noncanonical Account publication settlement receipt"); + } + } + + private static void requireWireBudget(Message message) { + if (message.getSerializedSize() > MAX_MESSAGE_BYTES) { + throw new IllegalArgumentException( + "Account publication settlement exceeds the 32 MiB wire budget"); + } + } + + private static void noUnknownFields(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Account publication settlement has unsupported fields"); + } + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil request UUID required"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException("Canonical non-nil request UUID required", malformed); + } + } + + /** Request correlation is fresh per transport call and is not the retained settlement key. */ + public record Request( + int schemaVersion, String targetNamespace, UUID requestId, byte[] originalOperation) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported Account publication settlement schema"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + if (requestId == null || requestId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Non-nil canonical request identity required"); + } + if (originalOperation == null || originalOperation.length == 0) { + throw new IllegalArgumentException("Complete original publication operation required"); + } + if (originalOperation.length > GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES) { + throw new IllegalArgumentException("Original publication operation exceeds 4 MiB"); + } + originalOperation = originalOperation.clone(); + GameDesignPublicationOperationBinding operation; + try { + // Shared decoding preserves historical v1; this current wire requires complete v2 input. + new DraftAuthorizationFenceBinding.FrameReader(originalOperation) + .expect(GameDesignPublicationOperationBinding.SCHEMA); + operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Complete canonical original publication operation required", malformed); + } + if (!Arrays.equals(originalOperation, operation.canonicalBytes())) { + throw new IllegalArgumentException( + "Exact canonical original publication operation required"); + } + if (!targetNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException( + "Original publication operation differs from the Account workload namespace"); + } + } + + public static Request create(String targetNamespace, byte[] originalOperation) { + return new Request(SCHEMA_VERSION, targetNamespace, UUID.randomUUID(), originalOperation); + } + + @Override + public byte[] originalOperation() { + return originalOperation.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && requestId.equals(that.requestId) + && Arrays.equals(originalOperation, that.originalOperation); + } + + @Override + public int hashCode() { + return 31 * Objects.hash(schemaVersion, targetNamespace, requestId) + + Arrays.hashCode(originalOperation); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java index 8e799ce14c..71872ef675 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationRequest; @@ -184,6 +185,9 @@ public record Request( gameDesignTerminalEvidence = gameDesignTerminalEvidence.clone(); GameDesignPublicationTerminalEvidence terminal; try { + // Historical decoding must not widen this complete-v2 completion transport. + new DraftAuthorizationFenceBinding.FrameReader(originalOperation) + .expect(GameDesignPublicationOperationBinding.SCHEMA); terminal = GameDesignPublicationTerminalEvidence.fromStored(gameDesignTerminalEvidence); } catch (RuntimeException malformed) { throw new IllegalArgumentException( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java index 72a84eced9..416599fe7b 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java @@ -25,11 +25,17 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; import net.firedevops.firemud.common.publication.WorldSelectedOwnerInventoryGrpcClient; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; @@ -179,7 +185,13 @@ private enum ClientKind { SOURCE_READ, AUTOMATION_TERMINAL, GAME_DESIGN_SOURCE, - WORLD_INVENTORY; + WORLD_INVENTORY, + GAME_DESIGN_PUBLICATION_TERMINAL, + ACCOUNT_PUBLICATION_SETTLEMENT, + ACCOUNT_PUBLICATION_HELD_READ, + ACCOUNT_PUBLICATION_ORDER, + GAME_DESIGN_PUBLICATION_SELECTION, + WORLD_PUBLICATION_TERMINAL; ClientHandle create( ServiceEndpointsProperties endpoints, @@ -215,6 +227,32 @@ ClientHandle create( var client = new WorldSelectedOwnerInventoryGrpcClient(endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); } + case GAME_DESIGN_PUBLICATION_TERMINAL -> { + var client = new GameDesignPublicationTerminalClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case ACCOUNT_PUBLICATION_SETTLEMENT -> { + var client = + new AccountSelectedPublicationSettlementClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case ACCOUNT_PUBLICATION_HELD_READ -> { + var client = + new AccountPublicationAuthorizationReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case ACCOUNT_PUBLICATION_ORDER -> { + var client = new AccountSelectedPublicationOrderClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GAME_DESIGN_PUBLICATION_SELECTION -> { + var client = new AuthoredDraftPublishSelectionReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case WORLD_PUBLICATION_TERMINAL -> { + var client = new WorldPublicationTerminalReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } }; } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java new file mode 100644 index 0000000000..eb8beecde7 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java @@ -0,0 +1,270 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class AssetSourceTest { + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID VERSION = UUID.randomUUID(); + + @Test + void extractionPreservesExactBindingOrderAndExplicitRequiredness() { + var binding = + binding( + AssetSource.upsertPayload( + "9223372036854775807", " Logo.png ", AssetSource.Requiredness.REQUIRED), + "{\"revisionKind\":\"COMMAND_DEFINITION\"}", + "{\"revisionKind\":\"REALM_ENTRY_POLICY\"}", + AssetSource.upsertPayload("2", "required.png", AssetSource.Requiredness.REQUIRED)); + var mutations = AssetSource.mutations(binding); + + assertThat(mutations).hasSize(2); + assertThat(mutations).extracting(AssetSource.Mutation::revisionOrder).containsExactly("0", "3"); + assertThat(mutations.getFirst().binding()).isSameAs(binding); + assertThat(mutations.getFirst().revisionId()) + .isEqualTo(binding.revisions().getFirst().revisionId()); + assertThat(mutations.getFirst().usageKey()).isEqualTo(" Logo.png "); + assertThat(mutations.getFirst().requiredness()).isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(mutations.getLast().requiredness()).isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(mutations.getFirst().binding()).isSameAs(binding); + assertThatThrownBy(() -> mutations.clear()).isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void replayReplacesOnlyExplicitKeysAndRetainsExactSourceProvenance() { + var original = + binding( + AssetSource.upsertPayload("1", "one.png", AssetSource.Requiredness.REQUIRED), + AssetSource.upsertPayload("2", "two.png", AssetSource.Requiredness.REQUIRED)); + var baseline = AssetSource.replay(List.of(), original); + var changed = + binding( + AssetSource.deletePayload("one.png"), + AssetSource.upsertPayload("3", "one.png", AssetSource.Requiredness.REQUIRED)); + var result = AssetSource.replay(baseline.references(), changed); + + assertThat(result.binding()).isSameAs(changed); + assertThat(result.references()) + .extracting(AssetSource.Reference::usageKey) + .containsExactly("one.png", "two.png"); + assertThat(result.references().getFirst().assetRowId()).isEqualTo("3"); + assertThat(result.references().getFirst().requiredness()) + .isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(result.references().getFirst().family()).isEqualTo("ORDINARY"); + assertThat(result.references().getFirst().role()).isEqualTo("RESOURCE"); + assertThat(result.references().getFirst().sourceBinding()).isSameAs(changed); + assertThat(result.references().getLast().sourceBinding()).isSameAs(original); + assertThat(AssetSource.replay(result.references(), changed)).isEqualTo(result); + assertThat( + AssetSource.replay(result.references(), binding(AssetSource.deletePayload("two.png"))) + .references()) + .extracting(AssetSource.Reference::usageKey) + .containsExactly("one.png"); + } + + @Test + void referenceCannotRewriteItsBoundRequirednessOrRevisionIdentity() { + var binding = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var revision = binding.revisions().getFirst(); + + assertThatThrownBy( + () -> + new AssetSource.Reference( + "logo.png", + "1", + AssetSource.Requiredness.OPTIONAL, + binding, + "0", + revision.revisionId())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AssetSource.Reference( + "logo.png", + "1", + AssetSource.Requiredness.REQUIRED, + binding, + "0", + UUID.randomUUID())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void snapshotRejectsForeignTargetDuplicateKeysAndSourceAliases() { + var original = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var references = AssetSource.replay(List.of(), original).references(); + var foreign = binding(UUID.randomUUID(), AssetSource.deletePayload("logo.png")); + + assertThatThrownBy(() -> AssetSource.replay(references, foreign)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AssetSource.Snapshot( + original, List.of(references.getFirst(), references.getFirst()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AssetSource.replay( + references, + binding( + AssetSource.upsertPayload( + "1", "alias.png", AssetSource.Requiredness.REQUIRED)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void snapshotDefensivelyRetainsItsReferenceList() { + var binding = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var mutable = new ArrayList<>(AssetSource.replay(List.of(), binding).references()); + var snapshot = new AssetSource.Snapshot(binding, mutable); + mutable.clear(); + + assertThat(snapshot.references()).hasSize(1); + assertThatThrownBy(() -> snapshot.references().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "0", + "01", + "-1", + "+1", + "1.0", + "1e2", + " 1", + "9223372036854775808", + "999999999999999999999999" + }) + void deniesNoncanonicalOrOverflowingOwnerRowId(String value) { + assertThatThrownBy( + () -> AssetSource.mutations(binding(upsert("\"" + value + "\"", "\"REQUIRED\"")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"1", "1.0", "1e0", "null", "true", "{}", "[]"}) + void ownerRowIdMustBeTextNotCoercedJson(String value) { + assertThatThrownBy(() -> AssetSource.mutations(binding(upsert(value, "\"REQUIRED\"")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"\"UNKNOWN\"", "\"required\"", "null", "true", "1", "{}"}) + void deniesUnknownOrUntypedRequiredness(String value) { + assertThatThrownBy(() -> AssetSource.mutations(binding(upsert("\"1\"", value)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void deniesMissingRequirednessUnknownMembersDuplicateFieldsAndTrailingJson() { + String valid = upsert("\"1\"", "\"REQUIRED\""); + List invalid = + List.of( + valid.replace(",\"requiredness\":\"REQUIRED\"", ""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1.0"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":\"1\""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":2"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"), + valid.replace("\"usageKey\":\"logo.png\"", "\"usageKey\":\"logo.png\",\"extra\":true"), + valid + " {}", + "{\"revisionKind\":\"UNSUPPORTED\"}", + "{}", + AssetSource.deletePayload("logo.png") + .replace( + "\"operation\":\"DELETE\"", + "\"operation\":\"DELETE\",\"requiredness\":\"OPTIONAL\"")); + for (String payload : invalid) { + assertThatThrownBy(() -> AssetSource.mutations(binding(payload))) + .as(payload) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void usageKeyIsExactBoundedAndCannotReserveManifestName() { + for (String key : List.of("", " ", "manifest.json", "x".repeat(256))) { + assertThatThrownBy( + () -> AssetSource.upsertPayload("1", key, AssetSource.Requiredness.REQUIRED)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat( + AssetSource.mutations( + binding( + AssetSource.upsertPayload( + "1", "x".repeat(255), AssetSource.Requiredness.REQUIRED)))) + .hasSize(1); + } + + @Test + void ordinaryResourceCannotClaimOptionalPresentationOrAnUnknownFamilyOrRole() { + assertThatThrownBy( + () -> AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.OPTIONAL)) + .isInstanceOf(IllegalArgumentException.class); + String required = upsert("\"1\"", "\"REQUIRED\""); + for (String payload : + List.of( + required.replace("REQUIRED", "OPTIONAL"), + required.replace("ORDINARY", "BRANDING"), + required.replace("RESOURCE", "PRESENTATION"), + required.replace(",\"role\":\"RESOURCE\"", ""), + required.replace(",\"family\":\"ORDINARY\"", ""))) { + assertThatThrownBy(() -> AssetSource.mutations(binding(payload))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static String upsert(String rowIdJson, String requirednessJson) { + return "{\"schemaVersion\":1,\"revisionKind\":\"ASSET_REFERENCE\",\"family\":\"ORDINARY\",\"role\":\"RESOURCE\",\"operation\":\"UPSERT\",\"assetRowId\":" + + rowIdJson + + ",\"usageKey\":\"logo.png\",\"requiredness\":" + + requirednessJson + + "}"; + } + + private static DraftCommitBinding binding(String... payloads) { + return binding(VERSION, payloads); + } + + private static DraftCommitBinding binding(UUID versionId, String... payloads) { + List revisions = new ArrayList<>(); + for (int index = 0; index < payloads.length; index++) { + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[index])); + } + return DraftCommitBinding.create( + new TargetProof(TENANT, versionId, 23L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + versionId.toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + "0"))); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandDefinitionClosedFieldsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandDefinitionClosedFieldsTest.java new file mode 100644 index 0000000000..5166f916ff --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandDefinitionClosedFieldsTest.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +class CommandDefinitionClosedFieldsTest { + private static final String VALID_DEFINITION = + """ + { + "schemaVersion": 1, + "commandId": "salute", + "semanticOwner": "GAME_LOGIC", + "executionDiscipline": "DURABLE_GAMEPLAY", + "stageRequirement": "GAMEPLAY", + "promptPolicy": "WHEN_GAMEPLAY", + "actionCategory": "SOCIAL", + "historyRecordable": true, + "aliases": ["salute"], + "actionTags": ["COMMUNICATION"], + "effects": [ + { + "effectKind": "APPLY_ACTION_STATE", + "schemaVersion": 1, + "targeting": "SELF", + "replayPolicy": "EFFECT_IDEMPOTENT", + "payload": { + "conditionKey": "SALUTING", + "durationSeconds": 30, + "effectPayload": { + "modifiers": [ + { + "operation": "ADD", + "target_key": "salute_count", + "value": 1, + "scope_kind": "ACTION_FAMILY", + "scope_key": "social", + "priority": 2 + } + ] + } + } + } + ] + } + """; + + @Test + void acceptsCanonicalDefinitionAndDefinedOptionalModifierFields() { + assertThat(CommandSource.upsertPayload(VALID_DEFINITION)).isNotBlank(); + } + + @Test + void acceptsCanonicalDefinitionWhenAllOptionalModifierFieldsAreAbsent() { + String definitionWithoutOptionalModifierFields = + VALID_DEFINITION.replace( + ",\n \"scope_kind\": \"ACTION_FAMILY\",\n \"scope_key\": \"social\",\n \"priority\": 2", + ""); + + assertThat(definitionWithoutOptionalModifierFields) + .doesNotContain("scope_kind", "scope_key", "priority"); + assertThat(CommandSource.upsertPayload(definitionWithoutOptionalModifierFields)).isNotBlank(); + } + + @Test + void rejectsUnknownDefinitionFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"commandId\": \"salute\",", "\"targetSelectionPolicyKey\": \"self\","); + } + + @Test + void rejectsUnknownEffectFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"effectKind\": \"APPLY_ACTION_STATE\",", "\"targetSetKey\": \"SOURCE\","); + } + + @Test + void rejectsUnknownPayloadFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"conditionKey\": \"SALUTING\",", "\"sourceRuleId\": \"rule-1\","); + } + + @Test + void rejectsUnknownEffectPayloadFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"effectPayload\": {", "\"targetRefs\": [],"); + } + + @Test + void rejectsUnknownModifierFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"operation\": \"ADD\",", "\"targetTemplateId\": \"item-1\","); + } + + private static void assertRejected(String marker, String insertion) { + String unsupported = VALID_DEFINITION.replace(marker, marker + insertion); + assertThat(unsupported).isNotEqualTo(VALID_DEFINITION); + assertThatThrownBy(() -> CommandSource.upsertPayload(unsupported)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java new file mode 100644 index 0000000000..26d4ac5fde --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.common.publication; + +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Stub configuration/codec units; mocked channels do not prove an mTLS handshake. */ +class AccountSelectedPublicationOrderClientTest { + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var tls = tls(directory); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + tls.setPlaintext(false); + for (String bad : + new String[] { + null, + "", + "classpath:credential.pem", + directory.toString(), + directory.resolve("missing.pem").toString() + }) { + tls.setCertChain(bad); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var valid = tls(directory); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), valid, factory, "Test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void configuresExactAccountPeerDeadlineAndValidatesEchoOutsideSql(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + when(factory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new AccountSelectedPublicationOrderClient(endpoints, tls(directory), factory, "test"); + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), "original.secret.credential"); + try { + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + client.init(); + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + var initialized = (io.grpc.stub.AbstractStub) field.get(client); + var credentials = initialized.getCallOptions().getCredentials(); + assertThat(credentials).isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + var peerField = + GrpcServerPeerIdentityCallCredentials.class.getDeclaredField("expectedPeerUri"); + peerField.setAccessible(true); + assertThat(peerField.get(credentials)) + .isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + var stub = + mock( + AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withCallCredentials(any())).thenReturn(stub); + field.set(client, stub); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.clearSynchronization(); + var wrongNamespace = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "other", binding.input().selection(), "original.secret.credential"); + assertThatThrownBy(() -> client.authorize(wrongNamespace)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(stub); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + when(stub.authorizeSelectedPublication(any())).thenReturn(response); + assertThat(client.authorize(request).canonicalBytes()).isEqualTo(binding.canonicalBytes()); + verify(stub).withDeadlineAfter(5, TimeUnit.SECONDS); + var wire = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest.class); + verify(stub).authorizeSelectedPublication(wire.capture()); + assertThat(wire.getValue().toString()).doesNotContain(request.originalCreatorCredential()); + var perCall = org.mockito.ArgumentCaptor.forClass(io.grpc.CallCredentials.class); + verify(stub).withCallCredentials(perCall.capture()); + assertThat(perCall.getValue()).isInstanceOf(io.grpc.CompositeCallCredentials.class); + when(stub.authorizeSelectedPublication(any())) + .thenReturn(response.toBuilder().setTargetNamespace("other").build()); + assertThatThrownBy(() -> client.authorize(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageNotContaining(request.originalCreatorCredential()); + when(stub.authorizeSelectedPublication(any())) + .thenThrow( + io.grpc.Status.UNAVAILABLE + .withDescription(request.originalCreatorCredential()) + .asRuntimeException()); + assertThatThrownBy(() -> client.authorize(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageNotContaining(request.originalCreatorCredential()) + .hasNoCause(); + } finally { + client.close(); + } + assertThatThrownBy(client::init).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private-key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "ca").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java new file mode 100644 index 0000000000..a003a624f5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.common.publication; + +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.when; + +import io.grpc.CallCredentials; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import java.nio.charset.StandardCharsets; +import java.util.List; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationOrderCredentialsTest { + private static final String SECRET = "original.secret.credential"; + private static final Metadata.Key RAW = + Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + Metadata.BINARY_BYTE_MARSHALLER); + + @Test + void carrierAndWrapperAreRedactedAndApplyOnlyToProtectedExactMethod() { + var credentials = AccountSelectedPublicationOrderCredentials.forCall(SECRET); + assertThat(credentials.toString()).doesNotContain(SECRET); + assertThat(AccountSelectedPublicationOrderCredentials.Credential.of(SECRET).toString()) + .doesNotContain(SECRET); + var info = mock(CallCredentials.RequestInfo.class); + when(info.getSecurityLevel()).thenReturn(SecurityLevel.PRIVACY_AND_INTEGRITY); + org.mockito.Mockito.doReturn( + AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod()) + .when(info) + .getMethodDescriptor(); + var applier = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, applier); + var captured = org.mockito.ArgumentCaptor.forClass(Metadata.class); + verify(applier).apply(captured.capture()); + assertThat( + AccountSelectedPublicationOrderCredentials.readAuthenticated(captured.getValue()) + .value()) + .isEqualTo(SECRET); + for (var level : List.of(SecurityLevel.NONE, SecurityLevel.INTEGRITY)) { + when(info.getSecurityLevel()).thenReturn(level); + var denied = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, denied); + verify(denied) + .fail( + org.mockito.ArgumentMatchers.argThat( + status -> status.getCode() == io.grpc.Status.Code.UNAUTHENTICATED)); + } + when(info.getSecurityLevel()).thenReturn(SecurityLevel.PRIVACY_AND_INTEGRITY); + org.mockito.Mockito.doReturn( + AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod() + .toBuilder() + .setFullMethodName("different/Method") + .build()) + .when(info) + .getMethodDescriptor(); + var denied = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, denied); + verify(denied).fail(org.mockito.ArgumentMatchers.any()); + } + + @Test + void + authenticatedReadRejectsMissingDuplicateOversizedAndMalformedHeadersWithoutSecretDiagnostics() { + var missing = new Metadata(); + var duplicate = new Metadata(); + duplicate.put(RAW, SECRET.getBytes(StandardCharsets.US_ASCII)); + duplicate.put(RAW, SECRET.getBytes(StandardCharsets.US_ASCII)); + for (var headers : + List.of( + missing, + duplicate, + raw(new byte[0]), + raw(new byte[] {(byte) 128}), + raw((SECRET + "\n").getBytes(StandardCharsets.US_ASCII)), + raw(new byte[16385]))) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderCredentials.readAuthenticated(headers)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(SECRET) + .hasNoCause(); + } + var exact = + AccountSelectedPublicationOrderCredentials.readAuthenticated( + raw(SECRET.getBytes(StandardCharsets.US_ASCII))); + assertThat(exact.value()).isEqualTo(SECRET); + assertThat(exact.toString()).doesNotContain(SECRET); + } + + private static Metadata raw(byte[] bytes) { + var headers = new Metadata(); + headers.put(RAW, bytes); + return headers; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java new file mode 100644 index 0000000000..9b39340b8a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationOrderGrpcCodecTest { + private static final String CREDENTIAL = "original.secret.credential"; + + @Test + void preservesOriginalCredentialAndCanonicalSelectionWithoutEchoingSecret() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + var decoded = AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, CREDENTIAL); + assertThat(decoded.originalCreatorCredential()).isEqualTo(CREDENTIAL); + assertThat(decoded.originalSelection()).isEqualTo(request.originalSelection()); + assertThat(decoded.requestId()).isEqualTo(request.requestId()); + assertThat(decoded.toString()).doesNotContain(CREDENTIAL); + assertThat(wire.toString()).doesNotContain(CREDENTIAL); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + assertThat(response.toString()).doesNotContain(CREDENTIAL); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + var fresh = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse( + fresh, AccountSelectedPublicationOrderGrpcCodec.toResponse(fresh, binding)) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + } + + @Test + void rejectsUnknownNoncanonicalOversizedAndMissingRequestFieldsWithoutSecretDiagnostics() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + for (AuthorizeSelectedPublicationRequest invalid : + List.of( + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setRequestId("1-1-1-1-1").build(), + wire.toBuilder().setRequestId(new UUID(0, 0).toString()).build(), + wire.toBuilder().setRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA").build(), + wire.toBuilder().setUnknownFields(unknown()).build(), + wire.toBuilder().clearOriginalSelection().build(), + wire.toBuilder().setOriginalSelection(ByteString.copyFrom(new byte[1048577])).build(), + wire.toBuilder() + .setOriginalSelection( + wire.getOriginalSelection().concat(ByteString.copyFromUtf8(" "))) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderGrpcCodec.fromRequest(invalid, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + for (String invalid : List.of("", "x".repeat(16385), CREDENTIAL + "\n")) { + assertThatThrownBy(() -> AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, invalid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + } + + @Test + void rejectsChangedResponseEchoBindingAndUnknownFields() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + for (var invalid : + List.of( + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder().clearOriginalSelection().build(), + response.toBuilder().setUnknownFields(unknown()).build(), + response.toBuilder().clearPublicationAuthorizationBinding().build(), + response.toBuilder() + .setPublicationAuthorizationBinding(ByteString.copyFrom(new byte[] {1})) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java new file mode 100644 index 0000000000..6ac82997be --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java @@ -0,0 +1,376 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical mTLS proof that Account settlement may complete after the former five-second window. */ +class AccountSelectedPublicationSettlementClientTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @Test + void returnsCanonicalReceiptFromAuthenticatedAccountPeerAfterFormerFiveSecondWindow( + @TempDir Path directory) throws Exception { + TestPki pki = TestPki.create(directory); + var operation = WorldPublicationTerminalTestFixtures.operation(); + var terminal = + WorldPublicationTerminalTestFixtures.terminal( + operation, GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()); + byte[] receipt = receipt(operation, terminal); + var response = AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt); + AtomicReference received = new AtomicReference<>(); + var service = + new AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceImplBase() { + @Override + public void settleSelectedPublication( + SettleSelectedPublicationRequest wireRequest, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !GAME_DESIGN_URI.equals(peer.uri())) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + received.set(wireRequest); + try { + TimeUnit.SECONDS.sleep(6L); + observer.onNext(response); + observer.onCompleted(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + observer.onError(Status.CANCELLED.withCause(interrupted).asRuntimeException()); + } + } + }; + + try (TransportServer server = startServer(pki, service); + AccountSelectedPublicationSettlementClient client = client(pki, server.port(), directory)) { + client.init(); + long started = System.nanoTime(); + byte[] actualReceipt = client.settle(request); + long elapsedNanos = System.nanoTime() - started; + + assertThat(elapsedNanos).isGreaterThanOrEqualTo(TimeUnit.SECONDS.toNanos(6L)); + assertThat(actualReceipt).containsExactly(receipt); + assertThat(received.get()) + .isEqualTo(AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); + } + } + + private static byte[] receipt( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence terminal) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + DraftAuthorizationFenceBinding.frame( + out, + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + return out.toByteArray(); + } + + private static TransportServer startServer(TestPki pki, io.grpc.BindableService service) + throws Exception { + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.accountServer().privateKey(), pki.accountServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(service) + .intercept(new GrpcPeerIdentityInterceptor()) + .build() + .start(); + return new TransportServer(server); + } + + private static AccountSelectedPublicationSettlementClient client( + TestPki pki, int port, Path directory) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + return new AccountSelectedPublicationSettlementClient( + endpoints, pki.clientProperties(directory), new GrpcChannelFactory(), NAMESPACE); + } + + private record TransportServer(Server server) implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Account settlement loopback server did not terminate"); + } + } + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, TestIdentity accountServer, TestIdentity gameDesignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD Account settlement test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + return new TestPki( + readCertificate(caFile), + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) throws Exception { + Path certificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + gameDesignClient.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + gameDesignClient.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String uri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + uri + ",DNS:localhost,IP:127.0.0.1"; + String usage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(2, TimeUnit.SECONDS); + throw new IllegalStateException("test keytool operation timed out"); + } + if (process.exitValue() != 0) { + throw new IllegalStateException( + "test keytool operation failed with exit " + process.exitValue()); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java new file mode 100644 index 0000000000..39f7bd3eab --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java @@ -0,0 +1,240 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationSettlementGrpcCodecTest { + @Test + void roundTripsBothCanonicalSixFrameReceiptsAndUsesIndependentCorrelation() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + for (Outcome outcome : Outcome.values()) { + var terminal = WorldPublicationTerminalTestFixtures.terminal(operation, outcome); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var decoded = + AccountSelectedPublicationSettlementGrpcCodec.fromRequest( + AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); + assertThat(decoded).isEqualTo(request); + + byte[] receipt = receipt(operation, terminal, null, null, null, null); + var response = AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt); + assertThat(AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, response)) + .containsExactly(receipt); + + var fresh = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat(fresh.originalOperation()).containsExactly(request.originalOperation()); + } + } + + @Test + void retainsV1HistoryButRejectsItFromCurrentSettlementRequests() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var history = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(history, "game-design-publication-operation/v1"); + DraftAuthorizationFenceBinding.frame(history, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(history, operation.world().canonicalBytes()); + byte[] original = history.toByteArray(); + assertThat(GameDesignPublicationOperationBinding.fromStored(original).canonicalBytes()) + .containsExactly(original); + + assertThatThrownBy( + () -> AccountSelectedPublicationSettlementGrpcCodec.Request.create("test", original)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Complete canonical original publication operation required"); + var current = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var changed = + AccountSelectedPublicationSettlementGrpcCodec.toRequest(current).toBuilder() + .setOriginalOperation(ByteString.copyFrom(original)) + .build(); + assertThatThrownBy(() -> AccountSelectedPublicationSettlementGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account publication settlement request is invalid"); + } + + @Test + void rejectsMalformedAndNoncanonicalRequestsAndUnknownFields() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var wire = AccountSelectedPublicationSettlementGrpcCodec.toRequest(request); + for (SettleSelectedPublicationRequest invalid : + List.of( + wire.toBuilder().setUnknownFields(unknown()).build(), + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + wire.toBuilder().setRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA").build(), + wire.toBuilder().setRequestId("1-1-1-1-1").build(), + wire.toBuilder().clearOriginalOperation().build(), + wire.toBuilder() + .setOriginalOperation( + wire.getOriginalOperation().concat(ByteString.copyFrom(new byte[] {0}))) + .build(), + wire.toBuilder().setOriginalOperation(ByteString.copyFrom(new byte[] {1})).build())) { + assertThatThrownBy(() -> AccountSelectedPublicationSettlementGrpcCodec.fromRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", + new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("4 MiB"); + } + + @Test + void rejectsChangedRequestEchoUnknownFieldsAndChangedOrNoncanonicalReceiptFrames() + throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var terminal = WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.NO_PUBLICATION); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var changedOperation = WorldPublicationTerminalTestFixtures.operation(); + var changedTerminal = + WorldPublicationTerminalTestFixtures.terminal(changedOperation, Outcome.PUBLISHED); + var sameOperationOtherOutcome = + WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.PUBLISHED); + byte[] receipt = receipt(operation, terminal, null, null, null, null); + var response = AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt); + var changedBinding = new byte[] {1, 2, 3}; + byte[] wrongOutcome = receipt(operation, terminal, "PUBLISHED", null, null, null); + byte[] wrongBinding = receipt(operation, terminal, null, changedBinding, null, null); + byte[] wrongOperation = + receipt(operation, terminal, null, null, changedOperation.canonicalBytes(), null); + byte[] wrongTerminal = receipt(operation, changedTerminal, null, null, null, null); + byte[] wrongWorldTerminal = + receipt(operation, terminal, null, null, null, sameOperationOtherOutcome.canonicalBytes()); + byte[] missingWorldTerminal = receipt(operation, terminal, null, null, null, new byte[0]); + byte[] noncanonicalWorldTerminal = + receipt( + operation, + terminal, + null, + null, + null, + ByteString.copyFrom(terminal.canonicalBytes()) + .concat(ByteString.copyFrom(new byte[] {0})) + .toByteArray()); + for (var invalid : + List.of( + response.toBuilder().setUnknownFields(unknown()).build(), + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder() + .setOriginalOperation(ByteString.copyFrom(changedOperation.canonicalBytes())) + .build(), + response.toBuilder().clearSettlementReceipt().build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongOutcome)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongBinding)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongOperation)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongTerminal)).build(), + response.toBuilder() + .setSettlementReceipt(ByteString.copyFrom(wrongWorldTerminal)) + .build(), + response.toBuilder() + .setSettlementReceipt(ByteString.copyFrom(missingWorldTerminal)) + .build(), + response.toBuilder() + .setSettlementReceipt(ByteString.copyFrom(noncanonicalWorldTerminal)) + .build(), + response.toBuilder() + .setSettlementReceipt( + response.getSettlementReceipt().concat(ByteString.copyFrom(new byte[] {0}))) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, wrongOutcome)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void enforcesCompleteSerializedMessageBudgetBeforeReceiptDecoding() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + byte[] oversizedReceipt = + new byte[AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES]; + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, oversizedReceipt)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("32 MiB"); + + var oversizedResponse = + SettleSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setSettlementReceipt(ByteString.copyFrom(oversizedReceipt)) + .build(); + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.fromResponse( + request, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("32 MiB"); + } + + private static byte[] receipt( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence terminal, + String outcomeOverride, + byte[] accountBindingOverride, + byte[] operationOverride, + byte[] worldTerminalOverride) { + String outcome = + outcomeOverride == null + ? terminal.outcome() == Outcome.PUBLISHED ? "PUBLISHED" : "ABORTED" + : outcomeOverride; + byte[] accountBinding = + accountBindingOverride == null + ? operation.account().canonicalBytes() + : accountBindingOverride; + byte[] operationBytes = + operationOverride == null ? operation.canonicalBytes() : operationOverride; + byte[] worldTerminal = + worldTerminalOverride == null ? terminal.canonicalBytes() : worldTerminalOverride; + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, accountBinding); + DraftAuthorizationFenceBinding.frame(out, operationBytes); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome); + DraftAuthorizationFenceBinding.frame(out, worldTerminal); + return out.toByteArray(); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java new file mode 100644 index 0000000000..6e66abf4af --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.common.publication; + +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.clearInvocations; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Transaction ordering units; mocked channels do not establish an mTLS handshake. */ +class GameDesignPublicationTerminalClientTransactionTest { + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void excludesActiveAndSynchronizationOnlyTransactionsBeforeAnyRpc(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("design.internal:6565"); + when(factory.buildChannel( + eq("design.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(mock(ManagedChannel.class)); + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private-key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "ca").toString()); + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", operation.canonicalBytes()); + var expected = + new GameDesignPublicationTerminalReadEvidence.ReadResult( + request, GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN, Optional.empty()); + var stub = + mock( + GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.readGameDesignPublicationTerminal(any())) + .thenReturn(GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, expected)); + + try (var client = new GameDesignPublicationTerminalClient(endpoints, tls, factory, "test")) { + client.init(); + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + assertThat(client.read(request).canonicalBytes()).containsExactly(expected.canonicalBytes()); + clearInvocations(stub); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + TransactionSynchronizationManager.clearSynchronization(); + verifyNoInteractions(stub); + + assertThat(client.read(request).canonicalBytes()).containsExactly(expected.canonicalBytes()); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..bee71c9c09 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java @@ -0,0 +1,172 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import org.junit.jupiter.api.Test; + +/** Preserved donor refusal vectors mapped to the canonical framed read, with controlled inputs. */ +class GameDesignPublicationTerminalReadGrpcCodecTest { + @Test + void retainsExactReadCorrelationAndTerminalBytesForEveryCanonicalStatus() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = ReadRequest.create("test", operation.canonicalBytes()); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request))) + .isEqualTo(request); + for (Status status : Status.values()) { + var terminal = + status == Status.UNKNOWN + ? Optional + . + empty() + : Optional.of( + WorldPublicationTerminalTestFixtures.terminal( + operation, Outcome.valueOf(status.name()))); + var result = new ReadResult(request, status, terminal); + var response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .containsExactly(result.canonicalBytes()); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .containsExactly(result.canonicalBytes()); + } + } + + @Test + void rejectsUnknownMalformedNoncanonicalAndIncompleteFramedRequests() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = ReadRequest.create("test", operation.canonicalBytes()); + var wire = GameDesignPublicationTerminalReadGrpcCodec.toRequest(request); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class); + for (byte[] invalid : + List.of( + new byte[0], + new byte[] {1}, + replaceFrame(request.canonicalBytes(), 1, text("2")), + replaceFrame(request.canonicalBytes(), 2, text("Test")), + replaceFrame(request.canonicalBytes(), 2, text("other")), + replaceFrame(request.canonicalBytes(), 3, text("00000000-0000-0000-0000-000000000000")), + replaceFrame(request.canonicalBytes(), 3, text("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA")), + replaceFrame(request.canonicalBytes(), 3, text("1-1-1-1-1")), + replaceFrame(request.canonicalBytes(), 4, new byte[0]), + replaceFrame(request.canonicalBytes(), 4, new byte[] {1}), + java.util.Arrays.copyOf( + request.canonicalBytes(), request.canonicalBytes().length + 1))) { + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + wire.toBuilder() + .setCanonicalRequestBytes(ByteString.copyFrom(invalid)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsChangedEchoUnknownMalformedMissingAndSubstitutedTerminalResponses() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = ReadRequest.create("test", operation.canonicalBytes()); + var terminal = WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.NO_PUBLICATION); + var result = new ReadResult(request, Status.NO_PUBLICATION, Optional.of(terminal)); + var wire = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result); + var changedRequest = ReadRequest.create("test", operation.canonicalBytes()); + var changedTerminal = + WorldPublicationTerminalTestFixtures.terminal( + WorldPublicationTerminalTestFixtures.operation(), Outcome.NO_PUBLICATION); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, wire.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class); + for (byte[] invalid : + List.of( + new byte[0], + new byte[] {1}, + replaceFrame(result.canonicalBytes(), 1, changedRequest.canonicalBytes()), + replaceFrame(result.canonicalBytes(), 2, text("UNKNOWN")), + replaceFrame(result.canonicalBytes(), 2, text("PUBLISHED")), + replaceFrame(result.canonicalBytes(), 3, new byte[0]), + replaceFrame(result.canonicalBytes(), 3, new byte[] {1}), + replaceFrame(result.canonicalBytes(), 3, changedTerminal.canonicalBytes()), + java.util.Arrays.copyOf(result.canonicalBytes(), result.canonicalBytes().length + 1))) { + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, + wire.toBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(invalid)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + var changedResult = + new ReadResult(changedRequest, Status.NO_PUBLICATION, Optional.of(terminal)); + assertThatThrownBy( + () -> GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, changedResult)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadResult(request, Status.UNKNOWN, Optional.of(terminal))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadResult(request, Status.PUBLISHED, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void retainsDefensiveOperationBytesAndRejectsReusedOriginalIdentity() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + byte[] input = operation.canonicalBytes(); + var request = ReadRequest.create("test", input); + java.util.Arrays.fill(input, (byte) 0); + assertThat(request.operationBytes()).containsExactly(operation.canonicalBytes()); + byte[] returned = request.operationBytes(); + java.util.Arrays.fill(returned, (byte) 0); + assertThat(request.operationBytes()).containsExactly(operation.canonicalBytes()); + assertThatThrownBy( + () -> + new ReadRequest( + 1, "test", operation.account().operationId(), operation.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static byte[] text(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static byte[] replaceFrame(byte[] framed, int target, byte[] replacement) { + var input = ByteBuffer.wrap(framed); + var output = new ByteArrayOutputStream(); + for (int index = 0; input.hasRemaining(); index++) { + int length = input.getInt(); + byte[] value = new byte[length]; + input.get(value); + DraftAuthorizationFenceBinding.frame(output, index == target ? replacement : value); + } + return output.toByteArray(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java index c46c8135fe..af7d66dd4a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java @@ -5,8 +5,10 @@ import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationRequest; @@ -41,6 +43,41 @@ void roundTripsBothTerminalOutcomesAndUsesIndependentTransportCorrelation() thro } } + @Test + void historicalTerminalReadbackCannotEnterCurrentV2CompletionTransport() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var history = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(history, "game-design-publication-operation/v1"); + DraftAuthorizationFenceBinding.frame(history, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(history, operation.world().canonicalBytes()); + byte[] original = history.toByteArray(); + var historicalTerminal = + new GameDesignPublicationTerminalEvidence(original, Outcome.NO_PUBLICATION, null, null); + assertThat( + GameDesignPublicationTerminalEvidence.fromStored(historicalTerminal.canonicalBytes()) + .operationBytes()) + .containsExactly(original); + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", original, historicalTerminal.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Complete canonical publication operation and terminal required"); + + var currentTerminal = + WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.NO_PUBLICATION); + var current = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), currentTerminal.canonicalBytes()); + var changed = + WorldPublicationTerminalCompletionGrpcCodec.toRequest(current).toBuilder() + .setOriginalOperation(ByteString.copyFrom(original)) + .setGameDesignTerminalEvidence(ByteString.copyFrom(historicalTerminal.canonicalBytes())) + .build(); + assertThatThrownBy(() -> WorldPublicationTerminalCompletionGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void rejectsMalformedAndNoncanonicalRequestsAndUnknownFields() throws Exception { var operation = WorldPublicationTerminalTestFixtures.operation(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java new file mode 100644 index 0000000000..f92a8c58d1 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java @@ -0,0 +1,339 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Game Design admission boundary for one exact selected-Draft publication. Account + * authorization, World freeze and selector capture finish before the local reservation transaction. + */ +public final class SelectedDraftPublicationAdmissionService { + private final AccountPublicationAuthorizationReadClient accountClient; + private final WorldPublishedStartLocationClient worldClient; + private final WorldSelectedDraftPublicationFreezeClient freezeClient; + private final WorldSelectedPublicationArtifactInventoryClient inventoryClient; + private final SelectionReader selectionReader; + private final SelectedDraftPublicationOwner owner; + private final WorldAuthoredSourceIntakeClient worldSourceIntakeClient; + private final GameAuthoredWorldSourceRepository worldSourceRepository; + private final GameAuthoredWorldSourceDeliveryRepository worldSourceDeliveryRepository; + private final TransactionTemplate reservationTransaction; + private final String workloadNamespace; + + public SelectedDraftPublicationAdmissionService( + DSLContext dsl, + PlatformTransactionManager transactionManager, + AccountPublicationAuthorizationReadClient accountClient, + WorldSelectedDraftPublicationFreezeClient freezeClient, + WorldSelectedPublicationArtifactInventoryClient inventoryClient, + WorldPublishedStartLocationClient worldClient, + WorldAuthoredSourceIntakeClient worldSourceIntakeClient, + String workloadNamespace) { + this( + transactionManager, + accountClient, + freezeClient, + inventoryClient, + worldClient, + worldSourceIntakeClient, + new GameAuthoredWorldSourceRepository(Objects.requireNonNull(dsl, "dsl")), + new GameAuthoredWorldSourceDeliveryRepository(dsl), + new SelectedDraftPublicationOwner(Objects.requireNonNull(dsl, "dsl")), + intent -> + new AuthoredDraftPublishSelectionRepository( + dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId()) + .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection), + workloadNamespace); + } + + SelectedDraftPublicationAdmissionService( + PlatformTransactionManager transactionManager, + AccountPublicationAuthorizationReadClient accountClient, + WorldSelectedDraftPublicationFreezeClient freezeClient, + WorldSelectedPublicationArtifactInventoryClient inventoryClient, + WorldPublishedStartLocationClient worldClient, + WorldAuthoredSourceIntakeClient worldSourceIntakeClient, + GameAuthoredWorldSourceRepository worldSourceRepository, + GameAuthoredWorldSourceDeliveryRepository worldSourceDeliveryRepository, + SelectedDraftPublicationOwner owner, + SelectionReader selectionReader, + String workloadNamespace) { + this.accountClient = Objects.requireNonNull(accountClient, "accountClient"); + this.worldClient = Objects.requireNonNull(worldClient, "worldClient"); + this.freezeClient = Objects.requireNonNull(freezeClient, "freezeClient"); + this.inventoryClient = Objects.requireNonNull(inventoryClient, "inventoryClient"); + this.worldSourceIntakeClient = + Objects.requireNonNull(worldSourceIntakeClient, "worldSourceIntakeClient"); + this.worldSourceRepository = + Objects.requireNonNull(worldSourceRepository, "worldSourceRepository"); + this.worldSourceDeliveryRepository = + Objects.requireNonNull(worldSourceDeliveryRepository, "worldSourceDeliveryRepository"); + this.selectionReader = Objects.requireNonNull(selectionReader, "selectionReader"); + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.reservationTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + this.reservationTransaction.setName("selected-draft-publication-reservation"); + this.reservationTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + this.reservationTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.reservationTransaction.setReadOnly(false); + } + + /** + * Verifies the retained selection, authenticates Account HELD, freezes World, and reads the exact + * selector and complete source receipt before reserving locally. All owner reads complete outside + * SQL. + */ + public SelectedDraftPublicationOwner.Reservation admitAndReserve( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding) { + requireNoAmbientTransaction(); + Objects.requireNonNull(intent, "intent"); + Objects.requireNonNull(accountBinding, "accountBinding"); + AuthoredDraftPublishSelection selection = + selectionReader + .read(intent) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")); + requireRequestIdentity(intent, accountBinding, selection); + + AccountPublicationAuthorizationReadEvidence.Request accountReadRequest = + AccountPublicationAuthorizationReadEvidence.Request.create( + workloadNamespace, accountBinding); + AccountPublicationAuthorizationReadEvidence accountEvidence = + accountClient.read(accountReadRequest); + requireExactAccountReadback(accountReadRequest, accountBinding, accountEvidence); + + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + workloadNamespace, + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + selection.digest().substring("sha256:".length()), + accountEvidence.request().binding()); + var freeze = freezeClient.begin(freezeRequest); + if (freeze == null + || !freezeRequest.equals(freeze.request()) + || !freezeRequest.equals(freeze.acknowledgement().request())) { + throw new IllegalStateException( + "World publication freeze readback differs from the exact request"); + } + var acknowledgement = freeze.acknowledgement(); + var inventory = inventoryClient.read(freeze); + if (inventory == null + || !freeze.request().equals(inventory.freezeEvidence().request()) + || !freeze.acknowledgement().equals(inventory.freezeEvidence().acknowledgement())) { + throw new IllegalStateException( + "World inventory readback differs from exact acknowledged freeze"); + } + var worldRequest = + new WorldPublishedStartLocationEvidence.Request( + workloadNamespace, + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + acknowledgement.intakeRequestId(), + acknowledgement.publicationFence(), + intent.publishRequestId(), + freezeRequest.requestDigest(), + acknowledgement.versionStateEpoch(), + PublicationDigestRequestBinding.full( + intent.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity(), + acknowledgement.appliedCommitId(), + acknowledgement.contentDigest(), + acknowledgement.digestSchemaVersion(), + selection + .selectedCommit() + .affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT) + .stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList()); + WorldPublishedStartLocationEvidence worldEvidence = worldClient.read(worldRequest); + requireExactWorldReadback(worldRequest, worldEvidence); + new GameDesignPublicationOperationBinding( + accountEvidence.request().binding(), worldEvidence, inventory); + SelectedDraftTemplateWorldSourceAssociation.SourceRead worldSourceRead = + readAndVerifyWorldSource(worldEvidence, selection.target()); + + return Objects.requireNonNull( + reservationTransaction.execute( + status -> + owner.reserve( + intent, + accountEvidence.request().binding(), + worldEvidence, + inventory, + worldSourceRead)), + "Selected Draft publication reservation returned no result"); + } + + private SelectedDraftTemplateWorldSourceAssociation.SourceRead readAndVerifyWorldSource( + WorldPublishedStartLocationEvidence worldEvidence, + DraftCommitBinding.TargetProof selectedTarget) { + var selected = worldEvidence.request(); + java.util.UUID readRequestId = java.util.UUID.randomUUID(); + while (readRequestId.equals(selected.intakeRequestId())) { + readRequestId = java.util.UUID.randomUUID(); + } + var request = + new ByIdReadRequest( + 1, + selected.targetNamespace(), + readRequestId, + selected.intakeRequestId(), + selected.canonicalTenantId()); + var receipt = worldSourceIntakeClient.readById(request); + var worldRead = new SelectedDraftTemplateWorldSourceAssociation.SourceRead(request, receipt); + var source = + worldSourceRepository + .read( + receipt.sourceOperationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + selected.targetNamespace()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_WORLD_SOURCE_GD_RECORD_UNAVAILABLE")); + var delivery = + worldSourceDeliveryRepository + .read(receipt.sourceOperationId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_WORLD_SOURCE_DELIVERY_UNAVAILABLE")); + var expectedReceipt = + new CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest()); + if (!source.equals(receipt.source()) + || !delivery.source().equals(source) + || !delivery.request().targetNamespace().equals(selected.targetNamespace()) + || !delivery.request().intakeRequestId().equals(selected.intakeRequestId()) + || !delivery.request().canonicalTenantId().equals(selected.canonicalTenantId()) + || !delivery.request().worldSlug().equals(receipt.worldSlug()) + || !delivery.request().sourceOperationId().equals(receipt.sourceOperationId()) + || !delivery.request().expectedSourceEvidenceDigest().equals(receipt.sourceEvidenceDigest()) + || source.sourceGameRowId() != selectedTarget.sourceGameRowId() + || !source.sourceGameTenantKey().equals(selectedTarget.sourceGameTenantKey()) + || !source.provenanceKind().equals(selectedTarget.sourceProvenanceKind()) + || !WorldAuthoredSourceIntakeGrpcCodec.requestDigest(delivery.request()) + .equals(receipt.requestDigest()) + || delivery.acknowledgedReceipt().filter(ack -> !ack.equals(expectedReceipt)).isPresent()) { + throw new IllegalStateException( + "SELECTED_WORLD_SOURCE_OWNER_READBACK_CONFLICT: World, retained source, and original delivery differ"); + } + return worldRead; + } + + private void requireRequestIdentity( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding, + AuthoredDraftPublishSelection selection) { + var intentFromBinding = accountBinding.input().selection().intent(); + var expectedIntent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + if (!expectedIntent.equals(intentFromBinding) + || !intent.equals(selection.intent()) + || !Arrays.equals( + selection.canonicalBytes(), accountBinding.input().selection().canonicalBytes())) { + throw new IllegalArgumentException( + "Account publication binding and retained selection must match the exact selected Draft intent"); + } + } + + @FunctionalInterface + interface SelectionReader { + Optional read( + AuthoredDraftPublishSelection.PublishIntent intent); + } + + private static void requireExactAccountReadback( + AccountPublicationAuthorizationReadEvidence.Request expectedRequest, + AccountPublicationAuthorizationBinding expectedBinding, + AccountPublicationAuthorizationReadEvidence evidence) { + if (evidence == null + || !expectedRequest.equals(evidence.request()) + || !java.util.Arrays.equals( + expectedBinding.canonicalBytes(), evidence.request().binding().canonicalBytes())) { + throw new IllegalStateException( + "Account publication authorization readback differs from the exact request"); + } + } + + private static void requireExactWorldReadback( + WorldPublishedStartLocationEvidence.Request expectedRequest, + WorldPublishedStartLocationEvidence evidence) { + if (evidence == null || !expectedRequest.equals(evidence.request())) { + throw new IllegalStateException( + "World publication selector readback differs from the exact request"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Selected Draft publication owner reads require no ambient transaction"); + } + } +} diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index f50e80d7a4..7f7b8a47eb 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -22,10 +22,13 @@ import java.util.ArrayList; import java.util.Date; import java.util.HexFormat; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Supplier; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestGrpcReceiver; import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestService; @@ -52,7 +55,6 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; -import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; @@ -75,8 +77,6 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; -import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; -import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; @@ -126,7 +126,9 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -165,11 +167,61 @@ class SelectedFullOwnerPublicationPostgresIntegrationTest { static final PostgreSQLContainer GAME_LOGIC_POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + private static final org.testcontainers.containers.Network ACCOUNT_NETWORK = + org.testcontainers.containers.Network.newNetwork(); + + @Container + static final PostgreSQLContainer ACCOUNT_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final org.testcontainers.containers.GenericContainer ACCOUNT_REDIS = + new org.testcontainers.containers.GenericContainer<>(TestContainerImages.redis()) + .withNetwork(ACCOUNT_NETWORK) + .withNetworkAliases("selected-reservation-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final org.testcontainers.containers.GenericContainer ACCOUNT_REPLICA = + new org.testcontainers.containers.GenericContainer<>(TestContainerImages.redis()) + .withNetwork(ACCOUNT_NETWORK) + .dependsOn(ACCOUNT_REDIS) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "selected-reservation-primary", + "6379"); + @TempDir Path temporary; @Test void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchemaFourBundle() throws Exception { + var diagnostics = new SettlementDiagnostics(); + diagnostics.logPostgres("game-design", GDS_POSTGRES); + diagnostics.logPostgres("world-management", WORLD_POSTGRES); + diagnostics.logPostgres("entity-management", ENTITY_POSTGRES); + diagnostics.logPostgres("automation-scripting", AUTOMATION_POSTGRES); + diagnostics.logPostgres("game-logic", GAME_LOGIC_POSTGRES); + diagnostics.logPostgres("account", ACCOUNT_POSTGRES); Store gds = store("game-design", "selected_full_gds", GDS_POSTGRES, false); Store world = store("world-management", "selected_full_world", WORLD_POSTGRES, false); Store entity = store("entity-management", "selected_full_entity", ENTITY_POSTGRES, true); @@ -181,9 +233,19 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema var worldSource = registerControlledWorldSource(gds, draft.target()); DraftCommitBinding commit = selectedCommit(gds, draft.target()); applyGameDesignCommit(gds, commit); + var delivery = + new net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository( + gds.dsl()) + .read(worldSource.operationId()) + .orElseThrow(); var worldGraph = WorldSelectedFullPublicationEvidenceFixture.applyGraph( - world.dsl(), world.transactions(), NAMESPACE, commit, worldSource); + world.dsl(), + world.transactions(), + NAMESPACE, + commit, + worldSource, + delivery.request().intakeRequestId()); completeGameDesignCommit(gds, commit, worldGraph.applied()); String publishRequestId = "selected-full-" + UUID.randomUUID(); @@ -205,465 +267,1169 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())) .reserve(intent) .selection()); - var worldOwners = - WorldSelectedFullPublicationEvidenceFixture.applyFreezeAndCapture( - world.dsl(), - world.transactions(), - NAMESPACE, - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson(), selection.digest()), - worldGraph, - SelectedFullOwnerPublicationPostgresIntegrationTest::controlledAccountBinding); - assertThat(worldOwners.selectedWorldDigest().digestSchemaVersion()).isEqualTo(4); - assertThat(worldOwners.appliedResultBytes()).isNotEmpty(); - assertThat(worldOwners.graphBytes()).isNotEmpty(); - assertThat(worldOwners.inventoryEvidence().freezeEvidence()) - .isEqualTo(worldOwners.freezeEvidence()); - - var sourceScopeActor = UUID.randomUUID(); - var entityAuthorization = - selectedOwnerAuthorization(gds, selection, Owner.ENTITY_MANAGEMENT, sourceScopeActor); - var entityWorldRead = - SelectedOwnerWorldInventoryReadEvidence.create( - NAMESPACE, entityAuthorization, worldOwners.freezeEvidence()); - var entityInputs = - new SelectedOwnerEmptySourceInputs( - entityAuthorization, - new SelectedOwnerWorldInventoryReadEvidence( - entityWorldRead, worldOwners.inventoryEvidence())); - var entityRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); - var entityReceipt = - entityRepository.retainFresh( - entityInputs, - EntityEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())); - assertThat( - entityRepository - .read(entityReceipt.targetNamespace(), entityReceipt.intakeRequestId()) - .orElseThrow() - .canonicalBytes()) - .containsExactly(entityReceipt.canonicalBytes()); - assertThat( - entityRepository - .retainFresh( - entityInputs, - EntityEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())) - .canonicalBytes()) - .containsExactly(entityReceipt.canonicalBytes()); - - var automationAuthorization = - selectedOwnerAuthorization(gds, selection, Owner.AUTOMATION_SCRIPTING, sourceScopeActor); - var automationWorldRead = - SelectedOwnerWorldInventoryReadEvidence.create( - NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()); - var automationInputs = - new SelectedOwnerEmptySourceInputs( - automationAuthorization, - new SelectedOwnerWorldInventoryReadEvidence( - automationWorldRead, worldOwners.inventoryEvidence())); - var automationRepository = new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); - var automationReceipt = - automationRepository.retainFresh( - automationInputs, - net.firedevops.firemud.common.automation.sourceintake - .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())); - assertThat( - automationRepository - .read(automationReceipt.targetNamespace(), automationReceipt.intakeRequestId()) - .orElseThrow() - .canonicalBytes()) - .containsExactly(automationReceipt.canonicalBytes()); - assertThat( - automationRepository - .retainFresh( - automationInputs, - net.firedevops.firemud.common.automation.sourceintake - .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())) - .canonicalBytes()) - .containsExactly(automationReceipt.canonicalBytes()); - - var synchronizedSources = - new GameDesignSourceRepository(gds.dsl()) - .readSynchronized(draft.target(), commit.commitId()) - .orElseThrow(); - assertThat(synchronizedSources.command().definitions()).isEmpty(); - var gameplaySnapshot = synchronizedSources.gameplayEvidence().orElseThrow(); - assertThat(gameplaySnapshot.manifest().families().get(GameplayRuleManifest.Family.COMMANDS)) - .extracting(GameplayRuleManifest.Definition::key) - .containsExactly("LOOK"); - var gameplaySource = new GameplayRuleSelectedSource(gameplaySnapshot.canonicalJson()); - var glAuthorization = - new GameLogicIntakeAuthorizationBinding( - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - sourceScopeActor, - gameplaySource, - controlledAccountSources(sourceScopeActor, draft.target().canonicalTenantId())); - var glOperation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, glAuthorization); - var glTerminal = - GameLogicGameplayRuleIntakeTerminal.retained( - glOperation, - gameplaySource.canonicalBytes(), - gameplaySource.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); - var glOwner = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); - gameLogic - .write() - .execute( - ignored -> { - glOwner.lockOperation(glAuthorization.operationId()); - glOwner.insertTerminal(glTerminal); - return null; - }); - var committedGlTerminal = glOwner.findTerminal(glAuthorization.operationId()).orElseThrow(); - assertThat(committedGlTerminal.canonicalBytes()).containsExactly(glTerminal.canonicalBytes()); - - var selectedReceiptRepository = new SelectedDraftGameLogicReceiptRepository(gds.dsl()); - var glReceiptCandidate = - new SelectedDraftGameLogicReceipt( - selection, - glAuthorization, - new AccountGameLogicIntakeSettlementEvidence(committedGlTerminal)); - var glReceipt = - gds.write().execute(ignored -> selectedReceiptRepository.retain(glReceiptCandidate)); - assertThat( - selectedReceiptRepository - .readForPublication( - PublicationDigestRequestBinding.full( - draft.target().canonicalTenantId().toString(), - Long.toString(draft.version().getId()), - publishRequestId)) - .orElseThrow() - .receipt() - .canonicalBytes()) - .containsExactly(glReceipt.receipt().canonicalBytes()); - - var selectionBinding = - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson(), selection.digest()); - var accountBinding = worldOwners.accountBinding(); - var templateSourceRead = - new SelectedDraftTemplateWorldSourceAssociation.SourceRead( - worldOwners.sourceReadRequest(), worldOwners.sourceReadReceipt()); - var selectedOwnerReservation = - gds.write() - .execute( - ignored -> - new SelectedDraftPublicationOwner(gds.dsl()) - .reserve( - intent, - accountBinding, - worldOwners.startLocationEvidence(), - worldOwners.inventoryEvidence(), - templateSourceRead)); - assertThat(selectedOwnerReservation.selection().canonicalBytes()) - .containsExactly(selectionBinding.canonicalBytes()); - - Long gdsBundleBefore = - gds.dsl() - .fetchSingle( - "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", - draft.version().getTenantId(), - draft.version().getId()) - .get(0, Long.class); - assertThat(gdsBundleBefore).isZero(); - - ProofPki pki = new ProofPki(temporary.resolve("selected-full-pki")); - Server entityServer = null; - Server automationServer = null; - Server gameLogicServer = null; - try { - entityServer = - ownerServer( - pki, - "entity-management-service", - new EntitySelectedEmptyPublicationDigestGrpcReceiver( - new EntitySelectedEmptyPublicationDigestService(NAMESPACE, entityRepository), - NAMESPACE, - new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); - automationServer = - ownerServer( - pki, - "automation-scripting-service", - new AutomationSelectedEmptyPublicationDigestGrpcReceiver( - new AutomationSelectedEmptyPublicationDigestService( - NAMESPACE, automationRepository), - NAMESPACE, - new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); - gameLogicServer = - ownerServer( - pki, - "game-logic-service", - new GameLogicGrpcService( + try (var accountFixture = + new AccountControlUiOriginalOrderFixture( + ACCOUNT_POSTGRES.getJdbcUrl(), + ACCOUNT_POSTGRES.getUsername(), + ACCOUNT_POSTGRES.getPassword(), + ACCOUNT_REDIS.getHost(), + ACCOUNT_REDIS.getMappedPort(6379), + temporary.resolve("account-original"), + draft.target().canonicalTenantId())) { + var issuedCreator = accountFixture.issueCreator(); + var accountSources = issuedCreator.sources(); + var publicationPki = new ProofPki(temporary.resolve("fresh-world-begin-pki")); + var publicationAuthorization = + authenticatedAccountPublicationOrder( + gds, + issuedCreator, + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + publicationPki); + var worldOwners = + freshAuthenticatedWorldFreeze( + gds, + world, + accountSources.dsl, + accountSources.manager, + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + worldGraph, + publicationAuthorization, + publicationPki); + assertThat(worldOwners.selectedWorldDigest().digestSchemaVersion()).isEqualTo(4); + assertThat(worldOwners.appliedResultBytes()).isNotEmpty(); + assertThat(worldOwners.graphBytes()).isNotEmpty(); + assertThat(worldOwners.inventoryEvidence().freezeEvidence()) + .isEqualTo(worldOwners.freezeEvidence()); + + var sourceScopeActor = UUID.randomUUID(); + var entityAuthorization = + selectedOwnerAuthorization(gds, selection, Owner.ENTITY_MANAGEMENT, sourceScopeActor); + var entityWorldRead = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence()); + var entityInputs = + new SelectedOwnerEmptySourceInputs( + entityAuthorization, + new SelectedOwnerWorldInventoryReadEvidence( + entityWorldRead, worldOwners.inventoryEvidence())); + var entityRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); + var entityReceipt = + entityRepository.retainFresh( + entityInputs, + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())); + assertThat( + entityRepository + .read(entityReceipt.targetNamespace(), entityReceipt.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + assertThat( + entityRepository + .retainFresh( + entityInputs, + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())) + .canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + + var automationAuthorization = + selectedOwnerAuthorization(gds, selection, Owner.AUTOMATION_SCRIPTING, sourceScopeActor); + var automationWorldRead = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()); + var automationInputs = + new SelectedOwnerEmptySourceInputs( + automationAuthorization, + new SelectedOwnerWorldInventoryReadEvidence( + automationWorldRead, worldOwners.inventoryEvidence())); + var automationRepository = + new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); + var automationReceipt = + automationRepository.retainFresh( + automationInputs, + net.firedevops.firemud.common.automation.sourceintake + .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())); + assertThat( + automationRepository + .read(automationReceipt.targetNamespace(), automationReceipt.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + assertThat( + automationRepository + .retainFresh( + automationInputs, + net.firedevops.firemud.common.automation.sourceintake + .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())) + .canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + + var synchronizedSources = + new GameDesignSourceRepository(gds.dsl()) + .readSynchronized(draft.target(), commit.commitId()) + .orElseThrow(); + assertThat(synchronizedSources.command().definitions()).isEmpty(); + var gameplaySnapshot = synchronizedSources.gameplayEvidence().orElseThrow(); + assertThat(gameplaySnapshot.manifest().families().get(GameplayRuleManifest.Family.COMMANDS)) + .extracting(GameplayRuleManifest.Definition::key) + .containsExactly("LOOK"); + var gameplaySource = new GameplayRuleSelectedSource(gameplaySnapshot.canonicalJson()); + var glAuthorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + sourceScopeActor, + gameplaySource, + controlledAccountSources(sourceScopeActor, draft.target().canonicalTenantId())); + var glOperation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, glAuthorization); + var glTerminal = + GameLogicGameplayRuleIntakeTerminal.retained( + glOperation, + gameplaySource.canonicalBytes(), + gameplaySource.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var glOwner = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); + gameLogic + .write() + .execute( + ignored -> { + glOwner.lockOperation(glAuthorization.operationId()); + glOwner.insertTerminal(glTerminal); + return null; + }); + var committedGlTerminal = glOwner.findTerminal(glAuthorization.operationId()).orElseThrow(); + assertThat(committedGlTerminal.canonicalBytes()).containsExactly(glTerminal.canonicalBytes()); + + var selectedReceiptRepository = new SelectedDraftGameLogicReceiptRepository(gds.dsl()); + var glReceiptCandidate = + new SelectedDraftGameLogicReceipt( + selection, + glAuthorization, + new AccountGameLogicIntakeSettlementEvidence(committedGlTerminal)); + var glReceipt = + gds.write().execute(ignored -> selectedReceiptRepository.retain(glReceiptCandidate)); + assertThat( + selectedReceiptRepository + .readForPublication( + PublicationDigestRequestBinding.full( + draft.target().canonicalTenantId().toString(), + Long.toString(draft.version().getId()), + publishRequestId)) + .orElseThrow() + .receipt() + .canonicalBytes()) + .containsExactly(glReceipt.receipt().canonicalBytes()); + + var selectionBinding = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + var accountBinding = worldOwners.accountBinding(); + + Long gdsBundleBefore = + gds.dsl() + .fetchSingle( + "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + draft.version().getTenantId(), + draft.version().getId()) + .get(0, Long.class); + assertThat(gdsBundleBefore).isZero(); + + ProofPki pki = new ProofPki(temporary.resolve("selected-full-pki")); + Server accountServer = null; + Server worldServer = null; + Server entityServer = null; + Server automationServer = null; + Server gameLogicServer = null; + // This case recovers the exact already-committed World freeze. Mutable owner reads must not + // repeat. + var replaySelection = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient + .class); + var replayVersion = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient.class); + var replayAccount = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient + .class); + var replaySource = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient.class); + try { + accountServer = + ownerServer( + pki, + "account-service", + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + new AccountPublicationAuthorizationRepository(accountSources.dsl), + accountSources.manager, + NAMESPACE), + NAMESPACE)); + var worldReaders = + WorldSelectedFullPublicationEvidenceFixture.reservationReadEndpoints( + world.dsl(), + world.transactions(), + NAMESPACE, + replaySelection, + replayVersion, + replayAccount, + replaySource); + worldServer = + ownerServer( + pki, + "world-management-service", + worldReaders.toArray(io.grpc.BindableService[]::new)); + entityServer = + ownerServer( + pki, + "entity-management-service", + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + new EntitySelectedEmptyPublicationDigestService(NAMESPACE, entityRepository), + NAMESPACE, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); + automationServer = + ownerServer( + pki, + "automation-scripting-service", + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + new AutomationSelectedEmptyPublicationDigestService( + NAMESPACE, automationRepository), + NAMESPACE, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); + gameLogicServer = + ownerServer( + pki, + "game-logic-service", + new GameLogicGrpcService( + null, + null, + null, + null, + null, + null, + new GameLogicDraftDesignDigestServiceImpl( + new GameLogicPublicationSourceReadService(glOwner, NAMESPACE)), + null, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry(), + new net.firedevops.firemud.common.security.PublicationReadGuard(NAMESPACE))); + + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService(loopback(accountServer)); + endpoints.setWorldManagementService(loopback(worldServer)); + endpoints.setEntityManagementService(loopback(entityServer)); + endpoints.setAutomationScriptingService(loopback(automationServer)); + endpoints.setGameLogicService(loopback(gameLogicServer)); + var channelFactory = new GrpcChannelFactory(); + try (var accountClient = + new net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var freezeClient = + new net.firedevops.firemud.common.publication + .WorldSelectedDraftPublicationFreezeClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var inventoryClient = + new net.firedevops.firemud.common.publication + .WorldSelectedPublicationArtifactInventoryClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var selectorClient = + new net.firedevops.firemud.common.world.WorldPublishedStartLocationClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var sourceClient = + new net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var entityClient = + new ReadyEntityManagementClient( + endpoints, pki.client("game-design-service"), channelFactory); + var automationClient = + new ReadyAutomationScriptingClient( + endpoints, pki.client("game-design-service"), channelFactory); + var gameLogicClient = + new ReadyGameLogicClient( + endpoints, pki.client("game-design-service"), channelFactory)) { + accountClient.init(); + freezeClient.init(); + inventoryClient.init(); + selectorClient.init(); + sourceClient.init(); + var admission = + new net.firedevops.firemud.gamedesign.publication + .SelectedDraftPublicationAdmissionService( + gds.dsl(), + gds.transactions(), + accountClient, + freezeClient, + inventoryClient, + selectorClient, + sourceClient, + NAMESPACE); + var selectedOwnerReservation = admission.admitAndReserve(intent, accountBinding); + assertThat(selectedOwnerReservation.selection().canonicalBytes()) + .containsExactly(selectionBinding.canonicalBytes()); + var reservationReplay = admission.admitAndReserve(intent, accountBinding); + assertThat(reservationReplay.operation().canonicalBytes()) + .containsExactly(selectedOwnerReservation.operation().canonicalBytes()); + org.mockito.Mockito.verifyNoInteractions( + replaySelection, replayVersion, replayAccount, replaySource); + ReflectionTestUtils.setField(gameLogicClient, "workloadNamespace", NAMESPACE); + entityClient.connect(); + automationClient.connect(); + gameLogicClient.connect(); + var gate = + new PublishGateServiceImpl( null, null, + entityClient, + gameLogicClient, + automationClient, + gds.dsl(), + gds.transactions(), + NAMESPACE); + VersionDto versionDto = versionDto(draft.version()); + var publicationRequest = + PublicationDigestRequestBinding.full( + draft.target().canonicalTenantId().toString(), + Long.toString(draft.version().getId()), + publishRequestId); + var participantDigests = + gate.collectSelectedFullVersionParticipantDigests( + versionDto, publicationRequest, publicationRequest.derivedWorkflowIdentity()); + assertThat(participantDigests) + .extracting(PublishParticipantDigestDto::participantKey) + .containsExactly( + "WORLD_MANAGEMENT", + "ENTITY_MANAGEMENT", + "GAME_LOGIC", + "AUTOMATION_SCRIPTING", + "GAME_DESIGN_CONTROL_PLANE"); + assertThat(participantDigests) + .extracting(PublishParticipantDigestDto::digestSchemaVersion) + .containsExactly(4, 3, 1, 6, 2); + assertThat(participantDigests) + .filteredOn(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey())) + .singleElement() + .satisfies( + digest -> + assertThat(digest.contentDigest()) + .isEqualTo(worldOwners.selectedWorldDigest().contentDigest())); + assertThat(participantDigests) + .filteredOn(digest -> "GAME_LOGIC".equals(digest.participantKey())) + .singleElement() + .satisfies(digest -> assertThat(digest.abilitySchemaDigest()).startsWith("sha256:")); + gate.assertSelectedGatePassed(versionDto, participantDigests); + + var altered = new ArrayList<>(participantDigests); + int automationIndex = 3; + var validAutomation = altered.get(automationIndex); + altered.set( + automationIndex, + new PublishParticipantDigestDto( + validAutomation.participantKey(), + validAutomation.scopeValue(), + validAutomation.baseVersionId(), + validAutomation.appliedCommitId(), + validAutomation.contentDigest(), + 5, + validAutomation.abilitySchemaDigest(), + validAutomation.errorCode(), + validAutomation.errorMessage())); + gate.assertSelectedGatePassed(versionDto, participantDigests); + assertThatThrownBy(() -> gate.assertSelectedGatePassed(versionDto, altered)) + .isInstanceOf(RuntimeException.class); + + var releaseService = + new PublishedReleaseBundleServiceImpl( + new PublishedReleaseBundleRepository(gds.dsl()), + new VersionRepository(gds.dsl()), + new ObjectMapper()); + var controlledEmptyManifest = controlledEmptyManifest(); + var artifactRepository = + new net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository( + gds.dsl()); + var versions = new VersionRepository(gds.dsl()); + var artifactService = + new net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl( + artifactRepository, + null, + versions, null, null, null, null, - new GameLogicDraftDesignDigestServiceImpl( - new GameLogicPublicationSourceReadService(glOwner, NAMESPACE)), null, - new io.micrometer.core.instrument.simple.SimpleMeterRegistry(), - new net.firedevops.firemud.common.security.PublicationReadGuard(NAMESPACE))); + new ObjectMapper()); + var assetPublication = + new net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository( + gds.dsl()); + var exportSnapshot = + gds.write() + .execute( + ignored -> + assetPublication.freezeOrReadSnapshot( + versionDto.tenantId(), versionDto.versionNumber())); + assertThat(exportSnapshot.items()).isEmpty(); + gds.write() + .execute( + ignored -> + artifactService.stageExport( + versionDto.tenantId(), + versionDto.id(), + versionDto.versionNumber(), + publicationRequest.derivedWorkflowIdentity())); + var candidateService = + new net.firedevops.firemud.gamedesign.service.impl + .VersionAssetExportCandidateServiceImpl( + versions, + new GameRepository(gds.dsl()), + new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( + gds.dsl()), + artifactRepository, + assetPublication, + gds.transactions(), + new ObjectMapper()); + // Controlled delivery origin and manifest metadata; no object-store or public delivery + // proof. + var candidate = + new net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate( + controlledEmptyManifest, "https://controlled.invalid/assets"); + assertThat( + candidateService.recordExportCandidate( + versionDto.tenantId(), versionDto.versionNumber(), candidate)) + .isEqualTo(candidate); + assertThat( + candidateService.readExportCandidate( + versionDto.tenantId(), versionDto.versionNumber())) + .isEqualTo(candidate); + assertThatThrownBy( + () -> + gds.write() + .execute( + ignored -> + releaseService.createFullVersionBundle( + versionDto, + publicationRequest.derivedWorkflowIdentity(), + controlledEmptyManifest, + "controlled-generation-input", + altered, + worldOwners.startLocationEvidence()))) + .isInstanceOf(RuntimeException.class); + assertThat( + gds.dsl() + .fetchSingle( + "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + draft.version().getTenantId(), + draft.version().getId()) + .get(0, Long.class)) + .isZero(); - var endpoints = new ServiceEndpointsProperties(); - endpoints.setEntityManagementService(loopback(entityServer)); - endpoints.setAutomationScriptingService(loopback(automationServer)); - endpoints.setGameLogicService(loopback(gameLogicServer)); - var channelFactory = new GrpcChannelFactory(); - try (var entityClient = - new ReadyEntityManagementClient( - endpoints, pki.client("game-design-service"), channelFactory); - var automationClient = - new ReadyAutomationScriptingClient( - endpoints, pki.client("game-design-service"), channelFactory); - var gameLogicClient = - new ReadyGameLogicClient( - endpoints, pki.client("game-design-service"), channelFactory)) { - ReflectionTestUtils.setField(gameLogicClient, "workloadNamespace", NAMESPACE); - entityClient.connect(); - automationClient.connect(); - gameLogicClient.connect(); - var gate = - new PublishGateServiceImpl( - null, - null, - entityClient, - gameLogicClient, - automationClient, - gds.dsl(), - gds.transactions(), - NAMESPACE); - VersionDto versionDto = versionDto(draft.version()); - var publicationRequest = - PublicationDigestRequestBinding.full( - draft.target().canonicalTenantId().toString(), - Long.toString(draft.version().getId()), - publishRequestId); - var participantDigests = - gate.collectSelectedFullVersionParticipantDigests( - versionDto, publicationRequest, publicationRequest.derivedWorkflowIdentity()); - assertThat(participantDigests) - .extracting(PublishParticipantDigestDto::participantKey) - .containsExactly( - "WORLD_MANAGEMENT", - "ENTITY_MANAGEMENT", - "GAME_LOGIC", - "AUTOMATION_SCRIPTING", - "GAME_DESIGN_CONTROL_PLANE"); - assertThat(participantDigests) - .extracting(PublishParticipantDigestDto::digestSchemaVersion) - .containsExactly(4, 3, 1, 6, 2); - assertThat(participantDigests) - .filteredOn(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey())) - .singleElement() - .satisfies( - digest -> - assertThat(digest.contentDigest()) - .isEqualTo(worldOwners.selectedWorldDigest().contentDigest())); - assertThat(participantDigests) - .filteredOn(digest -> "GAME_LOGIC".equals(digest.participantKey())) - .singleElement() - .satisfies(digest -> assertThat(digest.abilitySchemaDigest()).startsWith("sha256:")); - gate.assertSelectedGatePassed(versionDto, participantDigests); - - var altered = new ArrayList<>(participantDigests); - int automationIndex = 3; - var validAutomation = altered.get(automationIndex); - altered.set( - automationIndex, - new PublishParticipantDigestDto( - validAutomation.participantKey(), - validAutomation.scopeValue(), - validAutomation.baseVersionId(), - validAutomation.appliedCommitId(), - validAutomation.contentDigest(), - 5, - validAutomation.abilitySchemaDigest(), - validAutomation.errorCode(), - validAutomation.errorMessage())); - gate.assertSelectedGatePassed(versionDto, participantDigests); - assertThatThrownBy(() -> gate.assertSelectedGatePassed(versionDto, altered)) - .isInstanceOf(RuntimeException.class); - - var releaseService = - new PublishedReleaseBundleServiceImpl( - new PublishedReleaseBundleRepository(gds.dsl()), - new VersionRepository(gds.dsl()), - new ObjectMapper()); - var controlledEmptyManifest = controlledEmptyManifest(); - var artifactRepository = - new net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository( - gds.dsl()); - var versions = new VersionRepository(gds.dsl()); - var artifactService = - new net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl( - artifactRepository, - null, - versions, - null, - null, - null, - null, - null, - new ObjectMapper()); - var assetPublication = - new net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository( - gds.dsl()); - var exportSnapshot = - gds.write() - .execute( - ignored -> - assetPublication.freezeOrReadSnapshot( - versionDto.tenantId(), versionDto.versionNumber())); - assertThat(exportSnapshot.items()).isEmpty(); - gds.write() - .execute( - ignored -> - artifactService.stageExport( - versionDto.tenantId(), - versionDto.id(), - versionDto.versionNumber(), - publicationRequest.derivedWorkflowIdentity())); - var candidateService = - new net.firedevops.firemud.gamedesign.service.impl - .VersionAssetExportCandidateServiceImpl( - versions, - new GameRepository(gds.dsl()), - new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( - gds.dsl()), - artifactRepository, - assetPublication, - gds.transactions(), - new ObjectMapper()); - // Controlled delivery origin and manifest metadata; no object-store or public delivery - // proof. - var candidate = - new net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate( - controlledEmptyManifest, "https://controlled.invalid/assets"); - assertThat( - candidateService.recordExportCandidate( - versionDto.tenantId(), versionDto.versionNumber(), candidate)) - .isEqualTo(candidate); - assertThat( - candidateService.readExportCandidate( - versionDto.tenantId(), versionDto.versionNumber())) - .isEqualTo(candidate); - assertThatThrownBy( - () -> - gds.write() - .execute( - ignored -> - releaseService.createFullVersionBundle( - versionDto, - publicationRequest.derivedWorkflowIdentity(), - controlledEmptyManifest, - "controlled-generation-input", - altered, - worldOwners.startLocationEvidence()))) - .isInstanceOf(RuntimeException.class); - assertThat( - gds.dsl() - .fetchSingle( - "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", - draft.version().getTenantId(), - draft.version().getId()) - .get(0, Long.class)) - .isZero(); - - PublishedReleaseBundleService releaseOwner = releaseService; - var written = - gds.write() - .execute( - ignored -> { - String workflow = publicationRequest.derivedWorkflowIdentity(); - var exported = - artifactService.markExportedUnattested( - versionDto.tenantId(), - versionDto.id(), - versionDto.versionNumber(), - workflow, - controlledEmptyManifest); - var result = + PublishedReleaseBundleService releaseOwner = releaseService; + var written = + gds.write() + .execute( + ignored -> { + String workflow = publicationRequest.derivedWorkflowIdentity(); + var exported = + artifactService.markExportedUnattested( + versionDto.tenantId(), + versionDto.id(), + versionDto.versionNumber(), + workflow, + controlledEmptyManifest); + var result = + releaseOwner.createFullVersionBundle( + versionDto, + workflow, + controlledEmptyManifest, + "controlled-generation-input", + participantDigests, + worldOwners.startLocationEvidence()); + var version = + versions + .findByTenantIdAndIdForUpdate( + versionDto.tenantId(), versionDto.id()) + .orElseThrow(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch( + Math.addExact(version.getVersionStateEpoch(), 1L)); + versions.save(version); + artifactService.markPublished( + versionDto.tenantId(), + versionDto.id(), + exported.stateEpoch(), + workflow, + controlledEmptyManifest.manifestHash()); + var attempts = + new net.firedevops.firemud.gamedesign.repository + .PublishAttemptRepository(gds.dsl()); + var attempt = + attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow(); + attempt.setStatus( + net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); + attempts.save(attempt); + var operation = selectedOwnerReservation.operation(); + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationOperationRepository(gds.dsl()) + .seal( + operation.tenantKey(), + workflow, + operation.versionId(), + operation.selectionDigest(), + true); + return result; + }); + assertThat(written.attestationSchemaVersion()).isEqualTo("v4"); + assertThat(written.participantDigests()).containsExactlyElementsOf(participantDigests); + assertThat(written.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(worldOwners.startLocationEvidence().canonicalBytes()); + String committedBundleRow = bundleOwnerRow(gds, draft.version()); + var independentRead = + new PublishedReleaseBundleServiceImpl( + new PublishedReleaseBundleRepository(gds.dsl()), + new VersionRepository(gds.dsl()), + new ObjectMapper()) + .findPublishedReleaseBundle( + draft.version().getTenantId(), draft.version().getId()) + .orElseThrow(); + assertThat(independentRead).isEqualTo(written); + assertThat(independentRead.attestationSchemaVersion()).isEqualTo("v4"); + assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + + var replay = + gds.write() + .execute( + ignored -> releaseOwner.createFullVersionBundle( versionDto, - workflow, + publicationRequest.derivedWorkflowIdentity(), controlledEmptyManifest, "controlled-generation-input", participantDigests, - worldOwners.startLocationEvidence()); - var version = - versions - .findByTenantIdAndIdForUpdate(versionDto.tenantId(), versionDto.id()) - .orElseThrow(); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch( - Math.addExact(version.getVersionStateEpoch(), 1L)); - versions.save(version); - artifactService.markPublished( - versionDto.tenantId(), - versionDto.id(), - exported.stateEpoch(), - workflow, - controlledEmptyManifest.manifestHash()); - var attempts = - new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( - gds.dsl()); - var attempt = - attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow(); - attempt.setStatus( - net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); - attempts.save(attempt); - var operation = selectedOwnerReservation.operation(); - new net.firedevops.firemud.gamedesign.publication - .GameDesignPublicationOperationRepository(gds.dsl()) - .seal( - operation.tenantKey(), - workflow, - operation.versionId(), - operation.selectionDigest(), - true); - return result; - }); - assertThat(written.attestationSchemaVersion()).isEqualTo("v4"); - assertThat(written.participantDigests()).containsExactlyElementsOf(participantDigests); - assertThat(written.worldPublishedStartLocationEvidence().canonicalBytes()) - .containsExactly(worldOwners.startLocationEvidence().canonicalBytes()); - String committedBundleRow = bundleOwnerRow(gds, draft.version()); - var independentRead = - new PublishedReleaseBundleServiceImpl( - new PublishedReleaseBundleRepository(gds.dsl()), - new VersionRepository(gds.dsl()), - new ObjectMapper()) - .findPublishedReleaseBundle(draft.version().getTenantId(), draft.version().getId()) - .orElseThrow(); - assertThat(independentRead).isEqualTo(written); - assertThat(independentRead.attestationSchemaVersion()).isEqualTo("v4"); - assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); - - var replay = - gds.write() - .execute( - ignored -> - releaseOwner.createFullVersionBundle( - versionDto, - publicationRequest.derivedWorkflowIdentity(), - controlledEmptyManifest, - "controlled-generation-input", - participantDigests, - worldOwners.startLocationEvidence())); - assertThat(replay).isEqualTo(written); - assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + worldOwners.startLocationEvidence())); + assertThat(replay).isEqualTo(written); + assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + completeActualWorldAndAccountTerminals( + gds, + world, + accountSources.dsl, + accountSources.manager, + pki, + selectedOwnerReservation.operation(), + diagnostics); + assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + } + } finally { + stop(accountServer); + stop(worldServer); + stop(entityServer); + stop(automationServer); + stop(gameLogicServer); + } + } + } + + /** Actual authenticated Account ordering consumes the real GDS immutable selection owner. */ + private static net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding + authenticatedAccountPublicationOrder( + Store gds, + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + AuthoredDraftPublishSelectionBinding selection, + ProofPki pki) + throws Exception { + var reads = new java.util.concurrent.atomic.AtomicInteger(); + var unavailable = new java.util.concurrent.atomic.AtomicBoolean(true); + var selectionOwner = + new net.firedevops.firemud.gamedesign.draft + .GameDesignSelectedDraftPublicationReadGrpcService( + new AuthoredDraftPublishSelectionRepository( + gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())), + NAMESPACE); + Server gdsServer = + ownerServer(pki, "game-design-service", observedRead(selectionOwner, reads, unavailable)); + Server accountServer = null; + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService(loopback(gdsServer)); + var channels = new GrpcChannelFactory(); + var sources = issued.sources(); + try (var selectionClient = + new net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE)) { + selectionClient.init(); + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var owner = + new AccountSelectedDraftPublicationOrderService( + selectionClient, + new AccountPublicationAuthorizationService( + issued.actors(), sources.fences, repository), + NAMESPACE); + accountServer = + ownerServer( + pki, + "account-service", + new AccountSelectedDraftPublicationOrderGrpcService(owner, sources.terms, NAMESPACE)); + endpoints.setAccountService(loopback(accountServer)); + try (var client = + new net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + client.init(); + var request = + net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec + .Request.create(NAMESPACE, selection, issued.compact()); + var before = publicationOrderRows(sources.dsl); + assertThat(before.get("account_selected_publication_authorizations")).isEmpty(); + assertThat(before.get("account_selected_publication_sources")).isEmpty(); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(RuntimeException.class); + assertThat(publicationOrderRows(sources.dsl)).isEqualTo(before); + assertThat(reads.get()).isEqualTo(1); + unavailable.set(false); + var created = client.authorize(request); + assertThat(created.input().selection().canonicalBytes()) + .containsExactly(selection.canonicalBytes()); + var committed = publicationOrderRows(sources.dsl); + assertThat(committed.get("account_selected_publication_authorizations")).hasSize(1); + assertThat(committed.get("account_selected_publication_sources")).isNotEmpty(); + assertThat(client.authorize(request).canonicalBytes()) + .containsExactly(created.canonicalBytes()); + assertThat(publicationOrderRows(sources.dsl)).isEqualTo(committed); + assertThat(reads.get()).isEqualTo(3); + assertThat( + sources + .dsl + .fetchSingle( + "SELECT count(*) FROM account_control_ui_issuance_operations WHERE status = 'COMMITTED'") + .get(0, Long.class)) + .isEqualTo(1L); + return created; + } + } finally { + stop(accountServer); + stop(gdsServer); + } + } + + private static java.util.Map> publicationOrderRows( + org.jooq.DSLContext dsl) { + var result = new java.util.LinkedHashMap>(); + for (String table : + List.of( + "account_selected_publication_authorizations", + "account_selected_publication_sources", + "account_selected_publication_settlements", + "account_control_ui_issuance_operations")) { + result.put( + table, + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM " + table + " r ORDER BY 1") + .getValues(0, String.class)); + } + return result; + } + + /** Fresh World begin uses real owner reads before any World freeze attempt exists. */ + private static WorldSelectedFullPublicationEvidenceFixture.Result freshAuthenticatedWorldFreeze( + Store gds, + Store world, + org.jooq.DSLContext accountDsl, + org.springframework.transaction.PlatformTransactionManager accountTransactions, + AuthoredDraftPublishSelectionBinding selection, + WorldSelectedFullPublicationEvidenceFixture.AppliedGraph graph, + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding account, + ProofPki pki) + throws Exception { + var selectionCalls = new java.util.concurrent.atomic.AtomicInteger(); + var versionCalls = new java.util.concurrent.atomic.AtomicInteger(); + var heldCalls = new java.util.concurrent.atomic.AtomicInteger(); + var unavailableAccount = new java.util.concurrent.atomic.AtomicBoolean(true); + var unavailableGds = new java.util.concurrent.atomic.AtomicBoolean(); + var sources = + new net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository( + gds.dsl()); + Server gdsServer = + ownerServer( + pki, + "game-design-service", + observedRead( + new net.firedevops.firemud.gamedesign.draft + .GameDesignSelectedDraftPublicationReadGrpcService( + new AuthoredDraftPublishSelectionRepository( + gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())), + NAMESPACE), + selectionCalls, + unavailableGds), + observedRead( + new net.firedevops.firemud.gamedesign.service.impl + .AuthoredWorldVersionStateGrpcService( + new net.firedevops.firemud.gamedesign.service.impl + .AuthoredWorldVersionStateService(gds.transactions(), sources), + NAMESPACE), + versionCalls, + unavailableGds), + new net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceReadGrpcService( + sources, NAMESPACE)); + Server accountServer = null; + Server worldServer = null; + try { + accountServer = + ownerServer( + pki, + "account-service", + observedRead( + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + new AccountPublicationAuthorizationRepository(accountDsl), + accountTransactions, + NAMESPACE), + NAMESPACE), + heldCalls, + unavailableAccount)); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService(loopback(gdsServer)); + endpoints.setAccountService(loopback(accountServer)); + var channels = new GrpcChannelFactory(); + try (var selectionClient = + new net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var versionClient = + new net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var accountClient = + new net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var sourceClient = + new net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + selectionClient.init(); + versionClient.init(); + accountClient.init(); + sourceClient.init(); + var handlers = + WorldSelectedFullPublicationEvidenceFixture.reservationReadEndpoints( + world.dsl(), + world.transactions(), + NAMESPACE, + selectionClient, + versionClient, + accountClient, + sourceClient); + worldServer = + ownerServer( + pki, "world-management-service", handlers.toArray(io.grpc.BindableService[]::new)); + endpoints.setWorldManagementService(loopback(worldServer)); + try (var freeze = + new net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + freeze.init(); + var intent = selection.intent(); + var request = + net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence + .Request.create( + NAMESPACE, + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + selection.digest().substring("sha256:".length()), + account); + var before = freezeOwnerRows(world.dsl()); + for (String empty : + List.of( + "world_design_publication_fence_attempt", + "world_design_publication_account_binding", + "world_selected_publication_artifact_inventory", + "world_canonical_frozen_topology")) { + assertThat(before.get(empty)).as("no prior %s", empty).isEmpty(); + } + assertThat( + world + .dsl() + .fetchSingle( + "SELECT owner_freeze_phase FROM world_design_publication_fence_owner") + .get(0, String.class)) + .isEqualTo("OPEN"); + assertThatThrownBy(() -> freeze.begin(request)).isInstanceOf(RuntimeException.class); + assertThat(freezeOwnerRows(world.dsl())).isEqualTo(before); + assertThat(selectionCalls.get()).isEqualTo(1); + assertThat(versionCalls.get()).isEqualTo(1); + assertThat(heldCalls.get()).isEqualTo(1); + unavailableAccount.set(false); + var created = freeze.begin(request); + assertThat(created.request()).isEqualTo(request); + assertThat(created.acknowledgement().ownerFreezePhase()) + .isEqualTo( + net.firedevops.firemud.common.publication + .WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN); + assertThat(selectionCalls.get()).isEqualTo(2); + assertThat(versionCalls.get()).isEqualTo(2); + assertThat(heldCalls.get()).isEqualTo(2); + var retained = + WorldSelectedFullPublicationEvidenceFixture.readCommittedFreeze( + world.dsl(), NAMESPACE, selection, graph, account, created); + var committed = freezeOwnerRows(world.dsl()); + for (String written : + List.of( + "world_design_publication_fence_attempt", + "world_design_publication_account_binding", + "world_selected_publication_artifact_inventory", + "world_canonical_frozen_topology")) { + assertThat(committed.get(written)).as("one committed %s", written).hasSize(1); + } + unavailableAccount.set(true); + unavailableGds.set(true); + assertThat(freeze.begin(request)).isEqualTo(created); + assertThat(freezeOwnerRows(world.dsl())).isEqualTo(committed); + assertThat(selectionCalls.get()).isEqualTo(2); + assertThat(versionCalls.get()).isEqualTo(2); + assertThat(heldCalls.get()).isEqualTo(2); + return retained; + } + } + } finally { + stop(worldServer); + stop(accountServer); + stop(gdsServer); + } + } + + private static java.util.Map> freezeOwnerRows( + org.jooq.DSLContext dsl) { + var result = new java.util.LinkedHashMap>(); + for (String table : + List.of( + "world_design_publication_fence_owner", + "world_design_publication_fence_attempt", + "world_design_publication_account_binding", + "world_selected_publication_artifact_inventory", + "world_canonical_frozen_topology")) { + result.put( + table, + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM " + table + " r ORDER BY 1") + .getValues(0, String.class)); + } + return result; + } + + private static io.grpc.BindableService observedRead( + io.grpc.BindableService owner, + java.util.concurrent.atomic.AtomicInteger calls, + java.util.concurrent.atomic.AtomicBoolean unavailable) { + return () -> + ServerInterceptors.intercept( + owner, + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata metadata, + io.grpc.ServerCallHandler next) { + calls.incrementAndGet(); + if (unavailable.get()) { + call.close( + io.grpc.Status.UNAVAILABLE.withDescription( + "test-only owner transport outage"), + new io.grpc.Metadata()); + return new io.grpc.ServerCall.Listener<>() {}; + } + return next.startCall(call, metadata); + } + }); + } + + /** + * Actual immutable owner terminals and Account ingress over controlled loopback workload mTLS. + */ + private static void completeActualWorldAndAccountTerminals( + Store gds, + Store world, + org.jooq.DSLContext accountDsl, + org.springframework.transaction.PlatformTransactionManager accountTransactions, + ProofPki pki, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation, + SettlementDiagnostics diagnostics) + throws Exception { + requireAccountClosureInventoryRefusals(accountDsl, operation); + var gdsOwner = + new net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationService( + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationOperationRepository(gds.dsl()), + gds.transactions()); + Server gdsTerminalServer = + ownerServer( + pki, + "game-design-service", + diagnostics.timedGrpc( + "gds-terminal-read", + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationTerminalReadGrpcService(gdsOwner, NAMESPACE))); + Server worldTerminalServer = null; + Server accountSettlementServer = null; + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService(loopback(gdsTerminalServer)); + var channels = new GrpcChannelFactory(); + try (var worldGdsRead = + new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + worldGdsRead.init(); + var worldRepository = + new net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalRepository( + world.dsl(), world.transactions()); + var worldOwner = + net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalService + .authenticated(worldRepository, worldGdsRead, NAMESPACE); + worldTerminalServer = + ownerServer( + pki, + "world-management-service", + new net.firedevops.firemud.worldmanagement.tenant + .WorldPublicationTerminalCompletionGrpcService(worldOwner, NAMESPACE), + diagnostics.timedGrpc( + "world-terminal-read", + new net.firedevops.firemud.worldmanagement.tenant + .WorldPublicationTerminalReadGrpcService( + new net.firedevops.firemud.worldmanagement.tenant + .WorldPublicationTerminalReadService(worldRepository, NAMESPACE), + NAMESPACE))); + endpoints.setWorldManagementService(loopback(worldTerminalServer)); + try (var accountGdsRead = + new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var accountWorldRead = + new net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var producer = + net.firedevops.firemud.gamedesign.publication + .GameDesignWorldPublicationTerminalProducer.usingFileBackedMtls( + gdsOwner, endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + accountGdsRead.init(); + accountWorldRead.init(); + var accountOwner = + new AccountSelectedDraftPublicationSettlementService( + new AccountPublicationAuthorizationRepository(accountDsl), + accountGdsRead, + accountWorldRead, + diagnostics.timeTransactions(accountTransactions), + NAMESPACE); + var binding = + net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding + .fromStored(operation.canonicalBytes()); + accountSettlementServer = + ownerServer( + pki, + "account-service", + diagnostics.timedGrpc( + "account-settlement", + new AccountSelectedPublicationSettlementGrpcService(accountOwner, NAMESPACE))); + endpoints.setAccountService(loopback(accountSettlementServer)); + try (var settlementClient = + new net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + settlementClient.init(); + var settlementRequest = + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()); + try (var wrongCaller = + new net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + wrongCaller.init(); + assertThatThrownBy(() -> wrongCaller.settle(settlementRequest)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + } + diagnostics.phase( + "account-settlement-before-world-terminal", + () -> { + assertThatThrownBy( + () -> + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + return null; + }); + assertThat( + accountDsl + .fetchSingle( + "SELECT count(*) FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, Long.class)) + .isZero(); + var published = + diagnostics.phase( + "world-producer-reconcile", + () -> + producer.reconcile( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)); + assertThat(published.operationBytes()).containsExactly(operation.canonicalBytes()); + assertThat( + diagnostics.phase( + "world-producer-exact-retry", + () -> + producer + .reconcile( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + published.outcome()) + .canonicalBytes())) + .containsExactly(published.canonicalBytes()); + byte[] receipt = + diagnostics.phase( + "account-settlement-positive", + () -> + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()))); + assertThat(receipt).isNotEmpty(); + String retained = + accountDsl + .fetchSingle( + "SELECT to_jsonb(s)::text || ':' || xmin::text FROM account_selected_publication_settlements s WHERE operation_id = ?", + binding.account().operationId()) + .get(0, String.class); + assertThat( + diagnostics.phase( + "account-settlement-exact-retry", + () -> + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes())))) + .containsExactly(receipt); + assertThat( + accountDsl + .fetchSingle( + "SELECT to_jsonb(s)::text || ':' || xmin::text FROM account_selected_publication_settlements s WHERE operation_id = ?", + binding.account().operationId()) + .get(0, String.class)) + .isEqualTo(retained); + assertThat( + accountDsl + .fetchSingle( + "SELECT game_design_terminal FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, byte[].class)) + .containsExactly(published.canonicalBytes()); + assertThat( + accountDsl + .fetchSingle( + "SELECT world_terminal FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, byte[].class)) + .containsExactly(published.canonicalBytes()); + } } } finally { - stop(entityServer); - stop(automationServer); - stop(gameLogicServer); + stop(accountSettlementServer); + stop(worldTerminalServer); + stop(gdsTerminalServer); + } + } + + private static void requireAccountClosureInventoryRefusals( + org.jooq.DSLContext dsl, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation) + throws Exception { + dsl.fetch( + "SELECT require_selected_inventory_operation_v2(?::bytea)", operation.canonicalBytes()); + var mapper = new ObjectMapper(); + java.util.List> changes = + java.util.List.of( + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("sourceModel")) + .remove("inboundSourceClosure"), + tree -> + ((tools.jackson.databind.node.ObjectNode) + tree.at("/sourceModel/inboundSourceClosure/familyCounts/0")) + .put("count", 1), + tree -> + ((tools.jackson.databind.node.ArrayNode) + tree.at("/sourceModel/inboundSourceClosure/familyCounts")) + .remove(6), + tree -> { + var families = + (tools.jackson.databind.node.ArrayNode) + tree.at("/sourceModel/inboundSourceClosure/familyCounts"); + families.add(families.remove(0)); + }, + tree -> + ((tools.jackson.databind.node.ObjectNode) + tree.at("/sourceModel/inboundSourceClosure")) + .put("unknown", 1), + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("sourceModel")) + .put("unknown", 1), + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("sourceModel")) + .put("graphSchemaVersion", 2), + tree -> tree.put("schemaVersion", 1), + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("checkpoint")) + .put("digestSchemaVersion", 3)); + var before = + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM account_selected_publication_authorizations r ORDER BY 1") + .getValues(0, String.class); + for (var change : changes) { + var tree = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(operation.inventory().canonicalBytes()); + change.accept(tree); + byte[] inventory = mapper.writeValueAsBytes(tree); + var raw = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, + net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding.SCHEMA); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, operation.account().canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, operation.world().canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame(raw, inventory); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, + "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(inventory))); + assertThatThrownBy( + () -> + dsl.fetch( + "SELECT require_selected_inventory_operation_v2(?::bytea)", + raw.toByteArray())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .satisfies( + failure -> { + var cause = failure; + while (cause != null && !(cause instanceof java.sql.SQLException)) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(java.sql.SQLException.class); + assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("23514"); + }); } + assertThat( + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM account_selected_publication_authorizations r ORDER BY 1") + .getValues(0, String.class)) + .isEqualTo(before); } private static Draft createDraft(Store gds) { @@ -1008,17 +1774,6 @@ private static void completeGameDesignCommit( }); } - private static AccountPublicationAuthorizationBinding controlledAccountBinding( - AuthoredDraftPublishSelectionBinding selection) { - UUID actor = UUID.randomUUID(); - var input = new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection); - return new AccountPublicationAuthorizationBinding( - UUID.randomUUID(), - UUID.randomUUID(), - input, - controlledAccountSources(actor, selection.intent().canonicalTenantId())); - } - private static SelectedOwnerIntakeAuthorizationBinding selectedOwnerAuthorization( Store gds, AuthoredDraftPublishSelection selection, Owner recipient, UUID actor) { var scope = @@ -1115,18 +1870,281 @@ private static String loopback(Server server) { return "127.0.0.1:" + server.getPort(); } - private static Server ownerServer(ProofPki pki, String service, io.grpc.BindableService handler) - throws Exception { + private static final class SettlementDiagnostics { + private final AtomicLong sequence = new AtomicLong(); + private final long diagnosticOriginNanos = System.nanoTime(); + + void logPostgres(String role, PostgreSQLContainer postgres) { + try { + System.out.printf( + "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s elapsed_since_diagnostic_start_nanos=%d container=%s host=%s mapped_port=%d running=%s%n", + role, + System.nanoTime() - diagnosticOriginNanos, + postgres.getContainerId(), + postgres.getHost(), + postgres.getMappedPort(5432), + postgres.isRunning()); + } catch (RuntimeException unavailable) { + System.out.printf( + "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s elapsed_since_diagnostic_start_nanos=%d status=unavailable error=%s%n", + role, + System.nanoTime() - diagnosticOriginNanos, + unavailable.getClass().getSimpleName()); + } + } + + T phase(String stage, Supplier action) { + long call = sequence.incrementAndGet(); + long started = System.nanoTime(); + event(call, stage, "start", 0L, "none"); + try { + T result = action.get(); + event(call, stage, "complete", System.nanoTime() - started, "OK"); + return result; + } catch (RuntimeException | Error failure) { + event( + call, stage, "failed", System.nanoTime() - started, failure.getClass().getSimpleName()); + throw failure; + } + } + + io.grpc.BindableService timedGrpc(String stage, io.grpc.BindableService owner) { + return () -> + ServerInterceptors.intercept( + owner, + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + long callSequence = sequence.incrementAndGet(); + long started = System.nanoTime(); + String method = call.getMethodDescriptor().getFullMethodName(); + var recorded = new java.util.concurrent.atomic.AtomicBoolean(); + var timedCall = + new io.grpc.ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(ResponseT message) { + long sendStarted = System.nanoTime(); + String serializedSize = serializedSize(message); + event( + callSequence, + stage + "/" + method, + "send-message-before", + sendStarted - started, + serializedSize); + try { + super.sendMessage(message); + long sendFinished = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "send-message-after", + sendFinished - started, + serializedSize + + ",delegate_elapsed_nanos=" + + (sendFinished - sendStarted)); + } catch (RuntimeException | Error failure) { + long sendFailed = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "send-message-failed", + sendFailed - started, + serializedSize + + ",delegate_elapsed_nanos=" + + (sendFailed - sendStarted) + + ",failure=" + + failure.getClass().getSimpleName()); + throw failure; + } + } + + @Override + public void close(io.grpc.Status status, io.grpc.Metadata trailers) { + if (recorded.compareAndSet(false, true)) { + event( + callSequence, + stage + "/" + method, + "closed", + System.nanoTime() - started, + status.getCode().name()); + } + super.close(status, trailers); + } + }; + event(callSequence, stage + "/" + method, "start", 0L, "STARTED"); + var listener = next.startCall(timedCall, headers); + return new io.grpc.ForwardingServerCallListener + .SimpleForwardingServerCallListener<>(listener) { + @Override + public void onMessage(RequestT message) { + event( + callSequence, + stage + "/" + method, + "request-message", + System.nanoTime() - started, + serializedSize(message)); + super.onMessage(message); + } + + @Override + public void onHalfClose() { + long handlerStarted = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "handler-enter", + handlerStarted - started, + "ENTERED"); + try { + super.onHalfClose(); + long handlerFinished = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "handler-return", + handlerFinished - started, + "handler_elapsed_nanos=" + (handlerFinished - handlerStarted)); + } catch (RuntimeException | Error failure) { + long handlerFailed = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "handler-failed", + handlerFailed - started, + "handler_elapsed_nanos=" + + (handlerFailed - handlerStarted) + + ",failure=" + + failure.getClass().getSimpleName()); + throw failure; + } + } + + @Override + public void onCancel() { + if (recorded.compareAndSet(false, true)) { + event( + callSequence, + stage + "/" + method, + "cancelled", + System.nanoTime() - started, + "CANCELLED"); + } + super.onCancel(); + } + }; + } + }); + } + + PlatformTransactionManager timeTransactions(PlatformTransactionManager delegate) { + return new PlatformTransactionManager() { + private final Map active = new IdentityHashMap<>(); + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + long call = sequence.incrementAndGet(); + long started = System.nanoTime(); + event(call, "account-transaction", "acquire-start", 0L, "STARTED"); + try { + TransactionStatus status = delegate.getTransaction(definition); + synchronized (active) { + active.put(status, new TransactionTiming(call, started)); + } + event(call, "account-transaction", "acquired", System.nanoTime() - started, "OK"); + return status; + } catch (RuntimeException | Error failure) { + event( + call, + "account-transaction", + "acquire-failed", + System.nanoTime() - started, + failure.getClass().getSimpleName()); + throw failure; + } + } + + @Override + public void commit(TransactionStatus status) { + finish(status, true); + } + + @Override + public void rollback(TransactionStatus status) { + finish(status, false); + } + + private void finish(TransactionStatus status, boolean commit) { + TransactionTiming timing; + synchronized (active) { + timing = active.remove(status); + } + long completionStarted = System.nanoTime(); + try { + if (commit) { + delegate.commit(status); + } else { + delegate.rollback(status); + } + if (timing != null) { + event( + timing.sequence(), + "account-transaction", + commit ? "committed" : "rolled-back", + System.nanoTime() - timing.startedNanos(), + "completion_ns=" + (System.nanoTime() - completionStarted)); + } + } catch (RuntimeException | Error failure) { + if (timing != null) { + event( + timing.sequence(), + "account-transaction", + commit ? "commit-failed" : "rollback-failed", + System.nanoTime() - timing.startedNanos(), + failure.getClass().getSimpleName()); + } + throw failure; + } + } + }; + } + + private String serializedSize(Object message) { + if (message instanceof com.google.protobuf.MessageLite protobufMessage) { + try { + return "serialized_size_bytes=" + protobufMessage.getSerializedSize(); + } catch (RuntimeException unavailable) { + return "serialized_size_bytes=unavailable"; + } + } + return "serialized_size_bytes=unavailable"; + } + + private void event(long call, String stage, String event, long elapsedNanos, String result) { + long elapsedSinceDiagnosticStartNanos = System.nanoTime() - diagnosticOriginNanos; + System.out.printf( + "SETTLEMENT_DIAGNOSTIC call=%d stage=%s event=%s elapsed_nanos=%d elapsed_since_diagnostic_start_nanos=%d result=%s%n", + call, stage, event, elapsedNanos, elapsedSinceDiagnosticStartNanos, result); + } + + private record TransactionTiming(long sequence, long startedNanos) {} + } + + private static Server ownerServer( + ProofPki pki, String service, io.grpc.BindableService... handlers) throws Exception { var identity = pki.server(service); - return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) - .trustManager(pki.ca().toFile()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())) - .build() - .start(); + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + for (var handler : handlers) + builder.addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())); + return builder.build().start(); } private static void stop(Server server) throws InterruptedException { @@ -1278,6 +2296,8 @@ private static final class ProofPki { for (String service : List.of( "game-design-service", + "account-service", + "world-management-service", "entity-management-service", "automation-scripting-service", "game-logic-service")) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 5db106da16..43aedd6b50 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -442,6 +442,302 @@ void repositoryNestedTransactionRollsBackWithOuterJooqOwnerTransaction() { assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); } + @Test + void selectedFullV4StorageRejectsMixedProfilesAndExactlyReplaysOriginalBytes() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selected-v4-profile-source"); + Version version = saveVersion(fixture, owner); + var operation = selectedFullOperation(fixture, version); + var json = new tools.jackson.databind.ObjectMapper(); + var participants = + net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures.participants( + version.getId(), operation.world(), 4); + String original = + new String(operation.world().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + var gameBefore = sourceRow(fixture.dsl(), "game", owner.getId()); + var versionBefore = sourceRow(fixture.dsl(), "version", version.getId()); + for (int index = 0; index < participants.size(); index++) { + var mixed = + (tools.jackson.databind.node.ArrayNode) + json.readTree(json.writeValueAsString(participants)); + var participant = participants.get(index); + ((tools.jackson.databind.node.ObjectNode) mixed.get(index)) + .put( + "digestSchemaVersion", + participant.digestSchemaVersion() == 1 ? 2 : participant.digestSchemaVersion() - 1); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, version, operation, original, json.writeValueAsString(mixed))) + .as("mixed storage profile for %s", participant.participantKey()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("selected participant differs from commit/digest/schema"); + assertThat(bundleCount(fixture.dsl())).isZero(); + assertThat(sourceRow(fixture.dsl(), "game", owner.getId())).isEqualTo(gameBefore); + assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); + } + var requested = selectedFullBundle(version, operation.world()); + var saved = + fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> fixture.releaseBundleRepository().save(requested))); + assertThat(saved).isNotNull(); + var tuple = releaseBundleTuple(fixture.dsl(), saved.getId()); + var independent = + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(independent).usingRecursiveComparison().isEqualTo(saved); + assertThat(independent.getWorldPublishedStartLocationEvidenceJson()).isEqualTo(original); + assertThat(independent.getParticipantDigestsJson()) + .isEqualTo(json.writeValueAsString(participants)); + assertThat(fixture.releaseBundleRepository().save(requested)) + .usingRecursiveComparison() + .isEqualTo(saved); + var changed = selectedFullBundle(version, operation.world()); + changed.setGenerationConfigRevision("changed-selected-generation"); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(releaseBundleTuple(fixture.dsl(), saved.getId())).isEqualTo(tuple); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + + @Test + void concurrentExactSelectedFullRetriesCommitOneImmutableBundle() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selected-full-concurrent-source"); + Version version = saveVersion(fixture, owner); + var operation = selectedFullOperation(fixture, version); + var start = new java.util.concurrent.CountDownLatch(1); + try (var executor = java.util.concurrent.Executors.newFixedThreadPool(2)) { + java.util.concurrent.Callable save = + () -> { + start.await(); + return fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> + new PublishedReleaseBundleRepository(fixture.dsl()) + .save(selectedFullBundle(version, operation.world())))); + }; + var first = executor.submit(save); + var second = executor.submit(save); + start.countDown(); + var one = first.get(20, java.util.concurrent.TimeUnit.SECONDS); + var two = second.get(20, java.util.concurrent.TimeUnit.SECONDS); + assertThat(two).usingRecursiveComparison().isEqualTo(one); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + var beforeRetry = releaseBundleTuple(fixture.dsl(), one.getId()); + assertThat( + fixture + .releaseBundleRepository() + .save(selectedFullBundle(version, operation.world()))) + .usingRecursiveComparison() + .isEqualTo(one); + assertThat(releaseBundleTuple(fixture.dsl(), one.getId())).isEqualTo(beforeRetry); + } + } + + @Test + void sqlGuardRejectsMissingAndChangedSelectedFullBindingsWithoutAnyRelease() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selected-full-guard-source"); + Version version = saveVersion(fixture, owner); + var operation = selectedFullOperation(fixture, version); + var json = new tools.jackson.databind.ObjectMapper(); + String original = + new String(operation.world().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + String participants = + json.writeValueAsString( + net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures + .participants(version.getId(), operation.world(), 4)); + var gameBefore = sourceRow(fixture.dsl(), "game", owner.getId()); + var versionBefore = sourceRow(fixture.dsl(), "version", version.getId()); + assertThat(json.readTree(original).path("request").path("versionStateEpoch").isTextual()) + .isTrue(); + assertThatThrownBy(() -> insertRawSelectedFull(fixture, version, operation, null, participants)) + .isInstanceOf(DataAccessException.class); + for (String epoch : java.util.List.of("0", "01", "-1", "9223372036854775808")) { + var changed = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("versionStateEpoch", epoch); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, version, operation, json.writeValueAsString(changed), participants)) + .isInstanceOf(DataAccessException.class); + } + var numericEpoch = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + ((tools.jackson.databind.node.ObjectNode) numericEpoch.get("request")) + .put("versionStateEpoch", 1L); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, + version, + operation, + json.writeValueAsString(numericEpoch), + participants)) + .isInstanceOf(DataAccessException.class); + for (String field : + java.util.List.of( + "canonicalTenantId", + "canonicalVersionId", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "intakeRequestId")) { + var changed = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + var request = (tools.jackson.databind.node.ObjectNode) changed.get("request"); + if (field.equals("digestSchemaVersion")) request.put(field, 3); + else request.put(field, field.endsWith("Id") ? UUID.randomUUID().toString() : "changed"); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, version, operation, json.writeValueAsString(changed), participants)) + .isInstanceOf(DataAccessException.class); + } + for (String field : + java.util.List.of( + "selectorReceiptBytesBase64", + "originalAccountBindingBytesBase64", + "appliedResultBytesBase64")) { + var changed = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + changed.remove(field); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, version, operation, json.writeValueAsString(changed), participants)) + .isInstanceOf(DataAccessException.class); + } + assertThatThrownBy(() -> insertRawSelectedFull(fixture, version, operation, original, "[]")) + .isInstanceOf(DataAccessException.class); + var changedParticipants = (tools.jackson.databind.node.ArrayNode) json.readTree(participants); + ((tools.jackson.databind.node.ObjectNode) changedParticipants.get(0)) + .put("contentDigest", "c".repeat(64)); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, + version, + operation, + original, + json.writeValueAsString(changedParticipants))) + .isInstanceOf(DataAccessException.class); + assertThat(bundleCount(fixture.dsl())).isZero(); + assertThat(sourceRow(fixture.dsl(), "game", owner.getId())).isEqualTo(gameBefore); + assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); + fixture + .transactionTemplate() + .executeWithoutResult( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> { + insertRawSelectedFull(fixture, version, operation, original, participants); + return fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow(); + })); + assertThat( + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow() + .getWorldPublishedStartLocationEvidenceJson()) + .isEqualTo(original); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + + /** Actual GDS owner selection/captures with explicitly stipulated remote Account/World input. */ + private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation + selectedFullOperation(Fixture fixture, Version version) { + var target = + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + return fixture + .transactionTemplate() + .execute( + status -> { + try { + return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .retainFrozenSourceBackedSelectedFull( + fixture.dsl(), + target, + version.getVersionStateEpoch(), + "ISOLATED selected-full storage regression", + java.util.List.of()); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + + private PublishedReleaseBundle selectedFullBundle( + Version version, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence evidence) { + var candidate = bundle(version.getTenantId(), version.getId()); + candidate.setAttestationSchemaVersion("v4"); + candidate.setPublishWorkflowId(evidence.request().publishWorkflowId()); + candidate.setParticipantDigestsJson( + new tools.jackson.databind.ObjectMapper() + .writeValueAsString( + net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures + .participants(version.getId(), evidence, 4))); + candidate.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8)); + return candidate; + } + + private void insertRawSelectedFull( + Fixture fixture, + Version version, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation, + String evidence, + String participants) { + fixture + .dsl() + .execute( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, " + + "canonical_tenant_id, canonical_version_id, published_release_bundle_ref, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, generation_config_revision, manifest_schema_version, artifact_digests_json, " + + "required_manifest_asset_keys_json, participant_digests_json, command_definitions_json, script_only, " + + "world_published_start_location_evidence_json) VALUES (?, ?, 1, ?, ?, ?, 'v4', ?, ?, ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", + version.getTenantId(), + version.getId(), + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + UUID.randomUUID().toString(), + operation.workflowId(), + MANIFEST_HASH, + GENERATION_CONFIG_REVISION, + participants, + evidence); + } + private Fixture fixture(MigrationVersion target) { String schema = "game_design_release_identity_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java new file mode 100644 index 0000000000..4f54642590 --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java @@ -0,0 +1,101 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import org.junit.jupiter.api.Test; + +class AssetSnapshotTest { + @Test + void exactTypedSnapshotRoundTripsAndOwnsItsImmutableCollection() { + var binding = binding(); + var reference = AssetSource.replay(List.of(), binding).references().getFirst(); + var item = + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[] {1, 2}), 2); + var mutable = new ArrayList<>(List.of(item)); + var snapshot = new AssetSnapshot(binding, "1", null, UUID.randomUUID(), mutable); + mutable.clear(); + assertThat(AssetSnapshot.fromStored(snapshot.canonicalJson())).isEqualTo(snapshot); + assertThat(snapshot.items()).containsExactly(item); + assertThatThrownBy(() -> snapshot.items().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(snapshot.items().getFirst().reference().family()).isEqualTo("ORDINARY"); + assertThat(snapshot.items().getFirst().reference().role()).isEqualTo("RESOURCE"); + assertThat(new AssetApplication(binding, "0", snapshot).appliedEpoch().resultingEpoch()) + .isEqualTo("1"); + assertThatThrownBy(() -> new AssetApplication(binding, "1", snapshot)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void storedSnapshotCannotChangeBoundRequirednessIdentityOrCanonicalRepresentation() { + var binding = binding(); + var reference = AssetSource.replay(List.of(), binding).references().getFirst(); + var snapshot = + new AssetSnapshot( + binding, + "1", + null, + UUID.randomUUID(), + List.of( + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[0]), 0))); + String json = snapshot.canonicalJson(); + for (String invalid : + List.of( + json.replace("\"requiredness\":\"REQUIRED\"", "\"requiredness\":\"OPTIONAL\""), + json.replace("\"family\":\"ORDINARY\"", "\"family\":\"UNKNOWN\""), + json.replace("\"role\":\"RESOURCE\"", "\"role\":\"PRESENTATION\""), + " " + json)) { + assertThatThrownBy(() -> AssetSnapshot.fromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "", CommandSource.sha256(new byte[0]), 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", "sha256:00", 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[0]), -1)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DraftCommitBinding binding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "tenant", 2, "tenant", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.upsertPayload("3", "logo.png", AssetSource.Requiredness.REQUIRED))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + target.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + "0"))); + } +} diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRetentionTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRetentionTest.java new file mode 100644 index 0000000000..7a614e30f7 --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRetentionTest.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.Test; + +class RealmPolicySourceRetentionTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID GENESIS_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + + @Test + void schema3ActorCoreAndOriginalPolicyProvenanceSurviveOwnerApplication() { + String policyJson = + "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PLAYER_CREATED\"," + + "\"creationDescriptor\":{\"schemaVersion\":1,\"descriptorId\":\"11111111-1111-4111-8111-111111111111\"," + + "\"descriptorRevisionId\":\"22222222-2222-4222-8222-222222222222\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}"; + String payload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmEntryPolicy.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r3", + "policy", + RealmPolicySource.tree(policyJson))); + DraftCommitBinding binding = + DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-commit-0", + List.of( + new RevisionPayload("0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION_ID.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + var policy = RealmPolicySource.revision(binding, binding.revisions().getFirst()); + var snapshot = new RealmPolicySnapshot(binding, "1", List.of(policy)); + var application = new RealmPolicyApplication(freshGenesis(), null, "0", snapshot); + var retained = RealmPolicySnapshot.fromStored(application.snapshot().canonicalJson()); + var retainedPolicy = retained.policies().getFirst(); + + assertThat(retainedPolicy.commitId()).isEqualTo(COMMIT_ID); + assertThat(retainedPolicy.revisionId()).isEqualTo(REVISION_ID); + assertThat(retainedPolicy.logicalRevisionId()).isEqualTo("policy-logical-r3"); + assertThat(retainedPolicy.policy().initialActorCore().displayName()).isEqualTo("Wayfarer"); + assertThat(retainedPolicy.policy().initialActorCore().dispositionKey()).isEqualTo("newcomer"); + assertThat(application.canonicalBytes()).containsSequence(retained.canonicalBytes()); + } + + @Test + void missingBothGenesisAndInheritedCommitAndInvalidRequiredTextAreRejected() { + RealmPolicySnapshot snapshot = snapshot(); + + assertThatThrownBy(() -> new RealmPolicyApplication(null, null, "0", snapshot)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new RealmPolicyApplication(freshGenesis(), null, "invalid", snapshot())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void knownSiblingSourceKindsAreNonPolicyAndUnknownKindsStillDeny() { + assertThat(RealmPolicySource.isPolicyRevision(revision(BrandingSource.REVISION_KIND))) + .isFalse(); + assertThat(RealmPolicySource.isPolicyRevision(revision(TemplateConfigSource.REVISION_KIND))) + .isFalse(); + assertThatThrownBy(() -> RealmPolicySource.isPolicyRevision(revision("UNKNOWN_SOURCE"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported Game Design owner revision kind"); + } + + private static RealmPolicyGenesis freshGenesis() { + return new RealmPolicyGenesis(target(), GENESIS_ID, "17"); + } + + private static RealmPolicySnapshot snapshot() { + DraftCommitBinding binding = + DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-commit-0", + List.of(new RevisionPayload("0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION_ID.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + return new RealmPolicySnapshot(binding, "1", List.of()); + } + + private static TargetProof target() { + return new TargetProof( + TENANT_ID, VERSION_ID, 23L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + } + + private static RevisionPayload revision(String kind) { + return new RevisionPayload( + "0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, "{\"revisionKind\":\"" + kind + "\"}"); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java new file mode 100644 index 0000000000..8dc7c51ca7 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java @@ -0,0 +1,412 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Ability; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Action; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActionCategory; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActionTag; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActorRole; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.AdmissionTag; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CandidateSelector; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CapacityChangePolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cardinality; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Command; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CommitPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Condition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ContinuousOverlay; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cooldown; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cost; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.DefaultBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Definition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.DurationPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Effect; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.EffectBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.EffectOperation; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ExecutionDiscipline; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Lifecycle; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ObservationPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Predicate; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PredicateKind; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PrimitiveKind; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PromptPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Reapplication; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ReplayPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Resource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.SelectionPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.SelectionStrategy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stage; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stat; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.StatField; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetSet; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetingPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import org.junit.jupiter.api.Test; + +class GameplayRuleSourceTest { + private static final TargetProof TARGET = + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + "private-owner-key", + 1L, + "private-owner-key", + "NEW_GAME_ROW"); + + @Test + void realNonemptyCatalogRetainsOrderedDeclarationsAndEveryOriginalRevision() { + var manifest = exampleManifest(); + var binding = + binding( + manifest.families().values().stream() + .flatMap(List::stream) + .map(GameplayRuleSource::upsertPayload) + .toList()); + var entries = GameplayRuleSource.replay(List.of(), binding); + var snapshot = new GameplayRuleSnapshot(binding, "1", null, UUID.randomUUID(), entries); + var read = GameplayRuleSnapshot.fromStored(snapshot.canonicalJson()); + + assertThat(read.canonicalBytes()).containsExactly(snapshot.canonicalBytes()); + assertThat(read.manifest().canonicalBytes()).containsExactly(manifest.canonicalBytes()); + assertThat(read.entries()).hasSize(entries.size()); + assertThat(read.entries()) + .allSatisfy(entry -> assertThat(entry.sourceBinding()).isEqualTo(binding)); + var action = (Action) read.manifest().families().get(Family.ACTIONS).getFirst(); + assertThat(action.admissionTags()).containsExactly("gameplay", "canFocus"); + assertThat(action.effects()) + .extracting(EffectBinding::effectKey) + .containsExactly("restore", "cleanse"); + var command = (Command) read.manifest().families().get(Family.COMMANDS).getFirst(); + assertThat(command.actionTags()).containsExactly(ActionTag.COMBAT); + assertThat(command.admissionTags()).containsExactly("gameplay", "canFocus"); + } + + @Test + void inheritedCatalogPreservesUnchangedProvenanceAndExplicitDelete() { + var initial = + binding( + List.of( + GameplayRuleSource.upsertPayload(new AdmissionTag("first")), + GameplayRuleSource.upsertPayload(new AdmissionTag("second")))); + var original = GameplayRuleSource.replay(List.of(), initial); + var changed = + binding( + List.of( + GameplayRuleSource.deletePayload(Family.ADMISSION_TAGS, "first"), + GameplayRuleSource.upsertPayload(new AdmissionTag("third")))); + var replayed = GameplayRuleSource.replay(original, changed); + assertThat(replayed) + .extracting(entry -> entry.definition().key()) + .containsExactly("second", "third"); + assertThat(replayed.getFirst().sourceBinding()).isEqualTo(initial); + assertThat(replayed.getLast().sourceBinding()).isEqualTo(changed); + assertThatThrownBy( + () -> + GameplayRuleSource.replay( + replayed, + binding( + List.of( + GameplayRuleSource.deletePayload(Family.ADMISSION_TAGS, "missing"))))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void authoredDispositionAndRequiredFeedbackRetainTypedSelectedRevisionProvenance() { + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor.created", + Audience.SOURCE_ACTOR, + "actor.created", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + ReplayPolicy.EFFECT_IDEMPOTENT); + var selected = + binding( + List.of( + GameplayRuleSource.upsertPayload(disposition), + GameplayRuleSource.upsertPayload(feedback))); + var entries = GameplayRuleSource.replay(List.of(), selected); + var manifest = GameplayRuleSource.manifest(entries); + + assertThat(manifest.families().keySet()).containsExactlyInAnyOrder(Family.values()); + for (Family family : Family.values()) { + if (family != Family.DISPOSITIONS && family != Family.FEEDBACK) { + assertThat(manifest.families().get(family)).isEmpty(); + } + } + assertThat(manifest.families().get(Family.DISPOSITIONS)).containsExactly(disposition); + assertThat(manifest.families().get(Family.FEEDBACK)).containsExactly(feedback); + assertThat(entries).extracting(GameplayRuleSource.Entry::sourceBinding).containsOnly(selected); + assertThat(entries) + .extracting(GameplayRuleSource.Entry::revisionOrder) + .containsExactly("0", "1"); + } + + @Test + void incompleteInventoryAndUnresolvedReferencesDenyInsteadOfBecomingEmpty() { + var families = + new EnumMap>(GameplayRuleManifest.explicitEmpty().families()); + families.remove(Family.FEEDBACK); + assertThatThrownBy(() -> new GameplayRuleManifest(families)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleSource.replay( + List.of(), + binding( + List.of( + GameplayRuleSource.upsertPayload( + new Ability("ability", "Ability", "missingAction")))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unresolved ACTIONS"); + assertThatThrownBy( + () -> + GameplayRuleManifest.fromStored( + "{\"schema\":\"gameplay-rule-manifest/v1\",\"families\":{}}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void unknownDefinitionFieldsDuplicateFieldsAndMissingAdmissionTagsDeny() { + String command = + GameplayRuleManifest.canonical( + exampleManifest().families().get(Family.COMMANDS).getFirst()); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.COMMANDS, + command.replace("\"admissionTags\":[\"gameplay\",\"canFocus\"],", ""))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.ADMISSION_TAGS, "{\"tagKey\":\"tag\",\"unknownPolicy\":true}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.ADMISSION_TAGS, "{\"tagKey\":\"first\",\"tagKey\":\"second\"}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition(Family.ADMISSION_TAGS, "{\"tagKey\":\"first\"} {}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleSource.mutations( + binding(List.of("{\"revisionKind\":\"UNKNOWN_RULE_FAMILY\"}")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void continuousEffectsCannotBecomeInstantActionEffectsOrGrantDeniedAdmission() { + var source = exampleManifest(); + var families = new EnumMap>(source.families()); + Action action = (Action) families.get(Family.ACTIONS).getFirst(); + families.put( + Family.ACTIONS, + List.of( + new Action( + action.key(), + action.name(), + action.admissionTags(), + action.targetSets(), + action.costs(), + action.cooldowns(), + List.of(new EffectBinding("capacity", "SOURCE")), + action.feedbackKeys()))); + assertThatThrownBy(() -> new GameplayRuleManifest(families)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.CONTINUOUS_OVERLAYS, + GameplayRuleManifest.canonical( + Map.of( + "overlayKey", + "overlay", + "eligibleWhen", + truth(), + "deniedAdmissionTags", + List.of(), + "effectKeys", + List.of(), + "grantedAdmissionTags", + List.of("gameplay"))))) + .isInstanceOf(IllegalArgumentException.class); + } + + static GameplayRuleManifest exampleManifest() { + List definitions = + List.of( + new Stat( + "focus", + PrimitiveKind.NUMERIC, + BigDecimal.ONE, + null, + BigDecimal.ZERO, + BigDecimal.TEN, + Visibility.PUBLIC, + List.of()), + new Resource( + "energy", + BigDecimal.TEN, + BigDecimal.ZERO, + BigDecimal.TEN, + BigDecimal.valueOf(100), + Visibility.PUBLIC, + List.of()), + new Condition( + "weary", + Reapplication.REFRESH, + DurationPolicy.RESET, + 5L, + null, + Visibility.PUBLIC, + List.of(), + List.of(), + 0), + new Effect( + "restore", + Lifecycle.INSTANT, + EffectOperation.ADJUST_RESOURCE, + "energy", + null, + BigDecimal.ONE, + null, + null), + new Effect( + "cleanse", + Lifecycle.INSTANT, + EffectOperation.REMOVE_CONDITION, + null, + null, + null, + "weary", + null), + new Effect( + "capacity", + Lifecycle.CONTINUOUS, + EffectOperation.ADD, + "energy", + StatField.MAXIMUM, + BigDecimal.ONE, + null, + CapacityChangePolicy.CLAMP_ONLY), + new AdmissionTag("gameplay"), + new AdmissionTag("canFocus"), + new Feedback( + "unavailable", + "ACTION_REJECTED", + Audience.SOURCE_ACTOR, + "action.unavailable", + "Unavailable.", + List.of(), + Visibility.PRIVATE, + ReplayPolicy.EFFECT_IDEMPOTENT), + new Disposition("ready", List.of(), "unavailable"), + new ContinuousOverlay( + "wearyOverlay", + new Predicate( + PredicateKind.CONDITION_PRESENT, + ActorRole.SOURCE, + "weary", + null, + null, + List.of()), + List.of("canFocus"), + List.of("capacity")), + new ObservationPolicy("observable", truth()), + new TargetingPolicy( + "self", CandidateSelector.SELF, "observable", truth(), "unavailable"), + new SelectionPolicy( + "one", + Cardinality.EXACTLY_ONE, + null, + null, + SelectionStrategy.CANONICAL_ORDER, + null, + List.of()), + new DefaultBinding( + "focusDefault", List.of(new TargetSet("subject", "self", "one", true, null, null))), + new Action( + "focusAction", + "Focus", + List.of("gameplay", "canFocus"), + List.of(new TargetSet("subject", "self", "one", true, null, null)), + List.of(new Cost("energy", BigDecimal.ONE, CommitPolicy.ON_EXECUTION)), + List.of(new Cooldown("focusCooldown", 3L, CommitPolicy.ON_EFFECT_SUCCESS)), + List.of( + new EffectBinding("restore", "subject"), + new EffectBinding("cleanse", "SOURCE")), + List.of("unavailable")), + new Ability("focusAbility", "Focus ability", "focusAction"), + new Command( + "focusCommand", + "focusAction", + "GAME_LOGIC", + ExecutionDiscipline.DURABLE_GAMEPLAY, + Stage.GAMEPLAY, + PromptPolicy.WHEN_GAMEPLAY, + ActionCategory.GAMEPLAY, + true, + List.of("focus"), + List.of(ActionTag.COMBAT), + List.of("gameplay", "canFocus"))); + Map> families = new EnumMap<>(Family.class); + for (Family family : Family.values()) families.put(family, new ArrayList<>()); + for (Definition definition : definitions) families.get(definition.family()).add(definition); + return new GameplayRuleManifest(families); + } + + private static Predicate truth() { + return new Predicate(PredicateKind.TRUE, null, null, null, null, List.of()); + } + + private static DraftCommitBinding binding(List payloads) { + List revisions = new ArrayList<>(); + for (int i = 0; i < payloads.size(); i++) + revisions.add( + new RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads.get(i))); + return DraftCommitBinding.create( + TARGET, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + TARGET.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java new file mode 100644 index 0000000000..f23215b237 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java @@ -0,0 +1,675 @@ +package net.firedevops.firemud.gamedesign.publication; + +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.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.inOrder; +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 io.grpc.Status; +import java.util.Arrays; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unit proof for the admission ordering and exact preflight checks; clients are transport doubles. + */ +class SelectedDraftPublicationAdmissionServiceTest { + private static final String NAMESPACE = "test"; + + @Test + void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = freezeClient(fixture); + var inventory = inventoryClient(fixture); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var sourceFixture = sourceFixture(fixture.worldRequest()); + when(sourceIntake.readById(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return sourceReceipt(invocation.getArgument(0), sourceFixture); + }); + when(sourceRepository.read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(sourceFixture.source())); + when(deliveryRepository.read(sourceFixture.source().operationId())) + .thenReturn( + Optional.of( + new GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim( + sourceFixture.source(), sourceFixture.intakeRequest(), Optional.empty()))); + var owner = mock(SelectedDraftPublicationOwner.class); + var reader = mock(SelectedDraftPublicationAdmissionService.SelectionReader.class); + var transactions = mock(PlatformTransactionManager.class); + var retained = + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest()); + when(reader.read(fixture.intent())).thenReturn(Optional.of(retained)); + when(account.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + when(world.read(fixture.worldRequest())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return fixture.operation().world(); + }); + var reservation = mock(SelectedDraftPublicationOwner.Reservation.class); + // Request.binding() reconstructs the exact Account bytes; its nested selection does not use + // value equality. Match the complete canonical binding rather than decoded object identity. + when(owner.reserve( + eq(fixture.intent()), + argThat( + binding -> + Arrays.equals( + binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), + same(fixture.operation().world()), + same(fixture.operation().inventory()), + any())) + .thenReturn(reservation); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + reader, + NAMESPACE); + + assertThat(service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(reservation); + var order = + inOrder( + reader, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + transactions, + owner); + order.verify(reader).read(fixture.intent()); + order.verify(account).read(any()); + order.verify(freeze).begin(any()); + order.verify(inventory).read(any()); + order.verify(world).read(fixture.worldRequest()); + order + .verify(sourceIntake) + .readById( + argThat( + request -> + request.schemaVersion() == 1 + && request.targetNamespace().equals(NAMESPACE) + && request + .intakeRequestId() + .equals(fixture.worldRequest().intakeRequestId()) + && request + .canonicalTenantId() + .equals(fixture.worldRequest().canonicalTenantId()) + && !request.readRequestId().equals(request.intakeRequestId()))); + order + .verify(sourceRepository) + .read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE); + order.verify(deliveryRepository).read(sourceFixture.source().operationId()); + order.verify(transactions).getTransaction(any()); + order + .verify(owner) + .reserve( + eq(fixture.intent()), + argThat( + binding -> + Arrays.equals( + binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), + same(fixture.operation().world()), + same(fixture.operation().inventory()), + any()); + } + + @Test + void missingRetainedSelectionNeverReadsAccountFreezesWorldOrOpensSql() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> Optional.empty(), + NAMESPACE); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SELECTION_UNAVAILABLE"); + verifyNoInteractions( + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + transactions); + } + + @Test + void mismatchedRetainedDeliveryAcknowledgementDeniesBeforeReservation() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var sourceFixture = sourceFixture(fixture.worldRequest()); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + when(sourceIntake.readById(any())) + .thenAnswer(invocation -> sourceReceipt(invocation.getArgument(0), sourceFixture)); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + when(sourceRepository.read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(sourceFixture.source())); + var receipt = + sourceReceipt( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + NAMESPACE, + UUID.randomUUID(), + fixture.worldRequest().intakeRequestId(), + fixture.worldRequest().canonicalTenantId()), + sourceFixture); + var wrongAcknowledgement = + new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + "sha256:" + "b".repeat(64)); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + when(deliveryRepository.read(sourceFixture.source().operationId())) + .thenReturn( + Optional.of( + new GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim( + sourceFixture.source(), + sourceFixture.intakeRequest(), + Optional.of(wrongAcknowledgement)))); + var world = mock(WorldPublishedStartLocationClient.class); + when(world.read(fixture.worldRequest())).thenReturn(fixture.operation().world()); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freezeClient(fixture), + inventoryClient(fixture), + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest())), + NAMESPACE); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("OWNER_READBACK_CONFLICT"); + verifyNoInteractions(transactions, owner); + } + + @Test + void freezeFailureNeverReadsSelectorOrReserves() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var selection = fixture.operation().account().input().selection(); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + selection.canonicalJson(), selection.digest())), + NAMESPACE); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var failure = Status.UNAVAILABLE.asRuntimeException(); + when(freeze.begin(any())).thenThrow(failure); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(failure); + verifyNoInteractions(inventory, world, owner, transactions); + } + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void missingInventoryAfterAcknowledgedFreezeNeverReadsSelectorOrOpensSql() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var selection = fixture.operation().account().input().selection(); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freezeClient(fixture), + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + selection.canonicalJson(), selection.digest())), + NAMESPACE); + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("inventory readback"); + verify(inventory).read(any()); + verifyNoInteractions( + world, sourceIntake, sourceRepository, deliveryRepository, owner, transactions); + } + + @Test + void rejectsAmbientSqlTransactionBeforeEitherOwnerRead() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void rejectsAmbientSynchronizationBeforeEitherOwnerRead() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void rejectsChangedIntentBeforeOwnerReads() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + var original = fixture.intent(); + var changedIntent = + new AuthoredDraftPublishSelection.PublishIntent( + original.canonicalTenantId(), + original.canonicalVersionId(), + original.publishRequestId(), + original.expectedVersionStateEpoch(), + "changed notes", + original.selectedCommitRequestId(), + original.selectedCommitId(), + original.selectedCommitDigest()); + + assertThatThrownBy(() -> service.admitAndReserve(changedIntent, fixture.operation().account())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected Draft intent"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void accountDenialOrUnavailableReadNeverReadsWorldOrReserves() throws Exception { + for (Status.Code code : + new Status.Code[] {Status.Code.PERMISSION_DENIED, Status.Code.UNAVAILABLE}) { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var service = service(fixture, accountClient, worldClient, owner); + var failure = Status.fromCode(code).asRuntimeException(); + when(accountClient.read(any())).thenThrow(failure); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(failure); + + verify(accountClient).read(any()); + verifyNoInteractions(worldClient, owner); + } + } + + @Test + void worldUnavailableAfterAccountReadNeverOpensReservation() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var service = service(fixture, accountClient, worldClient, owner); + + // The client is a transport double here; the mock evidence is never accepted as proof because + // the World read fails before the reservation boundary. + when(accountClient.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var failure = Status.UNAVAILABLE.asRuntimeException(); + when(worldClient.read(fixture.worldRequest())).thenThrow(failure); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(failure); + + verify(accountClient).read(any()); + verify(worldClient).read(fixture.worldRequest()); + verifyNoInteractions(owner); + } + + private static SelectedDraftPublicationAdmissionService service( + Fixture fixture, + AccountPublicationAuthorizationReadClient accountClient, + WorldPublishedStartLocationClient worldClient, + SelectedDraftPublicationOwner owner) { + return new SelectedDraftPublicationAdmissionService( + mock(PlatformTransactionManager.class), + accountClient, + freezeClient(fixture), + inventoryClient(fixture), + worldClient, + mock(WorldAuthoredSourceIntakeClient.class), + mock(GameAuthoredWorldSourceRepository.class), + mock(GameAuthoredWorldSourceDeliveryRepository.class), + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest())), + NAMESPACE); + } + + private static WorldSelectedPublicationArtifactInventoryClient inventoryClient(Fixture fixture) { + var client = mock(WorldSelectedPublicationArtifactInventoryClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return fixture.operation().inventory(); + }); + return client; + } + + private static WorldSelectedDraftPublicationFreezeClient freezeClient(Fixture fixture) { + var client = mock(WorldSelectedDraftPublicationFreezeClient.class); + when(client.begin(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + WorldSelectedDraftPublicationFreezeEvidence.Request request = + invocation.getArgument(0); + var world = fixture.worldRequest(); + var acknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + request, + world.intakeRequestId(), + world.versionStateEpoch(), + world.publicationFence(), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + world.appliedCommitId(), + world.contentDigest(), + world.digestSchemaVersion()); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + }); + return client; + } + + private static SourceFixture sourceFixture(WorldPublishedStartLocationEvidence.Request selected) { + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "fixture-tenant"; + String worldSlug = "fixture-world"; + String worldDisplayName = "Fixture World"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + selected.targetNamespace(), + registrationRequestId, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + var source = + new AuthoredWorldSourceEvidence( + 1, + selected.targetNamespace(), + registrationRequestId, + sourceOperationId, + requestDigest, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + "tenant-key", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + selected.targetNamespace(), + registrationRequestId, + sourceOperationId, + requestDigest, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + "tenant-key", + "NEW_GAME_ROW")); + var intakeRequest = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + selected.targetNamespace(), + selected.intakeRequestId(), + selected.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + return new SourceFixture(source, intakeRequest); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt sourceReceipt( + WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest request, SourceFixture fixture) { + var source = fixture.source(); + return new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + request.targetNamespace(), + request.intakeRequestId(), + UUID.nameUUIDFromBytes( + "synthetic-world-operation".getBytes(java.nio.charset.StandardCharsets.UTF_8)), + request.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(fixture.intakeRequest()), + "sha256:" + "a".repeat(64), + source); + } + + private static Fixture fixture() throws Exception { + var target = + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + var original = IsolatedPublicationOperationFixtures.fresh(target); + var selectionIntent = original.account().input().selection().intent(); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + selectionIntent.canonicalTenantId(), + selectionIntent.canonicalVersionId(), + selectionIntent.publishRequestId(), + selectionIntent.expectedVersionStateEpoch(), + selectionIntent.notes(), + selectionIntent.selectedCommitRequestId(), + selectionIntent.selectedCommitId(), + selectionIntent.selectedCommitDigest()); + return new Fixture(original, intent, original.world().request()); + } + + private record Fixture( + GameDesignPublicationOperation operation, + AuthoredDraftPublishSelection.PublishIntent intent, + WorldPublishedStartLocationEvidence.Request worldRequest) {} + + private record SourceFixture( + AuthoredWorldSourceEvidence source, + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest intakeRequest) {} +} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index c057e8810e..cb143e2d1a 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -151,6 +151,8 @@ import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -238,9 +240,11 @@ class WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest { @TempDir Path temporary; - @Test - void actualOwnersPrepareAndReplayOneExactOriginalOperation() throws Exception { - compose(Refusal.NONE); + @ParameterizedTest + @ValueSource(longs = {9_007_199_254_740_992L, 9_007_199_254_740_993L, Long.MAX_VALUE}) + void actualOwnersPrepareAndReplayOneExactOriginalOperation( + long reservationClaimFence, @TempDir Path proofDirectory) throws Exception { + compose(Refusal.NONE, reservationClaimFence, proofDirectory); } @Test @@ -320,10 +324,24 @@ private enum ActivationFailure { } private void compose(Refusal refusal) throws Exception { - compose(refusal, ActivationFailure.NONE); + compose(refusal, 9_007_199_254_740_993L, temporary, ActivationFailure.NONE); + } + + private void compose(Refusal refusal, long reservationClaimFence, Path proofDirectory) + throws Exception { + compose(refusal, reservationClaimFence, proofDirectory, ActivationFailure.NONE); } private void compose(Refusal refusal, ActivationFailure activationFailure) throws Exception { + compose(refusal, 9_007_199_254_740_993L, temporary, activationFailure); + } + + private void compose( + Refusal refusal, + long reservationClaimFence, + Path proofDirectory, + ActivationFailure activationFailure) + throws Exception { UUID tenant = UUID.randomUUID(); try (var account = new AccountControlUiOriginalOrderFixture( @@ -332,13 +350,13 @@ private void compose(Refusal refusal, ActivationFailure activationFailure) throw ACCOUNT.getPassword(), REDIS.getHost(), REDIS.getMappedPort(6379), - temporary.resolve("account"), + proofDirectory.resolve("account"), tenant); var world = database(WORLD, "world-management-service", true); var gs = database(GS, "game-session-service", false)) { var issuer = new AccountOriginalStartSessionAuthorizationProofFixture( - account, temporary.resolve("issuer"), NAMESPACE); + account, proofDirectory.resolve("issuer"), NAMESPACE); Duration lease = refusal == Refusal.EXPIRED_ATTEMPT ? Duration.ofSeconds(30) : Duration.ofMinutes(5); var attempts = new GameSessionStartSessionOperatorAttemptRepository(gs.dsl(), lease); @@ -354,7 +372,6 @@ private void compose(Refusal refusal, ActivationFailure activationFailure) throw new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), "TEST_ONLY owner composition"); String requestId = "controlled-original-prepare-" + UUID.randomUUID(); - long reservationClaimFence = 9_007_199_254_740_993L; var original = issuer.issueAndRedeemOriginal( requestId, @@ -434,7 +451,7 @@ public void attachAccountRedemptionProjection( claim.get().ownerMutationId(), input.gameSessionOwnerAttemptId(), claim.get().ownerFence()); - var pki = new WorldOriginalStartSessionPreparationProofPki(temporary.resolve("pki")); + var pki = new WorldOriginalStartSessionPreparationProofPki(proofDirectory.resolve("pki")); var factory = new GrpcChannelFactory(); var currentAttemptRefusal = new AtomicReference(); var currentAttemptReceiver = @@ -482,6 +499,8 @@ public void close(Status status, Metadata trailers) { currentAttempt.init(); launchAssociation.init(); if (refusal == Refusal.NONE) { + var beforeAuthenticatedRead = + rows(gs.dsl(), "game_session_start_session_operator_attempt"); var authenticatedCurrent = currentAttempt.read( new net.firedevops.firemud.common.gamesession @@ -494,8 +513,12 @@ public void close(Status status, Metadata trailers) { claim.get().ownerFence())); assertThat(authenticatedCurrent.request().originalTuple().reservationClaimFence()) .isEqualTo(reservationClaimFence); + assertThat(authenticatedCurrent.request().canonicalPostAuthorizationTuple()) + .containsExactly(tuple.canonicalBytes()); assertThat(authenticatedCurrent.accountRedemptionProjection()) .containsExactly(tuple.canonicalBytes()); + assertThat(rows(gs.dsl(), "game_session_start_session_operator_attempt")) + .isEqualTo(beforeAuthenticatedRead); } int accountPort = availablePort(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java index f1c0360f13..e41f3a32f2 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java @@ -3,7 +3,6 @@ import java.util.List; import java.util.Objects; import java.util.UUID; -import java.util.function.Function; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -13,7 +12,6 @@ import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; @@ -109,26 +107,19 @@ public DraftCommitBinding selectedCommit() { } } - /** - * Applies and freezes the exact already-retained GDS selection in current World owners. - * - *

The supplied selection is read from GDS's synchronized Version/commit owner before this - * method is called. The callback supplies only controlled upstream Account authorization bytes; - * its selected binding must be byte-for-byte that retained selection. - */ - public static Result applyFreezeAndCapture( + /** Independently reads actual owner rows after the authenticated World begin has committed. */ + public static Result readCommittedFreeze( DSLContext worldDsl, - PlatformTransactionManager worldTransactions, String namespace, AuthoredDraftPublishSelectionBinding selection, AppliedGraph worldGraph, - Function - controlledAccountBindingFactory) { + AccountPublicationAuthorizationBinding accountBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { Objects.requireNonNull(worldDsl, "worldDsl"); - Objects.requireNonNull(worldTransactions, "worldTransactions"); Objects.requireNonNull(selection, "selection"); Objects.requireNonNull(worldGraph, "worldGraph"); - Objects.requireNonNull(controlledAccountBindingFactory, "controlledAccountBindingFactory"); + Objects.requireNonNull(accountBinding, "accountBinding"); + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); var target = selection.target(); DraftCommitBinding binding = selection.selectedCommit(); @@ -154,9 +145,6 @@ public static Result applyFreezeAndCapture( var applied = worldGraph.applied(); requireExactAppliedReadback(applications, topology, application, plan, applied); - AccountPublicationAuthorizationBinding accountBinding = - Objects.requireNonNull( - controlledAccountBindingFactory.apply(selection), "controlled Account binding"); if (!selection.equals(accountBinding.input().selection())) { throw new IllegalArgumentException( "Controlled Account binding does not retain the exact GDS synchronized selection"); @@ -189,45 +177,7 @@ public static Result applyFreezeAndCapture( var authorizationRepository = new WorldSelectedDraftPublicationAuthorizationRepository(worldDsl); var inventoryRepository = new WorldSelectedPublicationArtifactInventoryRepository(worldDsl); - var checkpointRepository = - new WorldSelectedDraftPublicationCheckpointRepository( - fence, applications, topology, digestService); - var capturedCheckpoint = - new java.util.concurrent.atomic.AtomicReference< - WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint>(); - var createdCheckpointInTransaction = new java.util.concurrent.atomic.AtomicBoolean(); - var freezeTransaction = new TransactionTemplate(worldTransactions); - freezeTransaction.setIsolationLevel( - org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); - var frozenAttempt = - Objects.requireNonNull( - freezeTransaction.execute( - status -> { - createdCheckpointInTransaction.set(false); - var attempt = - fence.claimFreeze( - freeze, - () -> { - var captured = checkpointRepository.captureWithSource(freeze, plan); - capturedCheckpoint.set(captured); - createdCheckpointInTransaction.set(true); - return captured.checkpoint(); - }); - var retainedAccount = - authorizationRepository.retainOrRequireExact( - attempt, accountBinding, createdCheckpointInTransaction.get()); - if (!java.util.Arrays.equals( - retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) { - throw new IllegalStateException( - "World did not retain the exact original Account publication binding"); - } - inventoryRepository.retainOrRequireExact( - attempt, - retainedAccount, - createdCheckpointInTransaction.get(), - capturedCheckpoint.get()); - return attempt; - })); + var frozenAttempt = fence.readAttempt(freeze).orElseThrow(); var retainedAccount = authorizationRepository.readCommitted(frozenAttempt).orElseThrow(); if (!java.util.Arrays.equals( @@ -253,10 +203,11 @@ public static Result applyFreezeAndCapture( frozenAttempt.checkpoint().appliedCommitId(), frozenAttempt.checkpoint().contentDigest(), frozenAttempt.checkpoint().digestSchemaVersion()); - var freezeEvidence = - WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( - freezeRequest, - WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + if (!freezeRequest.equals(freezeEvidence.request()) + || !acknowledgement.equals(freezeEvidence.acknowledgement())) { + throw new IllegalStateException( + "Authenticated begin differs from independent committed World rows"); + } var inventoryEvidence = new WorldSelectedPublicationArtifactInventoryReadService( namespace, fence, authorizationRepository, inventoryRepository) @@ -266,13 +217,7 @@ public static Result applyFreezeAndCapture( var frozenRepository = new WorldCanonicalFrozenTopologyRepository( worldDsl, new WorldAuthoredGraphSnapshotRepository(worldDsl), topology, digestService); - var captured = - new WorldCanonicalFrozenTopologyService(frozenRepository, worldTransactions) - .capture(new WorldCanonicalFrozenTopology.Request(plan, captureRequest)); - var committedCapture = frozenRepository.readCommitted(captureRequest).orElseThrow(); - if (!java.util.Arrays.equals(committedCapture.graphBytes(), captured.graphBytes())) { - throw new IllegalStateException("Committed World frozen-graph readback changed bytes"); - } + var captured = frozenRepository.readCommitted(captureRequest).orElseThrow(); var publishedSource = new WorldPublishedStartLocationRepository(worldDsl, frozenRepository, applications) .readCommitted(captureRequest) @@ -280,8 +225,8 @@ public static Result applyFreezeAndCapture( var worldEvidence = publishedStartLocationEvidence(publishedSource); var worldDigest = new WorldDraftDesignDigestService.WorldDraftDesignDigest( - Long.toString(capturedCheckpoint.get().owner().localTenantKey()), - Long.toString(capturedCheckpoint.get().owner().localVersionKey()), + Long.toString(worldGraph.sourceIntake().localTenantKey()), + Long.toString(worldGraph.versionIdentity().localVersionKey()), frozenAttempt.checkpoint().appliedCommitId(), frozenAttempt.checkpoint().contentDigest(), frozenAttempt.checkpoint().digestSchemaVersion()); @@ -335,6 +280,24 @@ public static AppliedGraph applyGraph( String namespace, DraftCommitBinding selectedCommit, AuthoredWorldSourceEvidence controlledWorldSource) { + return applyGraph( + worldDsl, + worldTransactions, + namespace, + selectedCommit, + controlledWorldSource, + UUID.randomUUID()); + } + + /** Uses the existing GDS outbox's original World intake identity in composed proof. */ + public static AppliedGraph applyGraph( + DSLContext worldDsl, + PlatformTransactionManager worldTransactions, + String namespace, + DraftCommitBinding selectedCommit, + AuthoredWorldSourceEvidence controlledWorldSource, + UUID originalIntakeRequestId) { + Objects.requireNonNull(originalIntakeRequestId, "originalIntakeRequestId"); Objects.requireNonNull(worldDsl, "worldDsl"); Objects.requireNonNull(worldTransactions, "worldTransactions"); Objects.requireNonNull(selectedCommit, "selectedCommit"); @@ -350,7 +313,7 @@ public static AppliedGraph applyGraph( write.execute( status -> intakeRepository.acceptFresh( - namespace, UUID.randomUUID(), controlledWorldSource))); + namespace, originalIntakeRequestId, controlledWorldSource))); var versionStateRequest = new AuthoredWorldVersionStateEvidence.Request( 1, @@ -569,4 +532,54 @@ private static WorldPublishedStartLocationEvidence publishedStartLocationEvidenc source.appliedResult().application().operation().accountBindingBytes(), source.appliedResult().canonicalBytes()); } + + /** Explicit test-only composition of existing readers; no runtime registration or authority. */ + public static java.util.List reservationReadEndpoints( + DSLContext dsl, + PlatformTransactionManager transactions, + String namespace, + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient + selectionClient, + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient versionClient, + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient + accountClient, + net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient sourceClient) { + var intake = new WorldAuthoredSourceIntakeRepository(dsl); + var fence = new WorldDesignPublicationFenceRepository(dsl, intake); + var topology = new WorldDraftTopologyCommitRepository(dsl, fence, JSON); + var applications = new WorldDraftGraphApplicationRepository(dsl, fence, JSON); + var digest = digestService(dsl); + var authorization = new WorldSelectedDraftPublicationAuthorizationRepository(dsl); + var inventory = new WorldSelectedPublicationArtifactInventoryRepository(dsl); + var frozen = + new WorldCanonicalFrozenTopologyRepository( + dsl, new WorldAuthoredGraphSnapshotRepository(dsl), topology, digest); + var service = + new WorldSelectedDraftPublicationFreezeService( + namespace, + selectionClient, + versionClient, + accountClient, + intake, + fence, + new WorldSelectedDraftPublicationCheckpointRepository( + fence, applications, topology, digest), + authorization, + inventory, + applications, + new WorldSelectedPublicationSelectorCapture( + namespace, new WorldCanonicalFrozenTopologyService(frozen, transactions)), + transactions); + return java.util.List.of( + new WorldSelectedDraftPublicationFreezeGrpcService( + service, + new WorldSelectedPublicationArtifactInventoryReadService( + namespace, fence, authorization, inventory), + namespace), + new WorldPublishedStartLocationReadGrpcService( + new WorldPublishedStartLocationRepository(dsl, frozen, applications), namespace), + new WorldAuthoredSourceIntakeGrpcService( + new WorldAuthoredSourceIntakeService(sourceClient, intake, transactions, namespace), + namespace)); + } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java index 9689dbbce2..f6082e5461 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java @@ -1,27 +1,23 @@ package net.firedevops.firemud.worldmanagement.tenant; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; 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.util.UUID; -import java.util.function.Function; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; -import org.springframework.transaction.PlatformTransactionManager; class WorldSelectedFullPublicationEvidenceFixtureTest { @Test - void rejectsVersionWithDifferentSourceIntakeOperationBeforeSqlOrAccountCallback() { + void rejectsVersionWithDifferentSourceIntakeOperationBeforeSqlOrAccountEvidenceRead() { UUID tenant = UUID.fromString("11111111-1111-4111-8111-111111111111"); UUID versionId = UUID.fromString("22222222-2222-4222-8222-222222222222"); UUID intakeOperationId = UUID.fromString("33333333-3333-4333-8333-333333333333"); @@ -45,10 +41,8 @@ void rejectsVersionWithDifferentSourceIntakeOperationBeforeSqlOrAccountCallback( var version = mock(WorldAuthoredVersionIdentityReceipt.class); var graph = mock(WorldSelectedFullPublicationEvidenceFixture.AppliedGraph.class); var worldDsl = mock(DSLContext.class); - var transactions = mock(PlatformTransactionManager.class); - @SuppressWarnings("unchecked") - Function - accountBindingFactory = mock(Function.class); + var accountBinding = mock(AccountPublicationAuthorizationBinding.class); + var freezeEvidence = mock(WorldSelectedDraftPublicationFreezeEvidence.class); when(selection.target()).thenReturn(target); when(selection.intent()).thenReturn(intent); @@ -67,12 +61,11 @@ void rejectsVersionWithDifferentSourceIntakeOperationBeforeSqlOrAccountCallback( assertThatThrownBy( () -> - WorldSelectedFullPublicationEvidenceFixture.applyFreezeAndCapture( - worldDsl, transactions, "test", selection, graph, accountBindingFactory)) + WorldSelectedFullPublicationEvidenceFixture.readCommittedFreeze( + worldDsl, "test", selection, graph, accountBinding, freezeEvidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("World retained source/Version rows differ"); - verifyNoInteractions(worldDsl, transactions); - verify(accountBindingFactory, never()).apply(any()); + verifyNoInteractions(worldDsl, accountBinding, freezeEvidence); } } From c1700b5a8f0aa2e1eaeb1bfe9f9ea05b7c69df06 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 02:51:57 +1300 Subject: [PATCH 50/61] style: order combined selected-owner client imports --- .../sourceintake/SelectedOwnerIntakeClientLifecycleTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java index c9ea0b0b86..05e70d8051 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java @@ -25,8 +25,8 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; import net.firedevops.firemud.common.entity.sourceintake.GrpcEntitySelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; From dc3abab7c07539eeb2d50a009f37e058d6c73822 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 05:17:42 +1300 Subject: [PATCH 51/61] Fix Game Session image JAR selection --- services/game-session-service/Dockerfile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/Dockerfile b/services/game-session-service/Dockerfile index c1b20e68bf..fec569e1ef 100644 --- a/services/game-session-service/Dockerfile +++ b/services/game-session-service/Dockerfile @@ -3,8 +3,12 @@ FROM ${BASE_IMAGE} USER root WORKDIR /app COPY --chmod=644 *.jar /app/ +# Gradle emits proof-only JARs alongside the executable Spring Boot JAR. RUN set -e; \ - jar="$(find /app -maxdepth 1 -type f -name 'game-session-service-*.jar' ! -name '*-plain.jar' ! -name '*-test-fixtures.jar' | head -n 1)"; \ + candidates="$(find /app -maxdepth 1 -type f -name 'game-session-service-*.jar' ! -name '*-plain.jar' ! -name '*-test-fixtures.jar' ! -name '*-classes-proof.jar')"; \ + test -n "${candidates}"; \ + test "$(printf '%s\n' "${candidates}" | wc -l)" -eq 1; \ + jar="${candidates}"; \ test -n "${jar}"; \ mv "${jar}" /app/app.jar; \ find /app -maxdepth 1 -type f -name '*.jar' ! -name 'app.jar' -delete; \ From 274f3ef3418fc57ff1bc6cdad796f95e90bdd4fa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 06:21:22 +1300 Subject: [PATCH 52/61] Address selected-publication CLI findings --- ...ectedDraftPublicationOrderGrpcService.java | 3 + ...inalDraftOrderPostgresIntegrationTest.java | 9 +- ...horizationMtlsPostgresIntegrationTest.java | 40 ++--- ...ctedDraftPublicationOrderGrpcMtlsTest.java | 46 ++---- ...dDraftPublicationOrderGrpcServiceTest.java | 18 +++ ...ldParticipationSettlementGrpcMtlsTest.java | 141 +----------------- ...ccountStartSessionReservationProofPki.java | 5 +- ...AccountSelectedPublicationOrderClient.java | 32 +--- ...ntSelectedPublicationSettlementClient.java | 46 +----- ...nerPublicationPostgresIntegrationTest.java | 3 + 10 files changed, 78 insertions(+), 265 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java index 3e26220f58..4c928b56d9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java @@ -126,6 +126,9 @@ public void authorizeSelectedPublication( } catch (StatusRuntimeException failure) { deny(observer, Status.fromCode(failure.getStatus().getCode())); return; + } catch (IllegalArgumentException conflict) { + deny(observer, Status.FAILED_PRECONDITION); + return; } catch (RuntimeException unavailable) { deny(observer, Status.UNAVAILABLE); return; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java index 437d5cb329..1f22e95936 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java @@ -91,7 +91,7 @@ class AccountOriginalDraftOrderPostgresIntegrationTest { @ValueSource(booleans = {true, false}) void originalCreatorExpiryAtFinalOwnerLockDeniesCurrentCallback( boolean signedCredential, @TempDir Path proofDirectory) throws Exception { - assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( + assertOriginalCreatorTimeAtFinalOwnerLock( signedCredential, proofDirectory, Duration.ofMinutes(10)); } @@ -99,7 +99,7 @@ void originalCreatorExpiryAtFinalOwnerLockDeniesCurrentCallback( @ValueSource(booleans = {true, false}) void originalCreatorNotBeforeAtFinalOwnerLockDeniesCurrentCallback( boolean signedCredential, @TempDir Path proofDirectory) throws Exception { - assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( + assertOriginalCreatorTimeAtFinalOwnerLock( signedCredential, proofDirectory, Duration.ofMinutes(-10)); } @@ -107,11 +107,10 @@ void originalCreatorNotBeforeAtFinalOwnerLockDeniesCurrentCallback( @ValueSource(booleans = {true, false}) void originalCreatorIssuedAtEqualityAtFinalOwnerLockAllowsCurrentCallback( boolean signedCredential, @TempDir Path proofDirectory) throws Exception { - assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( - signedCredential, proofDirectory, Duration.ZERO); + assertOriginalCreatorTimeAtFinalOwnerLock(signedCredential, proofDirectory, Duration.ZERO); } - private void assertOriginalCreatorTimeAtFinalOwnerLockDeniesCurrentCallback( + private void assertOriginalCreatorTimeAtFinalOwnerLock( boolean signedCredential, Path proofDirectory, Duration clockChange) throws Exception { var clock = new ActorClock(); try (var fixture = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java index 3bd11eb575..aa2431ccfd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -15,7 +15,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyStore; -import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.UUID; @@ -23,6 +22,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; @@ -894,7 +894,8 @@ private static final class TestPki { TestPki(Path root) throws Exception { Path caStore = root.resolve("ca.p12"); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + root, "-genkeypair", "-alias", "test-ca", @@ -919,7 +920,8 @@ private static final class TestPki { "-keypass", PASSWORD); ca = root.resolve("ca.crt"); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + root, "-exportcert", "-alias", "test-ca", @@ -970,7 +972,8 @@ private static TestIdentity issue( + workload + ",DNS:localhost,IP:127.0.0.1"; String eku = server ? "serverAuth" : "clientAuth"; - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + root, "-genkeypair", "-alias", alias, @@ -996,7 +999,8 @@ private static TestIdentity issue( PASSWORD, "-keypass", PASSWORD); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + root, "-certreq", "-alias", alias, @@ -1010,7 +1014,8 @@ private static TestIdentity issue( request.toString(), "-ext", "SAN=" + san); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + root, "-gencert", "-alias", "test-ca", @@ -1055,28 +1060,5 @@ private static TestIdentity issue( java.util.Arrays.fill(privateKey, (byte) 0); return new TestIdentity(certificate, key); } - - private static void runKeytool(String... arguments) throws Exception { - Path keytool = - Path.of( - System.getProperty("java.home"), - "bin", - System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") - ? "keytool.exe" - : "keytool"); - var command = new ArrayList(); - command.add(keytool.toString()); - command.addAll(List.of(arguments)); - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); - if (!process.waitFor(30, TimeUnit.SECONDS)) { - process.destroyForcibly(); - throw new IllegalStateException("Ephemeral test certificate generation timed out"); - } - try (var output = process.getInputStream()) { - String details = new String(output.readAllBytes(), StandardCharsets.UTF_8); - if (process.exitValue() != 0) - throw new IllegalStateException("Test keytool failed: " + details); - } - } } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java index ed43b1f7a7..5c6c1d9957 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java @@ -22,7 +22,6 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import java.io.IOException; import java.net.InetSocketAddress; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyStore; @@ -30,7 +29,6 @@ import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.time.OffsetDateTime; -import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.UUID; @@ -40,6 +38,7 @@ import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationOrderGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationOrderService; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -355,7 +354,8 @@ private record TestPki( private static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("selected-publication-test-ca.p12"); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + directory, "-genkeypair", "-alias", "test-ca", @@ -380,7 +380,8 @@ private static TestPki create(Path directory) throws Exception { "-keypass", STORE_PASSWORD); Path caFile = directory.resolve("selected-publication-test-ca.crt"); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + directory, "-exportcert", "-alias", "test-ca", @@ -440,7 +441,8 @@ private static TestIdentity issueIdentity( Path request = directory.resolve(alias + ".csr"); Path certificate = directory.resolve(alias + ".crt"); String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + directory, "-genkeypair", "-alias", alias, @@ -466,7 +468,8 @@ private static TestIdentity issueIdentity( STORE_PASSWORD, "-keypass", STORE_PASSWORD); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + directory, "-certreq", "-alias", alias, @@ -480,7 +483,8 @@ private static TestIdentity issueIdentity( request.toString(), "-ext", "SAN=" + san); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + directory, "-gencert", "-alias", "test-ca", @@ -505,7 +509,8 @@ private static TestIdentity issueIdentity( "EKU=" + (server ? "serverAuth" : "clientAuth"), "-ext", "SAN=" + san); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + directory, "-importcert", "-alias", "test-ca", @@ -518,7 +523,8 @@ private static TestIdentity issueIdentity( "-file", caFile.toString(), "-noprompt"); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( + directory, "-importcert", "-alias", alias, @@ -541,28 +547,6 @@ private static TestIdentity issueIdentity( (X509Certificate) keyStore.getCertificate(alias)); } - private static void runKeytool(String... arguments) throws Exception { - Path keytool = - Path.of( - System.getProperty("java.home"), - "bin", - System.getProperty("os.name").toLowerCase().contains("windows") - ? "keytool.exe" - : "keytool"); - ArrayList command = new ArrayList<>(); - command.add(keytool.toString()); - command.addAll(List.of(arguments)); - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); - String output; - try (var stream = process.getInputStream()) { - output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } - if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { - process.destroyForcibly(); - throw new IllegalStateException("keytool failed: " + output); - } - } - private static X509Certificate readCertificate(Path path) throws Exception { try (var input = Files.newInputStream(path)) { return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java index 53a1c94d72..2521aa49f1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java @@ -182,6 +182,24 @@ void unavailableCaptureReturnsSanitizedFailure() { verifyNoInteractions(owner); } + @Test + void immutableOwnerConflictIsPermanentWhilePendingSourceChangeRemainsRetryable() { + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenThrow(new IllegalArgumentException(CREDENTIAL)) + .thenThrow(new IllegalStateException(CREDENTIAL)); + var conflict = authorized(() -> invoke(request())); + assertThat(conflict.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(conflict.error().toString()).doesNotContain(CREDENTIAL); + assertThat(conflict.error().getCause()).isNull(); + + var waiting = authorized(() -> invoke(request())); + assertThat(waiting.code()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(waiting.error().toString()).doesNotContain(CREDENTIAL); + assertThat(waiting.error().getCause()).isNull(); + } + @Test void secretBearingOwnerStatusReturnsOnlyItsCodeAndSanitizedDescription() { var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java index 9b2d8c5a80..49ed04378a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java @@ -29,7 +29,6 @@ import java.security.PrivateKey; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; -import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; @@ -40,6 +39,7 @@ import net.firedevops.firemud.account.v1.SettleOriginalStartSessionWorldParticipationRequest; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationSettlementGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationSettlementService; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationSettlementInput; import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionWorldParticipationSettlementClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -50,7 +50,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -79,70 +78,6 @@ void clearThreadState() { TransactionSynchronizationManager.clear(); } - @Test - @Timeout(15) - void keytoolTimeoutTerminatesAndReapsTheStalledChild() throws Exception { - Process process = keytoolAwaitingPassword(); - try { - assertThatThrownBy(() -> TestPki.awaitKeytoolExit(process, 1, TimeUnit.SECONDS)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("execution deadline"); - assertThat(process.isAlive()).isFalse(); - assertThat(process.exitValue()).isNotZero(); - } finally { - cleanupKeytool(process); - } - } - - @Test - @Timeout(15) - void keytoolInterruptionReapsTheChildAndPreservesTheInterruptFlag() throws Exception { - Process process = keytoolAwaitingPassword(); - try { - Thread.currentThread().interrupt(); - assertThatThrownBy(() -> TestPki.awaitKeytoolExit(process, 30, TimeUnit.SECONDS)) - .isInstanceOf(InterruptedException.class); - assertThat(Thread.currentThread().isInterrupted()).isTrue(); - Thread.interrupted(); - assertThat(process.isAlive()).isFalse(); - assertThat(process.exitValue()).isNotZero(); - } finally { - Thread.interrupted(); - cleanupKeytool(process); - } - } - - private Process keytoolAwaitingPassword() throws Exception { - Path keytool = - Path.of( - System.getProperty("java.home"), - "bin", - System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") - ? "keytool.exe" - : "keytool"); - return new ProcessBuilder( - keytool.toString(), - "-genkeypair", - "-alias", - "controlled-timeout", - "-keyalg", - "RSA", - "-keystore", - temporaryDirectory.resolve("pending-password.p12").toString(), - "-storetype", - "PKCS12") - .redirectErrorStream(true) - .start(); - } - - private static void cleanupKeytool(Process process) throws Exception { - if (process.isAlive()) process.destroyForcibly(); - assertThat(process.waitFor(5, TimeUnit.SECONDS)).isTrue(); - process.getOutputStream().close(); - process.getInputStream().close(); - process.getErrorStream().close(); - } - @Test void exactWorldClientReachesReceiverAndPassesOnlyTheRetainedLookupToOwner() throws Exception { var owner = mock(AccountStartSessionWorldParticipationSettlementService.class); @@ -358,7 +293,7 @@ private record TestPki( private static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("world-participation-settlement-test-ca.p12"); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( directory, "-genkeypair", "-alias", @@ -384,7 +319,7 @@ private static TestPki create(Path directory) throws Exception { "-keypass", STORE_PASSWORD); Path caFile = directory.resolve("world-participation-settlement-test-ca.crt"); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( directory, "-exportcert", "-alias", @@ -460,7 +395,7 @@ private static TestIdentity issueIdentity( Path certificate = directory.resolve(alias + "-signed.crt"); String san = "URI:" + workloadUri + (server ? ",DNS:localhost,IP:127.0.0.1" : ""); String usage = server ? "serverAuth" : "clientAuth"; - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( directory, "-genkeypair", "-alias", @@ -487,7 +422,7 @@ private static TestIdentity issueIdentity( STORE_PASSWORD, "-keypass", STORE_PASSWORD); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( directory, "-certreq", "-alias", @@ -502,7 +437,7 @@ private static TestIdentity issueIdentity( request.toString(), "-ext", "SAN=" + san); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( directory, "-gencert", "-alias", @@ -528,7 +463,7 @@ private static TestIdentity issueIdentity( "EKU=" + usage, "-ext", "SAN=" + san); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( directory, "-importcert", "-alias", @@ -542,7 +477,7 @@ private static TestIdentity issueIdentity( "-file", caFile.toString(), "-noprompt"); - runKeytool( + AccountStartSessionReservationProofPki.runKeytool( directory, "-importcert", "-alias", @@ -566,66 +501,6 @@ private static TestIdentity issueIdentity( (X509Certificate) keyStore.getCertificate(alias)); } - private static void runKeytool(Path directory, String... args) throws Exception { - Path keytool = - Path.of( - System.getProperty("java.home"), - "bin", - System.getProperty("os.name").toLowerCase().contains("windows") - ? "keytool.exe" - : "keytool"); - ArrayList command = new ArrayList<>(); - command.add(keytool.toString()); - command.addAll(List.of(args)); - Path output = Files.createTempFile(directory, "keytool-output-", ".log"); - try { - Process process = - new ProcessBuilder(command) - .redirectErrorStream(true) - .redirectOutput(output.toFile()) - .start(); - awaitKeytoolExit(process, 30, TimeUnit.SECONDS); - if (process.exitValue() != 0) { - throw new IllegalStateException("test keytool failed: " + Files.readString(output)); - } - } finally { - Files.deleteIfExists(output); - } - } - - /** Waits before reading child output, then terminates and reaps on timeout or interruption. */ - static void awaitKeytoolExit(Process process, long timeout, TimeUnit unit) - throws InterruptedException { - try { - if (!process.waitFor(timeout, unit)) { - throw new IllegalStateException("test keytool exceeded its execution deadline"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw interrupted; - } finally { - boolean restoreInterrupt = Thread.interrupted(); - try { - if (process.isAlive()) process.destroyForcibly(); - long cleanupDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - boolean reaped = false; - while (!reaped) { - long remaining = cleanupDeadline - System.nanoTime(); - if (remaining <= 0) { - throw new IllegalStateException("test keytool could not be reaped after termination"); - } - try { - reaped = process.waitFor(remaining, TimeUnit.NANOSECONDS); - } catch (InterruptedException interrupted) { - restoreInterrupt = true; - } - } - } finally { - if (restoreInterrupt) Thread.currentThread().interrupt(); - } - } - } - private static X509Certificate readCertificate(Path path) throws Exception { try (var input = Files.newInputStream(path)) { return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java index 9cf669c274..cf1a5de6bd 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.Base64; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -268,12 +269,12 @@ private static Identity issue( (X509Certificate) keyStore.getCertificate(alias)); } - private static void runKeytool(Path directory, String... args) throws Exception { + public static void runKeytool(Path directory, String... args) throws Exception { Path keytool = Path.of( System.getProperty("java.home"), "bin", - System.getProperty("os.name").toLowerCase().contains("windows") + System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("windows") ? "keytool.exe" : "keytool"); ArrayList command = new ArrayList<>(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java index 0fdcb5c9a2..efeefcf452 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java @@ -18,7 +18,6 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** Strict explicit mTLS client; never registers or enables the Account producer. */ public final class AccountSelectedPublicationOrderClient @@ -26,8 +25,6 @@ public final class AccountSelectedPublicationOrderClient AccountSelectedPublicationOrderServiceGrpc .AccountSelectedPublicationOrderServiceBlockingStub> { private final String namespace; - private volatile boolean initialized; - private volatile boolean closed; public AccountSelectedPublicationOrderClient( ServiceEndpointsProperties endpoints, @@ -40,27 +37,19 @@ public AccountSelectedPublicationOrderClient( this.namespace = namespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) throw new IllegalStateException("Account selected-publication client is closed"); - if (initialized) return; - initReloadingClient(); - if (stub() == null) - throw new IllegalStateException("Account selected-publication stub unavailable"); - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Account selected-publication client is closed", + "Account selected-publication stub unavailable"); } public AccountPublicationAuthorizationBinding authorize( AccountSelectedPublicationOrderGrpcCodec.Request request) { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) - throw new IllegalStateException( - "Account selected-publication transport requires no owner transaction"); + requireNoAmbientSql("Account selected-publication transport requires no owner transaction"); Objects.requireNonNull(request); if (!namespace.equals(request.targetNamespace())) throw new IllegalArgumentException("Account selected-publication namespace mismatch"); - var current = stub(); - if (closed || !initialized || current == null) - throw new IllegalStateException("Account selected-publication client unavailable"); + var current = requireInitializedStub("Account selected-publication client unavailable"); try { var response = current @@ -106,15 +95,6 @@ protected String defaultTarget() { .withCompression("gzip"); } - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - private static CommonGrpcClientProperties requireMtls(CommonGrpcClientProperties tls) { if (tls == null || tls.isPlaintext()) throw new IllegalArgumentException("Account selected-publication requires workload mTLS"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java index 8ac8526d31..cbf52664df 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java @@ -15,7 +15,6 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** Explicit file-backed mTLS client for Account-owned selected-publication settlement. */ public final class AccountSelectedPublicationSettlementClient @@ -26,8 +25,6 @@ public final class AccountSelectedPublicationSettlementClient private static final long CALL_DEADLINE_SECONDS = 30L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public AccountSelectedPublicationSettlementClient( ServiceEndpointsProperties endpoints, @@ -45,32 +42,23 @@ public AccountSelectedPublicationSettlementClient( this.workloadNamespace = workloadNamespace; } - public synchronized void init() throws SSLException, IOException { - if (closed) { - throw new IllegalStateException("Account publication settlement client is closed"); - } - if (initialized) return; - initReloadingClient(); - if (stub() == null) { - throw new IllegalStateException("Account publication settlement stub unavailable"); - } - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Account publication settlement client is closed", + "Account publication settlement stub unavailable"); } /** Returns the exact original six-frame receipt after Account peer and receipt validation. */ public byte[] settle(AccountSelectedPublicationSettlementGrpcCodec.Request request) { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException( - "Account publication settlement requires no owner transaction"); - } + requireNoAmbientSql("Account publication settlement requires no owner transaction"); Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "Account publication settlement must use the configured workload namespace"); } var response = - requireStub() + requireInitializedStub( + "Account publication settlement client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .settleSelectedPublication( AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); @@ -104,26 +92,6 @@ protected String defaultTarget() { .withMaxInboundMessageSize(AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES); } - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private AccountSelectedPublicationSettlementServiceGrpc - .AccountSelectedPublicationSettlementServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Account publication settlement client is not initialized and available"); - } - return currentStub; - } - private static CommonGrpcClientProperties requireFileBackedMtls( CommonGrpcClientProperties tlsProperties) { if (tlsProperties == null || tlsProperties.isPlaintext()) { diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 73fc63569b..9456958fe4 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -1877,10 +1877,12 @@ private static String loopback(Server server) { } private static final class SettlementDiagnostics { + private final boolean enabled = Boolean.getBoolean("firemud.settlementDiagnostics"); private final AtomicLong sequence = new AtomicLong(); private final long diagnosticOriginNanos = System.nanoTime(); void logPostgres(String role, PostgreSQLContainer postgres) { + if (!enabled) return; try { System.out.printf( "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s elapsed_since_diagnostic_start_nanos=%d container=%s host=%s mapped_port=%d running=%s%n", @@ -2129,6 +2131,7 @@ private String serializedSize(Object message) { } private void event(long call, String stage, String event, long elapsedNanos, String result) { + if (!enabled) return; long elapsedSinceDiagnosticStartNanos = System.nanoTime() - diagnosticOriginNanos; System.out.printf( "SETTLEMENT_DIAGNOSTIC call=%d stage=%s event=%s elapsed_nanos=%d elapsed_since_diagnostic_start_nanos=%d result=%s%n", From 6eb95d7a9cccfd3cd7d61bdac8baf45d0bcf6bd3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 06:26:53 +1300 Subject: [PATCH 53/61] Preserve selected owner proof failures during server cleanup --- ...nerPublicationPostgresIntegrationTest.java | 204 ++++++++++++++++-- 1 file changed, 187 insertions(+), 17 deletions(-) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 9456958fe4..edc15a6e8b 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -2,6 +2,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import com.google.protobuf.util.JsonFormat; import io.grpc.Server; @@ -463,6 +469,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema var replaySource = org.mockito.Mockito.mock( net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient.class); + Throwable bodyFailure = null; try { accountServer = ownerServer( @@ -830,16 +837,121 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema diagnostics); assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); } + } catch (Exception failure) { + bodyFailure = failure; + throw failure; + } catch (Error failure) { + bodyFailure = failure; + throw failure; } finally { - stop(accountServer); - stop(worldServer); - stop(entityServer); - stop(automationServer); - stop(gameLogicServer); + stopServers( + bodyFailure, + accountServer, + worldServer, + entityServer, + automationServer, + gameLogicServer); } } } + @Test + void ownerServerCleanupAttemptsEveryServerAndSuppressesFailuresOnBodyFailure() + throws InterruptedException { + Server firstServer = mock(Server.class); + Server secondServer = mock(Server.class); + Server thirdServer = mock(Server.class); + RuntimeException bodyFailure = new IllegalStateException("publication body failed"); + RuntimeException shutdownFailure = new IllegalStateException("first shutdown failed"); + RuntimeException waitFailure = new IllegalStateException("second wait failed"); + doThrow(shutdownFailure).when(firstServer).shutdownNow(); + when(firstServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + when(secondServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(waitFailure); + when(thirdServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(false); + + Throwable thrown = + catchThrowable( + () -> { + Throwable primaryFailure = null; + try { + throw bodyFailure; + } catch (RuntimeException failure) { + primaryFailure = failure; + throw failure; + } finally { + stopServers(primaryFailure, firstServer, secondServer, thirdServer); + } + }); + + assertThat(thrown).isSameAs(bodyFailure); + assertThat(bodyFailure.getSuppressed()).hasSize(3); + assertThat(bodyFailure.getSuppressed()[0].getCause()).isSameAs(shutdownFailure); + assertThat(bodyFailure.getSuppressed()[1].getCause()).isSameAs(waitFailure); + assertThat(bodyFailure.getSuppressed()[2].getMessage()) + .contains("Owner server 3 did not terminate"); + var order = inOrder(firstServer, secondServer, thirdServer); + order.verify(firstServer).shutdownNow(); + order.verify(secondServer).shutdownNow(); + order.verify(thirdServer).shutdownNow(); + order.verify(firstServer).awaitTermination(5, TimeUnit.SECONDS); + order.verify(secondServer).awaitTermination(5, TimeUnit.SECONDS); + order.verify(thirdServer).awaitTermination(5, TimeUnit.SECONDS); + } + + @Test + void ownerServerCleanupFailureFailsWhenPublicationBodySucceeded() throws InterruptedException { + Server firstServer = mock(Server.class); + Server secondServer = mock(Server.class); + Server thirdServer = mock(Server.class); + RuntimeException waitFailure = new IllegalStateException("first wait failed"); + when(firstServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(waitFailure); + when(secondServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + when(thirdServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + + assertThatThrownBy(() -> stopServers(null, firstServer, secondServer, thirdServer)) + .isInstanceOf(AssertionError.class) + .satisfies( + failure -> { + assertThat(failure.getSuppressed()).hasSize(1); + assertThat(failure.getSuppressed()[0].getCause()).isSameAs(waitFailure); + }); + + verify(firstServer).shutdownNow(); + verify(secondServer).shutdownNow(); + verify(thirdServer).shutdownNow(); + verify(firstServer).awaitTermination(5, TimeUnit.SECONDS); + verify(secondServer).awaitTermination(5, TimeUnit.SECONDS); + verify(thirdServer).awaitTermination(5, TimeUnit.SECONDS); + } + + @Test + void ownerServerCleanupRestoresInterruptAfterAttemptingAllTerminationWaits() + throws InterruptedException { + Server firstServer = mock(Server.class); + Server secondServer = mock(Server.class); + Server thirdServer = mock(Server.class); + InterruptedException interruption = new InterruptedException("first wait interrupted"); + when(firstServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(interruption); + when(secondServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + when(thirdServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + + try { + assertThatThrownBy(() -> stopServers(null, firstServer, secondServer, thirdServer)) + .isInstanceOf(AssertionError.class) + .satisfies( + failure -> { + assertThat(failure.getSuppressed()).hasSize(1); + assertThat(failure.getSuppressed()[0].getCause()).isSameAs(interruption); + }); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + verify(firstServer).awaitTermination(5, TimeUnit.SECONDS); + verify(secondServer).awaitTermination(5, TimeUnit.SECONDS); + verify(thirdServer).awaitTermination(5, TimeUnit.SECONDS); + } finally { + Thread.interrupted(); + } + } + /** Actual authenticated Account ordering consumes the real GDS immutable selection owner. */ private static net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding authenticatedAccountPublicationOrder( @@ -863,6 +975,7 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema endpoints.setGameDesignService(loopback(gdsServer)); var channels = new GrpcChannelFactory(); var sources = issued.sources(); + Throwable bodyFailure = null; try (var selectionClient = new net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient( endpoints, pki.client("account-service"), channels, NAMESPACE)) { @@ -913,9 +1026,14 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema .isEqualTo(1L); return created; } + } catch (Exception failure) { + bodyFailure = failure; + throw failure; + } catch (Error failure) { + bodyFailure = failure; + throw failure; } finally { - stop(accountServer); - stop(gdsServer); + stopServers(bodyFailure, accountServer, gdsServer); } } @@ -980,6 +1098,7 @@ private static WorldSelectedFullPublicationEvidenceFixture.Result freshAuthentic sources, NAMESPACE)); Server accountServer = null; Server worldServer = null; + Throwable bodyFailure = null; try { accountServer = ownerServer( @@ -1096,10 +1215,14 @@ private static WorldSelectedFullPublicationEvidenceFixture.Result freshAuthentic return retained; } } + } catch (Exception failure) { + bodyFailure = failure; + throw failure; + } catch (Error failure) { + bodyFailure = failure; + throw failure; } finally { - stop(worldServer); - stop(accountServer); - stop(gdsServer); + stopServers(bodyFailure, worldServer, accountServer, gdsServer); } } @@ -1179,6 +1302,7 @@ private static void completeActualWorldAndAccountTerminals( var endpoints = new ServiceEndpointsProperties(); endpoints.setGameDesignService(loopback(gdsTerminalServer)); var channels = new GrpcChannelFactory(); + Throwable bodyFailure = null; try (var worldGdsRead = new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient( endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { @@ -1345,10 +1469,14 @@ private static void completeActualWorldAndAccountTerminals( .containsExactly(published.canonicalBytes()); } } + } catch (Exception failure) { + bodyFailure = failure; + throw failure; + } catch (Error failure) { + bodyFailure = failure; + throw failure; } finally { - stop(accountSettlementServer); - stop(worldTerminalServer); - stop(gdsTerminalServer); + stopServers(bodyFailure, accountSettlementServer, worldTerminalServer, gdsTerminalServer); } } @@ -2156,10 +2284,52 @@ private static Server ownerServer( return builder.build().start(); } - private static void stop(Server server) throws InterruptedException { - if (server == null) return; - server.shutdownNow(); - assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + private static void stopServers(Throwable bodyFailure, Server... servers) { + List cleanupFailures = new ArrayList<>(); + boolean interrupted = bodyFailure instanceof InterruptedException; + + for (int index = 0; index < servers.length; index++) { + Server server = servers[index]; + if (server == null) continue; + try { + server.shutdownNow(); + } catch (RuntimeException | Error failure) { + cleanupFailures.add( + new IllegalStateException( + "Failed to request shutdown for owner server " + (index + 1), failure)); + } + } + + for (int index = 0; index < servers.length; index++) { + Server server = servers[index]; + if (server == null) continue; + try { + if (!server.awaitTermination(5, TimeUnit.SECONDS)) { + cleanupFailures.add( + new IllegalStateException( + "Owner server " + (index + 1) + " did not terminate within 5 seconds")); + } + } catch (InterruptedException failure) { + interrupted = true; + cleanupFailures.add( + new IllegalStateException( + "Interrupted while awaiting owner server " + (index + 1) + " termination", + failure)); + } catch (RuntimeException | Error failure) { + cleanupFailures.add( + new IllegalStateException( + "Failed while awaiting owner server " + (index + 1) + " termination", failure)); + } + } + + if (interrupted) Thread.currentThread().interrupt(); + if (bodyFailure != null) { + cleanupFailures.forEach(bodyFailure::addSuppressed); + } else if (!cleanupFailures.isEmpty()) { + AssertionError aggregate = new AssertionError("Selected-full owner server cleanup failed"); + cleanupFailures.forEach(aggregate::addSuppressed); + throw aggregate; + } } private static Store store( From 973a676e342ae9b2817d4769d42060d713654e48 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 07:20:20 +1300 Subject: [PATCH 54/61] Fix publication response bounds and shared client guards --- design/project-management/ai-observations.md | 13 +- .../GameDesignPublicationTerminalClient.java | 88 ++----------- .../AbstractReloadingBlockingGrpcClient.java | 41 ++++++ ...AccountSelectedPublicationOrderClient.java | 34 ++--- ...ountSelectedPublicationOrderGrpcCodec.java | 19 ++- ...ntSelectedPublicationSettlementClient.java | 38 +----- ...untSelectedPublicationOrderClientTest.java | 26 +++- ...SelectedPublicationOrderGrpcCodecTest.java | 123 ++++++++++++++++++ ...lectedPublicationSettlementClientTest.java | 33 +++++ ...licationTerminalClientTransactionTest.java | 26 ++++ 10 files changed, 285 insertions(+), 156 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 5b7de1a007..059dfe5847 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -265,9 +265,16 @@ Entry format: - Expected pattern: Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof. - Outcome: No production digest or retained bytes were changed. R44 and the fresh R45 JVM agree on the normalized vector; all 686 GDS unit cases pass in R45. -- 2026-10-15: Separate selected-publication owner proofs missed an Account settlement profile gap. The actual GDS terminal → authenticated World completion → both real terminal reads composition reached Account V94 and failed with SQLSTATE 23514 because its inventory validator still admitted only inventory/1 + World/3, while the current canonical producer retains closure inventory/2 + World/4. Preserve that failed composition beside prior component passes; a forward validator correction needs exact profile/refusal and existing-settlement byte/row-version upgrade proof. Do not rewrite installed migrations or treat controlled terminal readbacks as actual producer composition. Correction and qualification are in progress. - -- 2026-10-15 follow-up: Account's forward V1011 now converges the exact inventory/1 + World/3 and closure inventory/2 + World/4 validation profiles while retaining the original framing, digest, source and artifact guards. R14 passes the actual six-store terminal-to-settlement composition and nine malformed-profile refusals; R16 passes original PUBLISHED and NO_PUBLICATION settlement upgrade/replay with unchanged stored bytes and row versions. A test-only V1010 predecessor allowlist omission was corrected separately. These controlled component proofs supply no genuine creator, issuer, environment or deployed authority. +- `2026-10-15`: Separate selected-publication owner proofs missed an Account settlement profile gap. + - Context: The actual GDS terminal → authenticated World completion → both real terminal reads composition reached Account V94 and failed with SQLSTATE 23514 because its inventory validator still admitted only inventory/1 + World/3, while the current canonical producer retains closure inventory/2 + World/4. + - Observation: Correction and qualification are in progress. + - Expected pattern: Preserve that failed composition beside prior component passes; a forward validator correction needs exact profile/refusal and existing-settlement byte/row-version upgrade proof. Do not rewrite installed migrations or treat controlled terminal readbacks as actual producer composition. + +- `2026-10-15`: Selected-publication settlement profile follow-up. + - Context: Account's forward V1011 now converges the exact inventory/1 + World/3 and closure inventory/2 + World/4 validation profiles while retaining the original framing, digest, source and artifact guards. + - Observation: R14 passes the actual six-store terminal-to-settlement composition and nine malformed-profile refusals; R16 passes original PUBLISHED and NO_PUBLICATION settlement upgrade/replay with unchanged stored bytes and row versions. + - Outcome: A test-only V1010 predecessor allowlist omission was corrected separately. + - Expected pattern: These controlled component proofs supply no genuine creator, issuer, environment or deployed authority. - `2026-10-16`: Keep FireController briefs within the size limit - Context: FireController job briefs are capped at 200,000 characters. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java index 5f248d7ebc..5dcd5122b9 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java @@ -2,8 +2,6 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -15,7 +13,6 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; -import org.springframework.transaction.support.TransactionSynchronizationManager; /** Explicit mTLS client for the exact Game Design publication terminal read. */ public final class GameDesignPublicationTerminalClient @@ -25,8 +22,6 @@ public final class GameDesignPublicationTerminalClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GameDesignPublicationTerminalClient( ServiceEndpointsProperties endpoints, @@ -35,7 +30,7 @@ public GameDesignPublicationTerminalClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + requireFileBackedMtls(tlsProperties, "Game Design publication terminal read"), channelFactory, GameDesignPublicationTerminalClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -45,18 +40,10 @@ public GameDesignPublicationTerminalClient( } /** Initializes only when the owning Account or World service explicitly starts this client. */ - public synchronized void init() throws SSLException, IOException { - if (closed) { - throw new IllegalStateException("Game Design publication terminal client is closed"); - } - if (initialized) { - return; - } - initReloadingClient(); - if (stub() == null) { - throw new IllegalStateException("Game Design publication terminal client has no gRPC stub"); - } - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Game Design publication terminal client is closed", + "Game Design publication terminal client has no gRPC stub"); } /** @@ -65,18 +52,15 @@ public synchronized void init() throws SSLException, IOException { */ public GameDesignPublicationTerminalReadEvidence.ReadResult read( GameDesignPublicationTerminalReadEvidence.ReadRequest request) { - if (TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isSynchronizationActive()) { - throw new IllegalStateException( - "Game Design publication terminal read requires no owner transaction"); - } + requireNoAmbientSql("Game Design publication terminal read requires no owner transaction"); Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "Game Design publication terminal request must use the configured workload namespace"); } var response = - requireStub() + requireInitializedStub( + "Game Design publication terminal client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readGameDesignPublicationTerminal( GameDesignPublicationTerminalReadGrpcCodec.toRequest(request)); @@ -108,60 +92,4 @@ protected String defaultTarget() { .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); } - - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - - private GameDesignPublicationTerminalReadServiceGrpc - .GameDesignPublicationTerminalReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Game Design publication terminal client is not initialized and available"); - } - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException( - "Game Design publication terminal read requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "Game Design publication terminal read requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Game Design publication terminal read requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Game Design publication terminal read " + label + " must be a readable file-backed path", - invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Game Design publication terminal read " + label + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index 4e2f8cd6a6..a3cb2df6f3 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -3,6 +3,7 @@ import io.grpc.ManagedChannel; import io.grpc.stub.AbstractStub; import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import javax.net.ssl.SSLException; @@ -53,6 +54,46 @@ protected static final void requireNoAmbientSql(String message) { } } + protected static final CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties, String errorContext) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException(errorContext + " requires workload mTLS"); + } + for (String configuredPath : + new String[] { + tlsProperties.getCertChain(), tlsProperties.getPrivateKey(), tlsProperties.getCaCert() + }) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + errorContext + " requires readable file-backed TLS material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + errorContext + " requires readable file-backed TLS material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + errorContext + " requires readable file-backed TLS material"); + } + boolean readable; + try { + readable = Files.isRegularFile(path) && Files.isReadable(path); + } catch (RuntimeException inaccessible) { + throw new IllegalArgumentException( + errorContext + " requires readable file-backed TLS material"); + } + if (!readable) { + throw new IllegalArgumentException( + errorContext + " requires readable file-backed TLS material"); + } + } + return tlsProperties; + } + protected final void initReloadingClient() throws SSLException, IOException { if (tlsProps.isPlaintext() || !GrpcTlsReloadPolicy.isEnabled()) { reloadChannel(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java index efeefcf452..f7cf37d55e 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java @@ -5,8 +5,6 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -31,7 +29,11 @@ public AccountSelectedPublicationOrderClient( CommonGrpcClientProperties tls, GrpcChannelFactory factory, String namespace) { - super(endpoints, requireMtls(tls), factory, AccountSelectedPublicationOrderClient.class); + super( + endpoints, + requireFileBackedMtls(tls, "Account selected-publication"), + factory, + AccountSelectedPublicationOrderClient.class); if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw new IllegalArgumentException("Canonical Account namespace required"); this.namespace = namespace; @@ -92,28 +94,8 @@ protected String defaultTarget() { return AccountSelectedPublicationOrderServiceGrpc.newBlockingStub(channel) .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) - .withCompression("gzip"); - } - - private static CommonGrpcClientProperties requireMtls(CommonGrpcClientProperties tls) { - if (tls == null || tls.isPlaintext()) - throw new IllegalArgumentException("Account selected-publication requires workload mTLS"); - for (String configured : - new String[] {tls.getCertChain(), tls.getPrivateKey(), tls.getCaCert()}) { - if (configured == null || configured.isBlank() || configured.trim().startsWith("classpath:")) - throw new IllegalArgumentException( - "Account selected-publication requires readable file-backed TLS material"); - Path file; - try { - file = Path.of(configured.trim()); - } catch (RuntimeException malformed) { - throw new IllegalArgumentException( - "Account selected-publication requires file-backed TLS material"); - } - if (!Files.isRegularFile(file) || !Files.isReadable(file)) - throw new IllegalArgumentException( - "Account selected-publication requires readable file-backed TLS material"); - } - return tls; + .withCompression("gzip") + .withMaxInboundMessageSize( + AccountSelectedPublicationOrderGrpcCodec.MAX_RESPONSE_MESSAGE_BYTES); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java index 93c01ecb90..c187d2d2be 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java @@ -15,6 +15,10 @@ public final class AccountSelectedPublicationOrderGrpcCodec { public static final int MAX_CREDENTIAL_BYTES = 16384; public static final int MAX_SELECTION_BYTES = 1048576; + public static final int MAX_BINDING_BYTES = + AccountPublicationAuthorizationReadEvidence.MAX_BINDING_BYTES; + public static final int MAX_RESPONSE_MESSAGE_BYTES = + MAX_SELECTION_BYTES + MAX_BINDING_BYTES + 1024; private AccountSelectedPublicationOrderGrpcCodec() {} @@ -95,13 +99,16 @@ public static Request fromRequest(AuthorizeSelectedPublicationRequest wire, Stri public static AuthorizeSelectedPublicationResponse toResponse( Request request, AccountPublicationAuthorizationBinding binding) { + if (binding == null) throw invalid(); + byte[] bindingBytes = binding.canonicalBytes(); + if (bindingBytes.length == 0 || bindingBytes.length > MAX_BINDING_BYTES) throw invalid(); requireSelection(request, binding); return AuthorizeSelectedPublicationResponse.newBuilder() .setSchemaVersion(request.schemaVersion()) .setTargetNamespace(request.targetNamespace()) .setRequestId(request.requestId().toString()) .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) - .setPublicationAuthorizationBinding(ByteString.copyFrom(binding.canonicalBytes())) + .setPublicationAuthorizationBinding(ByteString.copyFrom(bindingBytes)) .build(); } @@ -109,15 +116,15 @@ public static AccountPublicationAuthorizationBinding fromResponse( Request request, AuthorizeSelectedPublicationResponse wire) { try { noUnknown(wire); + if (wire.getSerializedSize() > MAX_RESPONSE_MESSAGE_BYTES) throw invalid(); + var bindingBytes = wire.getPublicationAuthorizationBinding(); + if (bindingBytes.isEmpty() || bindingBytes.size() > MAX_BINDING_BYTES) throw invalid(); if (wire.getSchemaVersion() != request.schemaVersion() || !wire.getTargetNamespace().equals(request.targetNamespace()) || !wire.getRequestId().equals(request.requestId().toString()) - || !Arrays.equals(wire.getOriginalSelection().toByteArray(), request.originalSelection()) - || wire.getPublicationAuthorizationBinding().size() > MAX_SELECTION_BYTES) + || !Arrays.equals(wire.getOriginalSelection().toByteArray(), request.originalSelection())) throw invalid(); - var binding = - AccountPublicationAuthorizationBinding.fromStored( - wire.getPublicationAuthorizationBinding().toByteArray()); + var binding = AccountPublicationAuthorizationBinding.fromStored(bindingBytes.toByteArray()); requireSelection(request, binding); return binding; } catch (RuntimeException malformed) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java index cbf52664df..bc3ce66fd5 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java @@ -2,8 +2,6 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -33,7 +31,7 @@ public AccountSelectedPublicationSettlementClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + requireFileBackedMtls(tlsProperties, "Account publication settlement"), channelFactory, AccountSelectedPublicationSettlementClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -91,38 +89,4 @@ protected String defaultTarget() { .withCompression("gzip") .withMaxInboundMessageSize(AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES); } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException("Account publication settlement requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "Account publication settlement requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Account publication settlement requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Account publication settlement " + label + " must be a file-backed path", invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Account publication settlement " + label + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java index 26d4ac5fde..90579d9b81 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -34,13 +35,21 @@ void clear() { @Test void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) throws Exception { var factory = mock(GrpcChannelFactory.class); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), null, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication") + .hasNoCause(); var tls = tls(directory); tls.setPlaintext(true); assertThatThrownBy( () -> new AccountSelectedPublicationOrderClient( new ServiceEndpointsProperties(), tls, factory, "test")) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication"); tls.setPlaintext(false); for (String bad : new String[] { @@ -51,11 +60,18 @@ void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) th directory.resolve("missing.pem").toString() }) { tls.setCertChain(bad); - assertThatThrownBy( + Throwable failure = + catchThrowable( () -> new AccountSelectedPublicationOrderClient( - new ServiceEndpointsProperties(), tls, factory, "test")) - .isInstanceOf(IllegalArgumentException.class); + new ServiceEndpointsProperties(), tls, factory, "test")); + assertThat(failure) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication") + .hasNoCause(); + if (bad != null && !bad.isEmpty()) { + assertThat(failure).hasMessageNotContaining(bad); + } } var valid = tls(directory); assertThatThrownBy( @@ -88,6 +104,8 @@ void configuresExactAccountPeerDeadlineAndValidatesEchoOutsideSql(@TempDir Path var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); field.setAccessible(true); var initialized = (io.grpc.stub.AbstractStub) field.get(client); + assertThat(initialized.getCallOptions().getMaxInboundMessageSize()) + .isEqualTo(AccountSelectedPublicationOrderGrpcCodec.MAX_RESPONSE_MESSAGE_BYTES); var credentials = initialized.getCallOptions().getCredentials(); assertThat(credentials).isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); var peerField = diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java index 9b39340b8a..df0baf31a5 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java @@ -5,9 +5,14 @@ import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; +import java.time.OffsetDateTime; import java.util.List; import java.util.UUID; import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; import org.junit.jupiter.api.Test; class AccountSelectedPublicationOrderGrpcCodecTest { @@ -91,6 +96,10 @@ void rejectsChangedResponseEchoBindingAndUnknownFields() { response.toBuilder().setTargetNamespace("other").build(), response.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), response.toBuilder().clearOriginalSelection().build(), + response.toBuilder() + .setTargetNamespace( + "x".repeat(AccountSelectedPublicationOrderGrpcCodec.MAX_RESPONSE_MESSAGE_BYTES)) + .build(), response.toBuilder().setUnknownFields(unknown()).build(), response.toBuilder().clearPublicationAuthorizationBinding().build(), response.toBuilder() @@ -104,6 +113,120 @@ void rejectsChangedResponseEchoBindingAndUnknownFields() { } } + @Test + void roundTripsMaximumCanonicalSelectionWithLargerBoundedBinding() { + var base = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var selectionWithoutNotes = withNotes(base.input().selection(), ""); + int notesBytes = + AccountSelectedPublicationOrderGrpcCodec.MAX_SELECTION_BYTES + - selectionWithoutNotes.canonicalBytes().length; + var selection = withNotes(base.input().selection(), "n".repeat(notesBytes)); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create("test", selection, CREDENTIAL); + var binding = + new AccountPublicationAuthorizationBinding( + base.operationId(), + base.fenceId(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + base.input().actorAccountId(), selection), + base.sources()); + + assertThat(request.originalSelection()) + .hasSize(AccountSelectedPublicationOrderGrpcCodec.MAX_SELECTION_BYTES); + assertThat(binding.canonicalBytes()) + .hasSizeGreaterThan(request.originalSelection().length) + .hasSizeLessThanOrEqualTo(AccountSelectedPublicationOrderGrpcCodec.MAX_BINDING_BYTES); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(AccountSelectedPublicationOrderGrpcCodec.MAX_RESPONSE_MESSAGE_BYTES); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .containsExactly(binding.canonicalBytes()); + + var oversizedSelection = + withNotes( + base.input().selection(), + "n".repeat(AccountSelectedPublicationOrderGrpcCodec.MAX_SELECTION_BYTES)); + assertThat(oversizedSelection.canonicalBytes()) + .hasSizeGreaterThan(AccountSelectedPublicationOrderGrpcCodec.MAX_SELECTION_BYTES); + assertThatThrownBy( + () -> + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", oversizedSelection, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class) + .hasNoCause(); + } + + @Test + void rejectsOversizedBindingBeforeProducerAndConsumerDecode() { + var base = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", base.input().selection(), CREDENTIAL); + var source = base.sources().get(0); + var oversizedSource = + new SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + new byte[AccountSelectedPublicationOrderGrpcCodec.MAX_BINDING_BYTES + 1]); + var oversizedBinding = + new AccountPublicationAuthorizationBinding( + base.operationId(), base.fenceId(), base.input(), List.of(oversizedSource)); + + assertThat(oversizedBinding.canonicalBytes()) + .hasSizeGreaterThan(AccountSelectedPublicationOrderGrpcCodec.MAX_BINDING_BYTES); + assertThatThrownBy( + () -> AccountSelectedPublicationOrderGrpcCodec.toResponse(request, oversizedBinding)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid selected-publication order transport evidence") + .hasNoCause(); + + var wire = + AuthorizeSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .setPublicationAuthorizationBinding( + ByteString.copyFrom(oversizedBinding.canonicalBytes())) + .build(); + assertThat(wire.getSerializedSize()) + .isLessThanOrEqualTo(AccountSelectedPublicationOrderGrpcCodec.MAX_RESPONSE_MESSAGE_BYTES); + assertThatThrownBy(() -> AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, wire)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid selected-publication order transport evidence") + .hasNoCause(); + } + + private static AuthoredDraftPublishSelectionBinding withNotes( + AuthoredDraftPublishSelectionBinding selection, String notes) { + var intent = selection.intent(); + return AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + notes, + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()), + selection.target(), + selection.selectedCommit(), + new VisibilityFence( + selection.target(), + selection.fenceRequestId(), + selection.fenceCommitId(), + selection.fenceInputDigest(), + selection.fenceResultVectorJson(), + OffsetDateTime.parse(selection.fenceCreatedAt()))); + } + private static UnknownFieldSet unknown() { return UnknownFieldSet.newBuilder() .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java index 6ac82997be..c7efe63fe5 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java @@ -1,6 +1,9 @@ package net.firedevops.firemud.common.publication; 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.verifyNoInteractions; import io.grpc.Server; import io.grpc.Status; @@ -44,6 +47,36 @@ class AccountSelectedPublicationSettlementClientTest { private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; private static final String STORE_PASSWORD = "test-only-store-password"; + @Test + void requiresFileBackedMtlsWithAccountSettlementContext(@TempDir Path directory) { + var endpoints = new ServiceEndpointsProperties(); + var factory = mock(GrpcChannelFactory.class); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountSelectedPublicationSettlementClient( + endpoints, plaintext, factory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account publication settlement") + .hasNoCause(); + + var classpath = new CommonGrpcClientProperties(); + classpath.setPlaintext(false); + classpath.setCertChain("classpath:client.crt"); + classpath.setPrivateKey(directory.resolve("client.key").toString()); + classpath.setCaCert(directory.resolve("ca.crt").toString()); + assertThatThrownBy( + () -> + new AccountSelectedPublicationSettlementClient( + endpoints, classpath, factory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account publication settlement") + .hasMessageNotContaining("classpath:client.crt") + .hasNoCause(); + verifyNoInteractions(factory); + } + @Test void returnsCanonicalReceiptFromAuthenticatedAccountPeerAfterFormerFiveSecondWindow( @TempDir Path directory) throws Exception { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java index 6e66abf4af..0cd2843a8c 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java @@ -34,6 +34,32 @@ void clearTransactionContext() { TransactionSynchronizationManager.clear(); } + @Test + void requiresFileBackedMtlsWithGameDesignTerminalContext(@TempDir Path directory) { + var factory = mock(GrpcChannelFactory.class); + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> new GameDesignPublicationTerminalClient(endpoints, plaintext, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Game Design publication terminal read") + .hasNoCause(); + + var classpath = new CommonGrpcClientProperties(); + classpath.setPlaintext(false); + classpath.setCertChain("classpath:client.crt"); + classpath.setPrivateKey(directory.resolve("client.key").toString()); + classpath.setCaCert(directory.resolve("ca.crt").toString()); + assertThatThrownBy( + () -> new GameDesignPublicationTerminalClient(endpoints, classpath, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Game Design publication terminal read") + .hasMessageNotContaining("classpath:client.crt") + .hasNoCause(); + verifyNoInteractions(factory); + } + @Test void excludesActiveAndSynchronizationOnlyTransactionsBeforeAnyRpc(@TempDir Path directory) throws Exception { From c5f7f48bfcbe9b5c2a5b55149ab65d4e0c833b3e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 07:32:33 +1300 Subject: [PATCH 55/61] test: require exact selected publication refusal statuses --- ...nerPublicationPostgresIntegrationTest.java | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index edc15a6e8b..4e327233ce 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -1003,7 +1003,12 @@ void ownerServerCleanupRestoresInterruptAfterAttemptingAllTerminationWaits() var before = publicationOrderRows(sources.dsl); assertThat(before.get("account_selected_publication_authorizations")).isEmpty(); assertThat(before.get("account_selected_publication_sources")).isEmpty(); - assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> client.authorize(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.UNAVAILABLE)); assertThat(publicationOrderRows(sources.dsl)).isEqualTo(before); assertThat(reads.get()).isEqualTo(1); unavailable.set(false); @@ -1178,7 +1183,12 @@ private static WorldSelectedFullPublicationEvidenceFixture.Result freshAuthentic "SELECT owner_freeze_phase FROM world_design_publication_fence_owner") .get(0, String.class)) .isEqualTo("OPEN"); - assertThatThrownBy(() -> freeze.begin(request)).isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> freeze.begin(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.UNAVAILABLE)); assertThat(freezeOwnerRows(world.dsl())).isEqualTo(before); assertThat(selectionCalls.get()).isEqualTo(1); assertThat(versionCalls.get()).isEqualTo(1); @@ -1387,7 +1397,11 @@ private static void completeActualWorldAndAccountTerminals( net.firedevops.firemud.common.publication .AccountSelectedPublicationSettlementGrpcCodec.Request.create( NAMESPACE, operation.canonicalBytes()))) - .isInstanceOf(RuntimeException.class); + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); return null; }); assertThat( From 2cff49c55aa37d100de378486e6834899e930f4e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 07:58:43 +1300 Subject: [PATCH 56/61] fix: validate exact configured selected publication TLS paths --- .../AbstractReloadingBlockingGrpcClient.java | 2 +- ...untSelectedPublicationOrderClientTest.java | 75 +++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index a3cb2df6f3..8840f13cee 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -67,7 +67,7 @@ protected static final CommonGrpcClientProperties requireFileBackedMtls( throw new IllegalArgumentException( errorContext + " requires readable file-backed TLS material"); } - String pathText = configuredPath.trim(); + String pathText = configuredPath; if (pathText.startsWith("classpath:")) { throw new IllegalArgumentException( errorContext + " requires readable file-backed TLS material"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java index 90579d9b81..7431387421 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java @@ -82,6 +82,81 @@ void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) th verifyNoInteractions(factory); } + @Test + void validatesExactConfiguredTlsPathsBeforeCreatingAChannel(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + + var certChainTls = tls(directory); + certChainTls.setCertChain(certChainTls.getCertChain() + " "); + assertThat(Files.exists(Path.of(certChainTls.getCertChain()))).isFalse(); + assertThat(Files.isReadable(Path.of(certChainTls.getCertChain().trim()))).isTrue(); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), certChainTls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication") + .hasMessageNotContaining(certChainTls.getCertChain()) + .hasNoCause(); + + var privateKeyTls = tls(directory); + privateKeyTls.setPrivateKey(privateKeyTls.getPrivateKey() + " "); + assertThat(Files.exists(Path.of(privateKeyTls.getPrivateKey()))).isFalse(); + assertThat(Files.isReadable(Path.of(privateKeyTls.getPrivateKey().trim()))).isTrue(); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), privateKeyTls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication") + .hasMessageNotContaining(privateKeyTls.getPrivateKey()) + .hasNoCause(); + + var caCertTls = tls(directory); + caCertTls.setCaCert(caCertTls.getCaCert() + " "); + assertThat(Files.exists(Path.of(caCertTls.getCaCert()))).isFalse(); + assertThat(Files.isReadable(Path.of(caCertTls.getCaCert().trim()))).isTrue(); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), caCertTls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication") + .hasMessageNotContaining(caCertTls.getCaCert()) + .hasNoCause(); + + verifyNoInteractions(factory); + } + + @Test + void acceptsAndPreservesTrailingSpacesInExistingTlsPaths(@TempDir Path directory) + throws Exception { + var certChain = Files.writeString(directory.resolve("client.crt "), "certificate"); + var privateKey = Files.writeString(directory.resolve("client.key "), "private-key"); + var caCert = Files.writeString(directory.resolve("ca.crt "), "ca"); + assertThat(Files.exists(directory.resolve("client.crt"))).isFalse(); + assertThat(Files.exists(directory.resolve("client.key"))).isFalse(); + assertThat(Files.exists(directory.resolve("ca.crt"))).isFalse(); + + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(certChain.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(caCert.toString()); + var client = + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "test"); + + var tlsPropsField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("tlsProps"); + tlsPropsField.setAccessible(true); + var copiedTls = (CommonGrpcClientProperties) tlsPropsField.get(client); + assertThat(copiedTls.getCertChain()).isEqualTo(certChain.toString()); + assertThat(copiedTls.getPrivateKey()).isEqualTo(privateKey.toString()); + assertThat(copiedTls.getCaCert()).isEqualTo(caCert.toString()); + client.close(); + } + @Test void configuresExactAccountPeerDeadlineAndValidatesEchoOutsideSql(@TempDir Path directory) throws Exception { From 7b07f3568e767b0a7ddd85a4bf7b24280bb9944f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 09:26:35 +1300 Subject: [PATCH 57/61] fix(account): allow bounded selected-order credential metadata --- .../account-service/api-contracts.md | 2 ++ ...ectedDraftPublicationOrderGrpcService.java | 7 +++- ...horizationMtlsPostgresIntegrationTest.java | 1 + ...ctedDraftPublicationOrderGrpcMtlsTest.java | 35 ++++++++++++++++++- ...ountSelectedPublicationOrderGrpcCodec.java | 2 ++ ...lectedPublicationOrderCredentialsTest.java | 9 ++++- ...nerPublicationPostgresIntegrationTest.java | 2 ++ 7 files changed, 55 insertions(+), 3 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 89c31dc784..2d62ae9923 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -26,6 +26,8 @@ Decline or missing reacceptance does not itself cancel a subscription, delete co The original Draft claim transport delegates to Account’s existing creator and retained-fence owners; a claim uses the exact same-namespace Game Design workload and protected creator credential, while the separate held-order read is restricted to the exact World workload. The [original-order proto](../../../../protos/account/v1/original_draft_order_service.proto) carries only the original operation and transport correlation; it supplies neither environment authority nor a creator credential in its body. The credential is carried in the protected binary metadata header and retains Account’s 16 KiB maximum compact creator-token bound. The shared transport codec permits 22,872 bytes of inbound metadata and a 4 MiB + 1 KiB inbound request message. Before registering `AccountOriginalDraftOrderGrpcService`, the Account receiving server must allow inbound metadata of at least `AccountOriginalDraftOrderGrpcCodec.MAX_METADATA_BYTES` and inbound request messages of at least `AccountOriginalDraftOrderGrpcCodec.MAX_WIRE_BYTES`; binding the service configures neither server limit. Held replay preserves the original binding and pending settlement rather than issuing fresh creator authority. These adapters remain unregistered, and both application profiles continue to omit permission for the RPCs. Controlled issuer, environment and PKI inputs are component proof only; caller qualification and remaining genuine authority are tracked in [Game Authoring](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#original-account-ordered-world-source-caller). +The selected-publication order adapter likewise carries the original creator credential only in protected binary metadata, with an unchanged 16 KiB maximum. Its `AccountSelectedPublicationOrderGrpcCodec.MAX_METADATA_BYTES` allowance is 22,872 bytes, including base64 wire encoding and bounded metadata overhead. Any future Account receiving composition must allow that metadata size before registering `AccountSelectedDraftPublicationOrderGrpcService`; binding the service does not configure the server limit. The service remains unregistered, so this prerequisite does not configure or claim a deployed receiver. + The unregistered Draft terminal reconciler consumes the exact required Game Design and World owner readbacks outside Account transactions, then retains missing evidence through the existing Account fence repository after rechecking the original binding and ordering. Additional required v2 owners without a supported reader remain pending. It creates no new authorization or runtime access; its qualification and source-provenance limits belong to [the authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#account-terminal-settlement-continuation). Both terminal-read transports retain the complete original binding and complete owner readback. Their shared bounds are 4 MiB for the binding, 16 MiB for the complete framed owner readback (including its repeated binding and result), and 1 KiB for protobuf/request metadata. The response allowance is therefore 20 MiB plus 1 KiB; both Account clients set that inbound limit, and both owner codecs enforce the same field and wire bounds on production and consumption. Receiving-server composition must allow the request bound of 4 MiB plus 1 KiB before these currently unregistered adapters are enabled. These limits change no original bytes, outcome, owner authorization or settlement rule. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java index 4c928b56d9..0b584f52dc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java @@ -22,7 +22,12 @@ import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Standalone, unregistered producer; Account obtains environment authority internally. */ +/** + * Standalone, unregistered producer; Account obtains environment authority internally. Any future + * receiving server must allow at least {@link + * AccountSelectedPublicationOrderGrpcCodec#MAX_METADATA_BYTES} inbound metadata before registering + * this service; binding it does not configure that server limit. + */ public final class AccountSelectedDraftPublicationOrderGrpcService implements BindableService { private final AccountSelectedDraftPublicationOrderService owner; private final AccountHostedTermsService terms; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java index aa2431ccfd..b10df212dd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -698,6 +698,7 @@ private static Server terminalServer( TestIdentity identity, Path ca, io.grpc.BindableService... endpoints) throws Exception { var builder = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMetadataSize(AccountSelectedPublicationOrderGrpcCodec.MAX_METADATA_BYTES) .sslContext( GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) .trustManager(ca.toFile()) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java index 5c6c1d9957..7c09e53845 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java @@ -102,6 +102,34 @@ void authenticatedGameDesignClientReachesEnvironmentCaptureThenUnresolvedOwner() } } + @Test + void maximumCreatorCredentialMetadataReachesAuthenticatedOwnerUnchanged() throws Exception { + String credential = "A".repeat(AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES); + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(credential), any(), same(captured))) + .thenThrow(Status.FAILED_PRECONDITION.asRuntimeException()); + + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + var client = newClient(server.port(), pki.gameDesignClient())) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request(credential))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + + assertThat(server.handlerCalls()).hasValue(1); + var calls = inOrder(terms, owner); + calls.verify(terms).captureCurrentEnvironmentBoundary(); + calls.verify(owner).authorize(eq(credential), any(), same(captured)); + } + } + @Test void trustedWrongServiceAndNamespaceGameDesignCallersAreDeniedBeforeCapture() throws Exception { for (TestIdentity identity : List.of(pki.wrongServiceClient(), pki.otherNamespaceClient())) { @@ -209,6 +237,7 @@ public io.grpc.ServerCall.Listener interceptCall( }; Server server = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMetadataSize(AccountSelectedPublicationOrderGrpcCodec.MAX_METADATA_BYTES) .sslContext( GrpcSslContexts.configure( SslContextBuilder.forServer( @@ -261,6 +290,10 @@ private static ClientTransport newClientWithIdentity(int port, TestIdentity iden } private static AccountSelectedPublicationOrderGrpcCodec.Request request() { + return request(CREDENTIAL); + } + + private static AccountSelectedPublicationOrderGrpcCodec.Request request(String credential) { UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); var target = new DraftCommitBinding.TargetProof( @@ -303,7 +336,7 @@ private static AccountSelectedPublicationOrderGrpcCodec.Request request() { "[]", OffsetDateTime.parse("2026-10-01T00:00:00Z"))); return AccountSelectedPublicationOrderGrpcCodec.Request.create( - NAMESPACE, selection, CREDENTIAL); + NAMESPACE, selection, credential); } private static final String CREDENTIAL = "original.secret.credential"; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java index c187d2d2be..ceeb056bb0 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java @@ -14,6 +14,8 @@ /** Closed producer transport. Credential data never appears in responses or diagnostics. */ public final class AccountSelectedPublicationOrderGrpcCodec { public static final int MAX_CREDENTIAL_BYTES = 16384; + // Protected binary metadata uses base64 on the gRPC wire plus bounded metadata overhead. + public static final int MAX_METADATA_BYTES = ((MAX_CREDENTIAL_BYTES + 2) / 3) * 4 + 1024; public static final int MAX_SELECTION_BYTES = 1048576; public static final int MAX_BINDING_BYTES = AccountPublicationAuthorizationReadEvidence.MAX_BINDING_BYTES; diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java index a003a624f5..aed92c82e7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java @@ -66,6 +66,8 @@ void carrierAndWrapperAreRedactedAndApplyOnlyToProtectedExactMethod() { @Test void authenticatedReadRejectsMissingDuplicateOversizedAndMalformedHeadersWithoutSecretDiagnostics() { + String maxCredential = + "A".repeat(AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES); var missing = new Metadata(); var duplicate = new Metadata(); duplicate.put(RAW, SECRET.getBytes(StandardCharsets.US_ASCII)); @@ -77,7 +79,7 @@ void carrierAndWrapperAreRedactedAndApplyOnlyToProtectedExactMethod() { raw(new byte[0]), raw(new byte[] {(byte) 128}), raw((SECRET + "\n").getBytes(StandardCharsets.US_ASCII)), - raw(new byte[16385]))) { + raw(new byte[AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES + 1]))) { assertThatThrownBy( () -> AccountSelectedPublicationOrderCredentials.readAuthenticated(headers)) .isInstanceOf(IllegalArgumentException.class) @@ -89,6 +91,11 @@ void carrierAndWrapperAreRedactedAndApplyOnlyToProtectedExactMethod() { raw(SECRET.getBytes(StandardCharsets.US_ASCII))); assertThat(exact.value()).isEqualTo(SECRET); assertThat(exact.toString()).doesNotContain(SECRET); + assertThat( + AccountSelectedPublicationOrderCredentials.readAuthenticated( + raw(maxCredential.getBytes(StandardCharsets.US_ASCII))) + .value()) + .isEqualTo(maxCredential); } private static Metadata raw(byte[] bytes) { diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 4e327233ce..bc956259e1 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -61,6 +61,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; @@ -2288,6 +2289,7 @@ private static Server ownerServer( var identity = pki.server(service); var builder = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMetadataSize(AccountSelectedPublicationOrderGrpcCodec.MAX_METADATA_BYTES) .sslContext( GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) .trustManager(pki.ca().toFile()) From de8695176c0c78f61d32ed8ad1edf801ccdbd3c9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 09:55:46 +1300 Subject: [PATCH 58/61] test(publication): share controlled PKI and bound concurrent cleanup --- ...horizationMtlsPostgresIntegrationTest.java | 175 +++------- ...ctedDraftPublicationOrderGrpcMtlsTest.java | 209 ++---------- ...ldParticipationSettlementGrpcMtlsTest.java | 200 ++--------- ...ccountStartSessionReservationProofPki.java | 321 +++++++++++------- ...leaseCanonicalIdentityIntegrationTest.java | 30 +- 5 files changed, 325 insertions(+), 610 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java index b10df212dd..1acb484eb8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -14,7 +14,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.KeyStore; import java.util.Base64; import java.util.List; import java.util.UUID; @@ -894,162 +893,64 @@ private static final class TestPki { otherWorldNamespace; TestPki(Path root) throws Exception { - Path caStore = root.resolve("ca.p12"); - AccountStartSessionReservationProofPki.runKeytool( - root, - "-genkeypair", - "-alias", - "test-ca", - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=Account publication test CA", - "-validity", - "30", - "-ext", - "BC=ca:true", - "-ext", - "KU=keyCertSign,cRLSign", - "-storetype", - "PKCS12", - "-keystore", - caStore.toString(), - "-storepass", - PASSWORD, - "-keypass", - PASSWORD); - ca = root.resolve("ca.crt"); - AccountStartSessionReservationProofPki.runKeytool( - root, - "-exportcert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - PASSWORD, - "-file", - ca.toString(), - "-rfc"); - server = issue(root, caStore, "account-server", NAMESPACE, "account-service", true); - accountClient = issue(root, caStore, "account-client", NAMESPACE, "account-service", false); + var authority = + AccountStartSessionReservationProofPki.createCertificateAuthority( + root, "ca.p12", "ca.crt", "test-ca", "CN=Account publication test CA", PASSWORD); + ca = authority.certificateFile(); + server = issue(root, authority, "account-server", NAMESPACE, "account-service", true); + accountClient = issue(root, authority, "account-client", NAMESPACE, "account-service", false); gameDesignServer = - issue(root, caStore, "game-design-server", NAMESPACE, "game-design-service", true); + issue(root, authority, "game-design-server", NAMESPACE, "game-design-service", true); worldServer = - issue(root, caStore, "world-server", NAMESPACE, "world-management-service", true); + issue(root, authority, "world-server", NAMESPACE, "world-management-service", true); gameDesign = - issue(root, caStore, "game-design-client", NAMESPACE, "game-design-service", false); + issue(root, authority, "game-design-client", NAMESPACE, "game-design-service", false); worldManagement = - issue(root, caStore, "world-client", NAMESPACE, "world-management-service", false); + issue(root, authority, "world-client", NAMESPACE, "world-management-service", false); wrongWorkload = - issue(root, caStore, "game-session-client", NAMESPACE, "game-session-service", false); + issue(root, authority, "game-session-client", NAMESPACE, "game-session-service", false); otherNamespace = issue( root, - caStore, + authority, "other-game-design-client", "other-test", "game-design-service", false); otherWorldNamespace = issue( - root, caStore, "other-world-client", "other-test", "world-management-service", false); + root, + authority, + "other-world-client", + "other-test", + "world-management-service", + false); } private static TestIdentity issue( - Path root, Path caStore, String alias, String namespace, String workload, boolean server) + Path root, + AccountStartSessionReservationProofPki.TestCertificateAuthority authority, + String alias, + String namespace, + String workload, + boolean server) throws Exception { - Path store = root.resolve(alias + ".p12"), - request = root.resolve(alias + ".csr"), - certificate = root.resolve(alias + ".crt"); - String san = - "URI:spiffe://firemud/ns/" - + namespace - + "/sa/" - + workload - + ",DNS:localhost,IP:127.0.0.1"; - String eku = server ? "serverAuth" : "clientAuth"; - AccountStartSessionReservationProofPki.runKeytool( - root, - "-genkeypair", - "-alias", - alias, - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=" + alias, - "-validity", - "30", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + eku, - "-ext", - "SAN=" + san, - "-storetype", - "PKCS12", - "-keystore", - store.toString(), - "-storepass", - PASSWORD, - "-keypass", - PASSWORD); - AccountStartSessionReservationProofPki.runKeytool( - root, - "-certreq", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - PASSWORD, - "-file", - request.toString(), - "-ext", - "SAN=" + san); - AccountStartSessionReservationProofPki.runKeytool( - root, - "-gencert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - PASSWORD, - "-infile", - request.toString(), - "-outfile", - certificate.toString(), - "-validity", - "30", - "-rfc", - "-ext", - "BC=ca:false", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + eku, - "-ext", - "SAN=" + san); - var keyStore = KeyStore.getInstance("PKCS12"); - try (var input = Files.newInputStream(store)) { - keyStore.load(input, PASSWORD.toCharArray()); - } + var issued = + AccountStartSessionReservationProofPki.issueIdentity( + root, + authority, + alias, + alias + ".p12", + alias + ".csr", + alias + ".crt", + "spiffe://firemud/ns/" + namespace + "/sa/" + workload, + server, + true, + false); byte[] privateKey = java.util.Objects.requireNonNull( java.util.Objects.requireNonNull( - keyStore.getKey(alias, PASSWORD.toCharArray()), - "Expected ephemeral test private key") + issued.identity().privateKey(), "Expected ephemeral test private key") .getEncoded(), "Expected encoded ephemeral test private key"); Path key = root.resolve(alias + ".key"); @@ -1059,7 +960,7 @@ private static TestIdentity issue( "-----BEGIN PRIVATE KEY-----\n" + body + "\n-----END PRIVATE KEY-----\n", StandardCharsets.US_ASCII); java.util.Arrays.fill(privateKey, (byte) 0); - return new TestIdentity(certificate, key); + return new TestIdentity(issued.certificateFile(), key); } } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java index 7c09e53845..937b78fad5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java @@ -24,9 +24,7 @@ import java.net.InetSocketAddress; import java.nio.file.Files; import java.nio.file.Path; -import java.security.KeyStore; import java.security.PrivateKey; -import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.time.OffsetDateTime; import java.util.Base64; @@ -386,65 +384,24 @@ private record TestPki( private static final String STORE_PASSWORD = "test-only-store-password"; private static TestPki create(Path directory) throws Exception { - Path caStore = directory.resolve("selected-publication-test-ca.p12"); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-genkeypair", - "-alias", - "test-ca", - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=FireMUD selected publication test CA", - "-validity", - "30", - "-ext", - "BC=ca:true", - "-ext", - "KU=keyCertSign,cRLSign", - "-storetype", - "PKCS12", - "-keystore", - caStore.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - Path caFile = directory.resolve("selected-publication-test-ca.crt"); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-exportcert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-rfc"); - var ca = readCertificate(caFile); + var authority = + AccountStartSessionReservationProofPki.createCertificateAuthority( + directory, + "selected-publication-test-ca.p12", + "selected-publication-test-ca.crt", + "test-ca", + "CN=FireMUD selected publication test CA", + STORE_PASSWORD); return new TestPki( - ca, - caFile, - issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), - issueIdentity(directory, caStore, caFile, "wrong-service-server", WRONG_SERVER_URI, true), - issueIdentity( - directory, caStore, caFile, "other-namespace-server", WRONG_ACCOUNT_URI, true), - issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false), + authority.certificate(), + authority.certificateFile(), + issueIdentity(directory, authority, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, authority, "wrong-service-server", WRONG_SERVER_URI, true), + issueIdentity(directory, authority, "other-namespace-server", WRONG_ACCOUNT_URI, true), + issueIdentity(directory, authority, "game-design-client", GAME_DESIGN_URI, false), + issueIdentity(directory, authority, "wrong-service-client", WRONG_CLIENT_URI, false), issueIdentity( - directory, caStore, caFile, "wrong-service-client", WRONG_CLIENT_URI, false), - issueIdentity( - directory, - caStore, - caFile, - "other-namespace-client", - OTHER_NAMESPACE_CLIENT_URI, - false)); + directory, authority, "other-namespace-client", OTHER_NAMESPACE_CLIENT_URI, false)); } private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) @@ -468,122 +425,26 @@ private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity } private static TestIdentity issueIdentity( - Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + Path directory, + AccountStartSessionReservationProofPki.TestCertificateAuthority authority, + String alias, + String workloadUri, + boolean server) throws Exception { - Path store = directory.resolve(alias + ".p12"); - Path request = directory.resolve(alias + ".csr"); - Path certificate = directory.resolve(alias + ".crt"); - String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-genkeypair", - "-alias", - alias, - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=" + alias, - "-validity", - "30", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + (server ? "serverAuth" : "clientAuth"), - "-ext", - "SAN=" + san, - "-storetype", - "PKCS12", - "-keystore", - store.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-certreq", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - request.toString(), - "-ext", - "SAN=" + san); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-gencert", - "-alias", - "test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-infile", - request.toString(), - "-outfile", - certificate.toString(), - "-validity", - "30", - "-rfc", - "-ext", - "BC=ca:false", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + (server ? "serverAuth" : "clientAuth"), - "-ext", - "SAN=" + san); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-importcert", - "-alias", - "test-ca", - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-noprompt"); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-importcert", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - certificate.toString(), - "-noprompt"); - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - try (var input = Files.newInputStream(store)) { - keyStore.load(input, STORE_PASSWORD.toCharArray()); - } - return new TestIdentity( - alias, - (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), - (X509Certificate) keyStore.getCertificate(alias)); - } - - private static X509Certificate readCertificate(Path path) throws Exception { - try (var input = Files.newInputStream(path)) { - return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); - } + var identity = + AccountStartSessionReservationProofPki.issueIdentity( + directory, + authority, + alias, + alias + ".p12", + alias + ".csr", + alias + ".crt", + workloadUri, + server, + true, + true) + .identity(); + return new TestIdentity(identity.alias(), identity.privateKey(), identity.certificate()); } private static Path writePem(Path path, String label, byte[] bytes) throws IOException { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java index 49ed04378a..f721291564 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java @@ -25,9 +25,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.KeyStore; import java.security.PrivateKey; -import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.List; @@ -292,69 +290,32 @@ private record TestPki( "spiffe://firemud/ns/world-runtime/sa/world-management-service"; private static TestPki create(Path directory) throws Exception { - Path caStore = directory.resolve("world-participation-settlement-test-ca.p12"); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-genkeypair", - "-alias", - "world-participation-settlement-ca", - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=FireMUD controlled World participation settlement test CA", - "-validity", - "30", - "-ext", - "BC=ca:true", - "-ext", - "KU=keyCertSign,cRLSign", - "-storetype", - "PKCS12", - "-keystore", - caStore.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - Path caFile = directory.resolve("world-participation-settlement-test-ca.crt"); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-exportcert", - "-alias", - "world-participation-settlement-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-rfc"); - X509Certificate ca = readCertificate(caFile); + var authority = + AccountStartSessionReservationProofPki.createCertificateAuthority( + directory, + "world-participation-settlement-test-ca.p12", + "world-participation-settlement-test-ca.crt", + "world-participation-settlement-ca", + "CN=FireMUD controlled World participation settlement test CA", + STORE_PASSWORD); return new TestPki( - ca, + authority.certificate(), issueIdentity( directory, - caStore, - caFile, + authority, "account-server", "spiffe://firemud/ns/world-runtime/sa/account-service", true), - issueIdentity(directory, caStore, caFile, "world-client", WORLD_URI, false), + issueIdentity(directory, authority, "world-client", WORLD_URI, false), issueIdentity( directory, - caStore, - caFile, + authority, "wrong-service-client", "spiffe://firemud/ns/world-runtime/sa/game-session-service", false), issueIdentity( directory, - caStore, - caFile, + authority, "other-namespace-client", "spiffe://firemud/ns/other-runtime/sa/world-management-service", false)); @@ -388,123 +349,26 @@ private Path caCertificatePem(Path directory) throws Exception { } private static TestIdentity issueIdentity( - Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + Path directory, + AccountStartSessionReservationProofPki.TestCertificateAuthority authority, + String alias, + String workloadUri, + boolean server) throws Exception { - Path store = directory.resolve(alias + ".p12"); - Path request = directory.resolve(alias + ".csr"); - Path certificate = directory.resolve(alias + "-signed.crt"); - String san = "URI:" + workloadUri + (server ? ",DNS:localhost,IP:127.0.0.1" : ""); - String usage = server ? "serverAuth" : "clientAuth"; - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-genkeypair", - "-alias", - alias, - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=" + alias, - "-validity", - "30", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + usage, - "-ext", - "SAN=" + san, - "-storetype", - "PKCS12", - "-keystore", - store.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-certreq", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - request.toString(), - "-ext", - "SAN=" + san); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-gencert", - "-alias", - "world-participation-settlement-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-infile", - request.toString(), - "-outfile", - certificate.toString(), - "-validity", - "30", - "-rfc", - "-ext", - "BC=ca:false", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + usage, - "-ext", - "SAN=" + san); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-importcert", - "-alias", - "world-participation-settlement-ca", - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-noprompt"); - AccountStartSessionReservationProofPki.runKeytool( - directory, - "-importcert", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - certificate.toString(), - "-noprompt"); - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - try (var input = Files.newInputStream(store)) { - keyStore.load(input, STORE_PASSWORD.toCharArray()); - } - return new TestIdentity( - alias, - (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), - (X509Certificate) keyStore.getCertificate(alias)); - } - - private static X509Certificate readCertificate(Path path) throws Exception { - try (var input = Files.newInputStream(path)) { - return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); - } + var identity = + AccountStartSessionReservationProofPki.issueIdentity( + directory, + authority, + alias, + alias + ".p12", + alias + ".csr", + alias + "-signed.crt", + workloadUri, + server, + false, + true) + .identity(); + return new TestIdentity(identity.alias(), identity.privateKey(), identity.certificate()); } private static Path writePem(Path path, String label, byte[] bytes) throws IOException { diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java index cf1a5de6bd..4a82b6ae81 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java @@ -32,22 +32,29 @@ private AccountStartSessionReservationProofPki( this.account = account; } - public static AccountStartSessionReservationProofPki create(Path directory, String namespace) + /** Creates one controlled CA using the caller's established fixture names and password. */ + public static TestCertificateAuthority createCertificateAuthority( + Path directory, + String storeFileName, + String certificateFileName, + String alias, + String distinguishedName, + String password) throws Exception { Files.createDirectories(directory); - Path caStore = directory.resolve("reservation-test-ca.p12"); - Path caFile = directory.resolve("reservation-test-ca.crt"); + Path caStore = directory.resolve(storeFileName); + Path caFile = directory.resolve(certificateFileName); runKeytool( directory, "-genkeypair", "-alias", - "reservation-test-ca", + alias, "-keyalg", "RSA", "-keysize", "2048", "-dname", - "CN=Controlled Logging claim-read test CA", + distinguishedName, "-validity", "30", "-ext", @@ -59,67 +66,209 @@ public static AccountStartSessionReservationProofPki create(Path directory, Stri "-keystore", caStore.toString(), "-storepass", - PASSWORD, + password, "-keypass", - PASSWORD); + password); runKeytool( directory, "-exportcert", "-alias", - "reservation-test-ca", + alias, "-keystore", caStore.toString(), "-storetype", "PKCS12", "-storepass", - PASSWORD, + password, "-file", caFile.toString(), "-rfc"); + return new TestCertificateAuthority(alias, caStore, caFile, readCertificate(caFile), password); + } + + /** Issues one controlled workload identity while retaining caller-specific SAN and store form. */ + public static IssuedIdentity issueIdentity( + Path directory, + TestCertificateAuthority authority, + String alias, + String storeFileName, + String requestFileName, + String certificateFileName, + String workloadUri, + boolean server, + boolean addLoopbackSansForClients, + boolean importCertificateChainIntoStore) + throws Exception { + String password = authority.storePassword(); + Path store = directory.resolve(storeFileName); + Path request = directory.resolve(requestFileName); + Path certificateFile = directory.resolve(certificateFileName); + String san = + "URI:" + + workloadUri + + (server || addLoopbackSansForClients ? ",DNS:localhost,IP:127.0.0.1" : ""); + String usage = server ? "serverAuth" : "clientAuth"; + runKeytool( + directory, + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + password, + "-keypass", + password); + runKeytool( + directory, + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + password, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + directory, + "-gencert", + "-alias", + authority.alias(), + "-keystore", + authority.keyStore().toString(), + "-storetype", + "PKCS12", + "-storepass", + password, + "-infile", + request.toString(), + "-outfile", + certificateFile.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san); + if (importCertificateChainIntoStore) { + runKeytool( + directory, + "-importcert", + "-alias", + authority.alias(), + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + password, + "-file", + authority.certificateFile().toString(), + "-noprompt"); + runKeytool( + directory, + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + password, + "-file", + certificateFile.toString(), + "-noprompt"); + } + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, password.toCharArray()); + } + X509Certificate certificate = + importCertificateChainIntoStore + ? (X509Certificate) keyStore.getCertificate(alias) + : readCertificate(certificateFile); + Identity identity = + new Identity( + alias, (PrivateKey) keyStore.getKey(alias, password.toCharArray()), certificate); + return new IssuedIdentity(identity, certificateFile); + } + + public static AccountStartSessionReservationProofPki create(Path directory, String namespace) + throws Exception { + TestCertificateAuthority authority = + createCertificateAuthority( + directory, + "reservation-test-ca.p12", + "reservation-test-ca.crt", + "reservation-test-ca", + "CN=Controlled Logging claim-read test CA", + PASSWORD); Map servers = Map.of( "logging", issue( directory, - caStore, - caFile, + authority, "logging-server", "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", true), "wrong-workload", issue( directory, - caStore, - caFile, + authority, "wrong-workload-server", "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", true), "missing-identity", issue( directory, - caStore, - caFile, + authority, "missing-identity-server", "https://localhost/controlled-test", true), "wrong-namespace", issue( directory, - caStore, - caFile, + authority, "wrong-namespace-server", "spiffe://firemud/ns/other-runtime/sa/logging-admin-service", true)); Identity account = issue( directory, - caStore, - caFile, + authority, "account-client", "spiffe://firemud/ns/" + namespace + "/sa/account-service", false); return new AccountStartSessionReservationProofPki( - directory, readCertificate(caFile), servers, account); + directory, authority.certificate(), servers, account); } public Identity accountIdentity() { @@ -156,117 +305,20 @@ public CommonGrpcClientProperties clientProperties() throws Exception { } private static Identity issue( - Path directory, Path caStore, Path caFile, String alias, String uri, boolean server) + Path directory, TestCertificateAuthority authority, String alias, String uri, boolean server) throws Exception { - Path store = directory.resolve(alias + ".p12"); - Path csr = directory.resolve(alias + ".csr"); - Path cert = directory.resolve(alias + "-signed.crt"); - String san = server ? "URI:" + uri + ",DNS:localhost,IP:127.0.0.1" : "URI:" + uri; - String usage = server ? "serverAuth" : "clientAuth"; - runKeytool( - directory, - "-genkeypair", - "-alias", - alias, - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=" + alias, - "-validity", - "30", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + usage, - "-ext", - "SAN=" + san, - "-storetype", - "PKCS12", - "-keystore", - store.toString(), - "-storepass", - PASSWORD, - "-keypass", - PASSWORD); - runKeytool( - directory, - "-certreq", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - PASSWORD, - "-file", - csr.toString(), - "-ext", - "SAN=" + san); - runKeytool( - directory, - "-gencert", - "-alias", - "reservation-test-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - PASSWORD, - "-infile", - csr.toString(), - "-outfile", - cert.toString(), - "-validity", - "30", - "-rfc", - "-ext", - "BC=ca:false", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + usage, - "-ext", - "SAN=" + san); - runKeytool( - directory, - "-importcert", - "-alias", - "reservation-test-ca", - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - PASSWORD, - "-file", - caFile.toString(), - "-noprompt"); - runKeytool( - directory, - "-importcert", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - PASSWORD, - "-file", - cert.toString(), - "-noprompt"); - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - try (var input = Files.newInputStream(store)) { - keyStore.load(input, PASSWORD.toCharArray()); - } - return new Identity( - alias, - (PrivateKey) keyStore.getKey(alias, PASSWORD.toCharArray()), - (X509Certificate) keyStore.getCertificate(alias)); + return issueIdentity( + directory, + authority, + alias, + alias + ".p12", + alias + ".csr", + alias + "-signed.crt", + uri, + server, + false, + true) + .identity(); } public static void runKeytool(Path directory, String... args) throws Exception { @@ -344,4 +396,13 @@ private static Path writePem(Path path, String label, byte[] bytes) throws IOExc } public record Identity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + public record TestCertificateAuthority( + String alias, + Path keyStore, + Path certificateFile, + X509Certificate certificate, + String storePassword) {} + + public record IssuedIdentity(Identity identity, Path certificateFile) {} } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 4a2abf2aa6..b163010139 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -524,7 +524,9 @@ void concurrentExactSelectedFullRetriesCommitOneImmutableBundle() throws Excepti Version version = saveVersion(fixture, owner); var operation = selectedFullOperation(fixture, version); var start = new java.util.concurrent.CountDownLatch(1); - try (var executor = java.util.concurrent.Executors.newFixedThreadPool(2)) { + var executor = java.util.concurrent.Executors.newFixedThreadPool(2); + Throwable testFailure = null; + try { java.util.concurrent.Callable save = () -> { start.await(); @@ -556,6 +558,32 @@ void concurrentExactSelectedFullRetriesCommitOneImmutableBundle() throws Excepti .usingRecursiveComparison() .isEqualTo(one); assertThat(releaseBundleTuple(fixture.dsl(), one.getId())).isEqualTo(beforeRetry); + } catch (Exception | Error failure) { + testFailure = failure; + if (failure instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + throw failure; + } finally { + try { + executor.shutdownNow(); + if (!executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)) { + throw new IllegalStateException("Executor did not terminate within 10 seconds"); + } + } catch (InterruptedException cleanupFailure) { + Thread.currentThread().interrupt(); + if (testFailure != null) { + testFailure.addSuppressed(cleanupFailure); + } else { + throw cleanupFailure; + } + } catch (RuntimeException cleanupFailure) { + if (testFailure != null) { + testFailure.addSuppressed(cleanupFailure); + } else { + throw cleanupFailure; + } + } } } From 4e15cdfb159cb4a7e3f748f4099bcb592b9ab723 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 20 Oct 2026 12:31:27 +1300 Subject: [PATCH 59/61] Enforce selected-publication workload caller contract --- .../account-service/api-contracts.md | 8 +++++- .../player-access-and-session.md | 4 +-- ...ectedDraftPublicationOrderGrpcService.java | 2 ++ ...dParticipationPostgresIntegrationTest.java | 6 +++-- ...dDraftPublicationOrderGrpcServiceTest.java | 26 +++++++++++++++++++ 5 files changed, 41 insertions(+), 5 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 2d62ae9923..d25cd74309 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -24,9 +24,15 @@ Supported reads and downloads, including any controlled export the product suppo Decline or missing reacceptance does not itself cancel a subscription, delete content, decide a refund, or change billing or entitlement state. Subscription and billing consequences remain independent under [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) and the Account subscription lifecycle; payment or continued hosting never implies hosted-terms acceptance or marketplace enrollment. Future creator commerce remains separately gated by [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). +### Original Creator Callback Authorization + +For fresh current-actor callbacks, Account observes its existing clock after the final blocking owner operations and immediately before invoking the callback. The original ControlUI issuance must have whole-second `issuedAt = iat = nbf`, with zero skew, and one clock observation must satisfy `issuedAt <= now < expiresAt`. Account does not rewrite the token, registry cleanup deadline, source evidence, or retained order. Exact historical recovery of an already-held original order remains separate and may proceed after creator expiry. Global token profile, signature, and key contracts remain defined by [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). + +For each fresh current-actor path, Account loads the existing trusted public JWKS source outside SQL transactions and synchronization. The protected snapshot must contain the immutable original signer receipt’s exact key ID and RFC 7638 fingerprint. An accepted original key may coexist with other current public keys and need not be the newest active signer. The snapshot belongs to one invocation and does not guarantee acceptance through later locks, callback, or commit. Signature/profile, active registry, historical signer provenance, and current Account source checks remain independent; the source remains unregistered. + The original Draft claim transport delegates to Account’s existing creator and retained-fence owners; a claim uses the exact same-namespace Game Design workload and protected creator credential, while the separate held-order read is restricted to the exact World workload. The [original-order proto](../../../../protos/account/v1/original_draft_order_service.proto) carries only the original operation and transport correlation; it supplies neither environment authority nor a creator credential in its body. The credential is carried in the protected binary metadata header and retains Account’s 16 KiB maximum compact creator-token bound. The shared transport codec permits 22,872 bytes of inbound metadata and a 4 MiB + 1 KiB inbound request message. Before registering `AccountOriginalDraftOrderGrpcService`, the Account receiving server must allow inbound metadata of at least `AccountOriginalDraftOrderGrpcCodec.MAX_METADATA_BYTES` and inbound request messages of at least `AccountOriginalDraftOrderGrpcCodec.MAX_WIRE_BYTES`; binding the service configures neither server limit. Held replay preserves the original binding and pending settlement rather than issuing fresh creator authority. These adapters remain unregistered, and both application profiles continue to omit permission for the RPCs. Controlled issuer, environment and PKI inputs are component proof only; caller qualification and remaining genuine authority are tracked in [Game Authoring](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#original-account-ordered-world-source-caller). -The selected-publication order adapter likewise carries the original creator credential only in protected binary metadata, with an unchanged 16 KiB maximum. Its `AccountSelectedPublicationOrderGrpcCodec.MAX_METADATA_BYTES` allowance is 22,872 bytes, including base64 wire encoding and bounded metadata overhead. Any future Account receiving composition must allow that metadata size before registering `AccountSelectedDraftPublicationOrderGrpcService`; binding the service does not configure the server limit. The service remains unregistered, so this prerequisite does not configure or claim a deployed receiver. +The selected-publication order adapter accepts only the exact same-namespace Game Design workload without authenticated end-user caller context, and carries the original creator credential only in protected binary metadata with an unchanged 16 KiB maximum. Its `AccountSelectedPublicationOrderGrpcCodec.MAX_METADATA_BYTES` allowance is 22,872 bytes, including base64 wire encoding and bounded metadata overhead. Any future Account receiving composition must allow that metadata size before registering `AccountSelectedDraftPublicationOrderGrpcService`; binding the service does not configure the server limit. The service remains unregistered, so this prerequisite does not configure or claim a deployed receiver. The unregistered Draft terminal reconciler consumes the exact required Game Design and World owner readbacks outside Account transactions, then retains missing evidence through the existing Account fence repository after rechecking the original binding and ordering. Additional required v2 owners without a supported reader remain pending. It creates no new authorization or runtime access; its qualification and source-provenance limits belong to [the authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#account-terminal-settlement-continuation). 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 3a487a1e91..23139b27d4 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -22,13 +22,13 @@ The existing [World original-owner composition](../../../services/world-manageme ### Original creator validity at the callback boundary -Both current-actor methods compare the original ControlUI token's complete validity interval after their final blocking owner operations, immediately before invoking a fresh authorization callback. One observation of the existing clock must satisfy `issuedAt <= now < expiresAt`; the canonical original issuance has whole-second `issuedAt = iat = nbf` and zero skew. The original token, registry cleanup deadline, source evidence and retained order remain unchanged. Exact historical recovery of an already-held original order remains permitted after creator expiry. +Both fresh current-actor paths implement [Account's original creator callback authorization contract](../../architecture/microservices/account-service/api-contracts.md#original-creator-callback-authorization) in `AccountControlUiActorService`. The existing Account original-order PostgreSQL fixture changes its injected actor clock when the real final owner locking read completes. The earlier expiry-only code enters both callbacks when that clock moves before the original not-before boundary. The corrected fixture denies both early and expired callbacks without changing the original row JSON or row version, permits both callbacks at exact original `issuedAt` equality, and preserves the existing expired-creator exact-recovery case. These seven native cases plus the unchanged healthy secured Account owner case pass at `cefccc984d6154b9d1b8c3e439541584d2844fc8` with zero failures, errors or skips and affected integration static analysis and formatting. Seven existing Actor unit cases and Main/unit static analysis retain their passing attribution at `774864935ba9783dab410507689ad2848c00fe15`, with the identical production blob. That earlier aggregate failed only because the fixture used an unavailable assertion overload; the test-only correction retains its exact Boolean predicate. Strict passive capture owns the final run's two PostgreSQL containers with inherited resource-session descriptor, no ownership gaps or observer errors, and neither container remaining afterward. This establishes a controlled temporal boundary at a real locking read, not measured physical contention, continuous production protection, genuine upstream authority, activation, admission or Entity delivery. ### Original creator key acceptance -Both fresh current-actor paths load the existing trusted public JWKS source outside SQL transactions and synchronization. They require the immutable original signer receipt’s exact key ID and RFC 7638 fingerprint in that protected snapshot, alongside the existing signature/profile, active registry, historical signer provenance, current Account source and final token validity checks. Accepted original keys may coexist with other current public keys; acceptance does not require selecting the newest active signer. The snapshot belongs to one invocation and supplies no guarantee that acceptance continues through later locks, callback or commit. Exact historical held-order recovery remains separate from fresh authentication. +Both fresh current-actor paths implement [Account's original creator callback authorization contract](../../architecture/microservices/account-service/api-contracts.md#original-creator-callback-authorization) in `AccountControlUiActorService`. The existing native original-order fixture proves missing-key and same-key-ID replacement refusal in both paths, accepted-original membership alongside another key, untrusted-source and protected-read failure refusal, and rejection before protected reads under ambient SQL or synchronization. Each parameter compares complete original row JSON and row version. Current snapshot membership is explicitly stipulated through the same concrete source fixture; the source-failure cases execute its real protected observation failure. This models accepted retiring-key membership and does not prove actual signer rotation, publication, withdrawal or compromise authority. At source `5c5363a5ba7caf3af5e6ca9dd93ea212ce3b0c5f`, all fourteen parameters, seven existing native time/equality/recovery cases, the healthy secured Account owner case and seven existing Actor unit cases pass: twenty-nine fresh cases with zero failures, errors or skips. Affected main, unit, integration and test-fixture static analysis, formatting and documentation checks pass. The test-only old-code source `fff5a48653bbcf6e0cd04610dd264c9e1b65c243` first preserves the original row, then fails all four missing/replaced-key callback-denial assertions. The successful run’s strict passive observer owns two PostgreSQL containers with an inherited resource-session descriptor, no ownership gaps or observer errors, and both containers absent afterward. These are bounded component proofs, without genuine upstream authority, runtime registration, gameplay admission or Entity delivery. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java index 0b584f52dc..e8f7b6a823 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; import org.springframework.transaction.support.TransactionSynchronizationManager; /** @@ -149,6 +150,7 @@ private static void deny(StreamObserver observer, Status status) { private Status peerDenial() { var peer = GrpcPeerIdentity.current(); if (peer == null) return Status.UNAUTHENTICATED; + if (SessionContext.hasAuthenticatedCallerContext()) return Status.PERMISSION_DENIED; return ("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri()) ? null : Status.PERMISSION_DENIED; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java index d8ed35617a..6925708488 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java @@ -150,8 +150,10 @@ void originalTupleRecoversCommittedParticipationAfterLostResponseAndLeaseExpiry( "tuple-recovery-world", GAME_TEMPLATE_ID); String preparationDigest = digest(preparationInput); + // Bounded synthetic headroom lets initial retention reach its currentness gate; later reads + // use this same expiry. Instant leaseExpiresAt = - Instant.ofEpochMilli(databaseNow(proof.sourceDsl()).toEpochMilli()).plusSeconds(4L); + Instant.ofEpochMilli(databaseNow(proof.sourceDsl()).toEpochMilli()).plusSeconds(10L); // The Game Session point-in-time observation is stipulated; Account's original issue, // redemption, source capture, acquisition gates, and PostgreSQL retention are real. var acquisition = @@ -496,7 +498,7 @@ private static Instant databaseNow(DSLContext dsl) { } private static void awaitDatabaseExpiry(DSLContext dsl, Instant expiresAt) throws Exception { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10L); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15L); while (!databaseNow(dsl).isAfter(expiresAt)) { if (System.nanoTime() >= deadline) { throw new IllegalStateException("PostgreSQL clock did not pass the retained lease expiry"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java index 2521aa49f1..7e8aba8be6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java @@ -24,6 +24,7 @@ import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -39,6 +40,7 @@ class AccountSelectedDraftPublicationOrderGrpcServiceTest { @AfterEach void clear() { + SessionContext.clear(); TransactionSynchronizationManager.clear(); } @@ -81,6 +83,30 @@ void boundInterceptorAuthenticatesBeforeTouchingMalformedCredentialMetadata() { verifyNoInteractions(owner, terms); } + @Test + void authenticatedCallerContextDeniesBoundCallBeforeReadingCredentialMetadata() { + SessionContext.setContext("test-user", List.of(), java.util.Map.of()); + var headers = mock(io.grpc.Metadata.class); + + assertThat(peer("test", "game-design-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(headers, owner, terms); + } + + @Test + void authenticatedCallerContextDeniesDirectCallBeforeMalformedPayloadDecode() { + SessionContext.setContext("test-user", List.of(), java.util.Map.of()); + + assertThat( + peer( + "test", + "game-design-service", + () -> invoke(AuthorizeSelectedPublicationRequest.getDefaultInstance())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner, terms); + } + @SuppressWarnings("unchecked") private Status.Code boundCode(io.grpc.Metadata headers) { var method = From c452490f4d4e0fe93c419f30a886e09ce21270f2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:12:39 +1300 Subject: [PATCH 60/61] Tighten publication workload authorization and review proof --- design/project-management/ai-observations.md | 7 ++ ...ntPublicationAuthorizationReadService.java | 7 +- ...inalDraftOrderPostgresIntegrationTest.java | 30 ++++- ...blicationAuthorizationReadServiceTest.java | 21 ++++ ...AccountSelectedPublicationOrderClient.java | 5 +- ...untSelectedPublicationOrderClientTest.java | 4 +- ...leaseCanonicalIdentityIntegrationTest.java | 119 ++++++++++++------ 7 files changed, 146 insertions(+), 47 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a2e4550a11..3fd650c3a7 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -268,6 +268,7 @@ Entry format: - `2026-10-15`: Separate selected-publication owner proofs missed an Account settlement profile gap. - Context: The actual GDS terminal → authenticated World completion → both real terminal reads composition reached Account V94 and failed with SQLSTATE 23514 because its inventory validator still admitted only inventory/1 + World/3, while the current canonical producer retains closure inventory/2 + World/4. - Observation: Correction and qualification are in progress. + - Outcome: Forward V1011 converges both validation profiles; the following selected-publication settlement entry records the R14/R16 qualification and its controlled-proof limits. - Expected pattern: Preserve that failed composition beside prior component passes; a forward validator correction needs exact profile/refusal and existing-settlement byte/row-version upgrade proof. Do not rewrite installed migrations or treat controlled terminal readbacks as actual producer composition. - `2026-10-15`: Selected-publication settlement profile follow-up. @@ -359,3 +360,9 @@ Entry format: - Observation: The ORT analyzer container did not inherit `CI`, so this project's Node Gradle plugin enabled a download repository that ORT cannot analyze. ORT 97 also disables repository package curations by default, even when it discovers a valid `.ort.yml`. - Expected pattern: Forward the existing CI environment contract explicitly and enable the documented repository-curation option while retaining global providers. Normalize only exact package/version metadata supported by upstream license text, and record a package-specific choice for an explicitly offered alternative. Custom licenses require their own policy decision; do not relabel them as SPDX aliases or waive unresolved policy errors. - Proof limit: Workflow wiring, YAML, failure guards and upstream metadata are checked locally. Only actual analyzer/evaluator results can qualify the hosted correction; the earlier Maven Central 403 response origin remains unknown. + +- `2026-10-24`: Distinguish PostgreSQL health from the Docker-published connection path + - Context: A forced Account integration run at `3534f58291439f7c059759cc57a7385106051e39` ran 333 cases with 13 mapped-localhost connection failures and no skips. One failed fixture recorded a running PostgreSQL container, successful internal Unix-socket `SELECT 1`, IPv4 localhost resolution and a Docker host-port binding while the test JVM's mapped JDBC connection was refused. The other twelve failures shared a different fixture without equivalent internal-health diagnostics. + - Observation: Those facts isolate the first failure to the test-to-published-port path without identifying a Docker Desktop, WSL, fixture or cleanup cause. Successful internal SQL or published binding metadata alone is insufficient host-path readiness proof. + - Outcome: A later focused run passed all seven source-evidence and twelve selected-owner cases without a Docker, host-setting or fixture change. This qualifies those nineteen cases separately; it neither turns the earlier failed aggregate green nor proves the connection problem repaired. + - Expected pattern: Retain exact fixture, host, mapped-port and internal SQL evidence beside the original failed run; qualify a focused retry independently and investigate recurrence without weakening readiness or cleaning unrelated containers. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java index aabbb848e7..df26c62b31 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java @@ -5,6 +5,7 @@ import java.util.Objects; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.security.SessionContext; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -75,8 +76,10 @@ static void requirePeer(String namespace) { .asRuntimeException(); } String peerUri = peer.uri(); - if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peerUri) - && !("spiffe://firemud/ns/" + namespace + "/sa/world-management-service").equals(peerUri)) { + if (SessionContext.hasAuthenticatedCallerContext() + || (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peerUri) + && !("spiffe://firemud/ns/" + namespace + "/sa/world-management-service") + .equals(peerUri))) { throw Status.PERMISSION_DENIED .withDescription("Exact same-namespace Game Design or World Management workload required") .asRuntimeException(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java index 1f22e95936..e40b6882e8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java @@ -219,7 +219,9 @@ public void executeEnd(ExecuteContext context) { assertThat(clock.instant()).isEqualTo(Instant.ofEpochSecond(issuedAt)); assertThat(failure).isNull(); } else { - assertThat(failure).isInstanceOf(IllegalStateException.class); + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact current authenticated initial creator required"); } assertThat( f.tx( @@ -417,8 +419,20 @@ void originalCreatorRequiresExactKeyInCurrentProtectedSnapshot( assertThat(callback.get()).isEqualTo("RETAINED".equals(keyState)); if ("RETAINED".equals(keyState)) { assertThat(failure).isNull(); + } else if (List.of("ABSENT", "REPLACED").contains(keyState)) { + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact current authenticated initial creator required"); + } else if ("SOURCE_FAILURE".equals(keyState) || "UNTRUSTED".equals(keyState)) { + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } else if ("SQL".equals(keyState) || "SYNCHRONIZATION".equals(keyState)) { + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Signature/registry/JWKS reads must precede owner SQL locks"); } else { - assertThat(failure).isInstanceOf(RuntimeException.class); + throw new AssertionError("Unexpected key state " + keyState); } if ("SQL".equals(keyState) || "SYNCHRONIZATION".equals(keyState)) { assertThat(reads.get()).isZero(); @@ -498,7 +512,9 @@ void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrS var before = f.tx(() -> f.fences.read(original)); clock.advance(Duration.ofMinutes(10)); assertThatThrownBy(() -> issued.actors().verifySigned(issued.compact())) - .isInstanceOf(RuntimeException.class); + .isInstanceOf( + net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier + .VerificationException.class); asPeer("test", "game-design-service", () -> invoke(receiver, request)); var owner = new AccountOriginalDraftOrderService(issued.actors(), "test"); @@ -537,7 +553,9 @@ void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrS "test", "game-design-service", () -> owner.claim(issued.compact(), changed, issued.environment()))) - .isInstanceOf(RuntimeException.class); + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .extracting(failure -> io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION); var absent = new DraftAuthorizationFenceBinding( UUID.randomUUID(), @@ -560,7 +578,9 @@ void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrS "test", "game-design-service", () -> owner.claim(issued.compact(), absent, issued.environment()))) - .isInstanceOf(RuntimeException.class); + .isInstanceOf( + net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier + .VerificationException.class); assertThat(f.tx(() -> f.fences.readOriginalBinding(absent.operationId()))).isEmpty(); for (String[] peer : List.of( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java index 98b3fce42e..0b04160423 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -44,6 +45,7 @@ class AccountPublicationAuthorizationReadServiceTest { @AfterEach void clear() { + SessionContext.clear(); TransactionSynchronizationManager.clear(); } @@ -95,6 +97,13 @@ void rejectsUnverifiedWrongWorkloadCrossNamespaceAndAmbientTransactionBeforeLook assertCode( Status.Code.PERMISSION_DENIED, () -> asPeer("other", "world-management-service", () -> service.requireHeld(request))); + SessionContext.setContext("authenticated-player", List.of(), java.util.Map.of()); + for (String workload : List.of("game-design-service", "world-management-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", workload, () -> service.requireHeld(request))); + } + SessionContext.clear(); assertCode( Status.Code.PERMISSION_DENIED, () -> asPeer("test", "game-design-service", () -> service.requireHeld(request("other")))); @@ -166,6 +175,18 @@ public void onCompleted() { endpoint.readHeldPublicationAuthorization( ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); assertThat(Status.fromThrowable(error.get()).getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + SessionContext.setContext("authenticated-player", List.of(), java.util.Map.of()); + for (String workload : List.of("game-design-service", "world-management-service")) { + asPeer( + "test", + workload, + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + SessionContext.clear(); verifyNoInteractions(repository, transactions); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java index f7cf37d55e..31707e6059 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java @@ -22,6 +22,9 @@ public final class AccountSelectedPublicationOrderClient extends AbstractReloadingBlockingGrpcClient< AccountSelectedPublicationOrderServiceGrpc .AccountSelectedPublicationOrderServiceBlockingStub> { + // Covers the nested Game Design selection read plus Account authorization and persistence. + private static final long CALL_DEADLINE_SECONDS = 30L; + private final String namespace; public AccountSelectedPublicationOrderClient( @@ -61,7 +64,7 @@ public AccountPublicationAuthorizationBinding authorize( "spiffe://firemud/ns/" + namespace + "/sa/account-service"), AccountSelectedPublicationOrderCredentials.forCall( request.originalCreatorCredential()))) - .withDeadlineAfter(5, TimeUnit.SECONDS) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .authorizeSelectedPublication( AccountSelectedPublicationOrderGrpcCodec.toRequest(request)); return AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, response); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java index 7431387421..5affea2688 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java @@ -192,7 +192,7 @@ void configuresExactAccountPeerDeadlineAndValidatesEchoOutsideSql(@TempDir Path mock( AccountSelectedPublicationOrderServiceGrpc .AccountSelectedPublicationOrderServiceBlockingStub.class); - when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withDeadlineAfter(30, TimeUnit.SECONDS)).thenReturn(stub); when(stub.withCallCredentials(any())).thenReturn(stub); field.set(client, stub); TransactionSynchronizationManager.setActualTransactionActive(true); @@ -210,7 +210,7 @@ void configuresExactAccountPeerDeadlineAndValidatesEchoOutsideSql(@TempDir Path var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); when(stub.authorizeSelectedPublication(any())).thenReturn(response); assertThat(client.authorize(request).canonicalBytes()).isEqualTo(binding.canonicalBytes()); - verify(stub).withDeadlineAfter(5, TimeUnit.SECONDS); + verify(stub).withDeadlineAfter(30, TimeUnit.SECONDS); var wire = org.mockito.ArgumentCaptor.forClass( net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest.class); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index b163010139..341be17fd1 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -604,30 +604,36 @@ void sqlGuardRejectsMissingAndChangedSelectedFullBindingsWithoutAnyRelease() thr var versionBefore = sourceRow(fixture.dsl(), "version", version.getId()); assertThat(json.readTree(original).path("request").path("versionStateEpoch").isTextual()) .isTrue(); - assertThatThrownBy(() -> insertRawSelectedFull(fixture, version, operation, null, participants)) - .isInstanceOf(DataAccessException.class); + // The exact operation-byte guard rejects substituted evidence before its semantic checks. + assertSelectedFullMutationRejected( + fixture, + version, + operation, + null, + participants, + "selected publication is absent, sealed, or changed"); for (String epoch : java.util.List.of("0", "01", "-1", "9223372036854775808")) { var changed = (tools.jackson.databind.node.ObjectNode) json.readTree(original); ((tools.jackson.databind.node.ObjectNode) changed.get("request")) .put("versionStateEpoch", epoch); - assertThatThrownBy( - () -> - insertRawSelectedFull( - fixture, version, operation, json.writeValueAsString(changed), participants)) - .isInstanceOf(DataAccessException.class); + assertSelectedFullMutationRejected( + fixture, + version, + operation, + json.writeValueAsString(changed), + participants, + "selected publication is absent, sealed, or changed"); } var numericEpoch = (tools.jackson.databind.node.ObjectNode) json.readTree(original); ((tools.jackson.databind.node.ObjectNode) numericEpoch.get("request")) .put("versionStateEpoch", 1L); - assertThatThrownBy( - () -> - insertRawSelectedFull( - fixture, - version, - operation, - json.writeValueAsString(numericEpoch), - participants)) - .isInstanceOf(DataAccessException.class); + assertSelectedFullMutationRejected( + fixture, + version, + operation, + json.writeValueAsString(numericEpoch), + participants, + "selected publication is absent, sealed, or changed"); for (String field : java.util.List.of( "canonicalTenantId", @@ -641,11 +647,13 @@ void sqlGuardRejectsMissingAndChangedSelectedFullBindingsWithoutAnyRelease() thr var request = (tools.jackson.databind.node.ObjectNode) changed.get("request"); if (field.equals("digestSchemaVersion")) request.put(field, 3); else request.put(field, field.endsWith("Id") ? UUID.randomUUID().toString() : "changed"); - assertThatThrownBy( - () -> - insertRawSelectedFull( - fixture, version, operation, json.writeValueAsString(changed), participants)) - .isInstanceOf(DataAccessException.class); + assertSelectedFullMutationRejected( + fixture, + version, + operation, + json.writeValueAsString(changed), + participants, + "selected publication is absent, sealed, or changed"); } for (String field : java.util.List.of( @@ -654,26 +662,32 @@ void sqlGuardRejectsMissingAndChangedSelectedFullBindingsWithoutAnyRelease() thr "appliedResultBytesBase64")) { var changed = (tools.jackson.databind.node.ObjectNode) json.readTree(original); changed.remove(field); - assertThatThrownBy( - () -> - insertRawSelectedFull( - fixture, version, operation, json.writeValueAsString(changed), participants)) - .isInstanceOf(DataAccessException.class); + assertSelectedFullMutationRejected( + fixture, + version, + operation, + json.writeValueAsString(changed), + participants, + "selected publication is absent, sealed, or changed"); } - assertThatThrownBy(() -> insertRawSelectedFull(fixture, version, operation, original, "[]")) - .isInstanceOf(DataAccessException.class); + // Keep the original operation-bound evidence so participant-specific checks remain reachable. + assertSelectedFullMutationRejected( + fixture, + version, + operation, + original, + "[]", + "selected release requires all five participant owners"); var changedParticipants = (tools.jackson.databind.node.ArrayNode) json.readTree(participants); ((tools.jackson.databind.node.ObjectNode) changedParticipants.get(0)) .put("contentDigest", "c".repeat(64)); - assertThatThrownBy( - () -> - insertRawSelectedFull( - fixture, - version, - operation, - original, - json.writeValueAsString(changedParticipants))) - .isInstanceOf(DataAccessException.class); + assertSelectedFullMutationRejected( + fixture, + version, + operation, + original, + json.writeValueAsString(changedParticipants), + "selected participant differs from commit/digest/schema"); assertThat(bundleCount(fixture.dsl())).isZero(); assertThat(sourceRow(fixture.dsl(), "game", owner.getId())).isEqualTo(gameBefore); assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); @@ -701,6 +715,37 @@ void sqlGuardRejectsMissingAndChangedSelectedFullBindingsWithoutAnyRelease() thr assertThat(bundleCount(fixture.dsl())).isEqualTo(1); } + private void assertSelectedFullMutationRejected( + Fixture fixture, + Version version, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation, + String evidence, + String participants, + String rejectionMessage) { + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .executeWithoutResult( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> { + insertRawSelectedFull( + fixture, version, operation, evidence, participants); + return fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId( + operation.tenantKey(), operation.versionId()) + .orElseThrow(); + }))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining(rejectionMessage); + } + /** Actual GDS owner selection/captures with explicitly stipulated remote Account/World input. */ private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation selectedFullOperation(Fixture fixture, Version version) { From 0d0b8bf08998582be116005aa59b8462f9c81259 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 02:45:38 +1300 Subject: [PATCH 61/61] Align asset runbook and ability authoring with current owner contracts --- .../ability-action-tools.md | 11 ++-- ...system-architecture-asset-store-runbook.md | 64 +++++++------------ 2 files changed, 29 insertions(+), 46 deletions(-) diff --git a/design/architecture/microservices/game-design-service/ability-action-tools.md b/design/architecture/microservices/game-design-service/ability-action-tools.md index d938afe9f5..9d0bf11857 100644 --- a/design/architecture/microservices/game-design-service/ability-action-tools.md +++ b/design/architecture/microservices/game-design-service/ability-action-tools.md @@ -1,15 +1,14 @@ # Ability & Action Design Tools -This document outlines the editors for defining abilities, actions, and combat mechanics. The tooling is part of the Game Design Service and pushes finalized data to the [Game Logic Service](../game-logic-service/README.md) during version publishing. +This document outlines the Game Design editors for authored ability and action inputs. Game Design owns these authored inputs, their revision history, and the frozen source-bound rule inventory. Game Logic owns validation and immutable retention of the selected inventory through authenticated intake, then consumes the rules from the published, pinned release at runtime. The owner handoff and publication boundary are defined by [Game Design Version Control](version-control.md#selected-full-publication-profile) and [Game Logic Runtime and Data](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake). The publish workflow is part of the durable control-plane workflow described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). ## Implementation Status -The current proven behavior is stable-reference validation against the exact published base version for the plugin publication path. `abilitySchemaDigest` is persisted in plugin metadata and exposed by the publication read, but dedicated Game Logic-owned release-attested ability-schema validation remains target-state and unproved. Current plugin publication and activation compare the plugin's `abilitySchemaDigest` with the published `AUTOMATION_SCRIPTING` aggregate participant digest; that aggregate comparison is not a dedicated ability-schema attestation. Script-patch publication does not currently enforce same-tenant published-base identity, and launch resolution does not currently prove same-base published patch identity or Automation `READY`; those are implementation gaps. Exact `scriptPinEpoch` propagation and same-version old-epoch rejection at runtime handoff are target-state and remain unproved; this design-time editor does not establish that runtime proof. See the [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#script-transition-reconciliation) and [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). +The selected gameplay-rule intake and receipt path remain standalone and unregistered, and public fresh/PENDING full-version publication denies before mutation; see the [gameplay-rule retention tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) and [Game Authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation). The current proven behavior is stable-reference validation against the exact published base version for the plugin publication path. `abilitySchemaDigest` is persisted in plugin metadata and exposed by the publication read, but dedicated Game Logic-owned release-attested ability-schema validation remains target-state and unproved. Current plugin publication and activation compare the plugin's `abilitySchemaDigest` with the published `AUTOMATION_SCRIPTING` aggregate participant digest; that aggregate comparison is not a dedicated ability-schema attestation. Script-patch publication does not currently enforce same-tenant published-base identity, and launch resolution does not currently prove same-base published patch identity or Automation `READY`; those are implementation gaps. Exact `scriptPinEpoch` propagation and same-version old-epoch rejection at runtime handoff are target-state and remain unproved; this design-time editor does not establish that runtime proof. See the [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#script-transition-reconciliation) and [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). -Data entered in these editors is stored as revisions using the `SaveRevision` gRPC call defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). -Finalized versions are published with `PublishVersion` so the Game Logic Service can load the rules as part of the cross-service publish workflow described in the [Game Design Service Architecture](README.md). +Data entered in these editors is stored as Game Design revisions using the `SaveRevision` gRPC call defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). `PublishVersion` coordinates validation and finalization of existing owner data; it does not copy or repair authored rules in Game Logic. The exact selected inventory is handed to Game Logic through its authenticated source-intake operation before the publication digest gate, as defined by the owner contracts linked above. Ability definitions use a structured schema delivered through the API. @@ -121,7 +120,7 @@ Example: if an `onInterval` combat-support handler can branch into at most eight At runtime, a published game version ties together: -- Ability/action definitions owned by the Game Logic Service. +- Ability/action definitions authored by Game Design and consumed by Game Logic from the published, pinned release. - Script and plugin patch versions owned by the Automation & Scripting Service. Within a given published game version: @@ -165,7 +164,7 @@ From an observability perspective, live script and plugin invocations (`isDryRun 1. Abilities and actions are created in the web UI and saved via `SaveRevision`. 2. Designers can group related abilities into categories for organization. 3. Each revision becomes part of a published version through `PublishVersion`. -4. When a version is published, abilities are copied to the Game Logic Service using the `version_id`. +4. Game Logic validates and immutably retains the exact source-bound ability/action selection through authenticated intake before the publication digest gate; `PublishVersion` does not copy or repair these definitions. ## Related Documentation diff --git a/design/architecture/system-architecture-asset-store-runbook.md b/design/architecture/system-architecture-asset-store-runbook.md index 5aa44b6e28..4cf8f36e0a 100644 --- a/design/architecture/system-architecture-asset-store-runbook.md +++ b/design/architecture/system-architecture-asset-store-runbook.md @@ -2,28 +2,26 @@ This runbook describes operational procedures for the **asset store** backing game content (binary design assets such as icons, audio, themes, and exported bundles). -For the architecture of asset storage, see `design/architecture/microservices/game-design-service/asset-storage.md`. +The canonical contract is [Asset Storage Setup](./microservices/game-design-service/asset-storage.md). Game Design owns publication coordination, release descriptors, asset lifecycle, CAS state, and purge eligibility. Platform Operations owns MinIO/object-storage, CDN, credentials, availability, and delivery infrastructure. Operators use the Game Design control-plane evidence for lifecycle decisions; bucket listings and CDN responses are not lifecycle authority. ## Implementation Status -- `CanDeleteVersionAssets`, `GetVersionAssetArtifactState`, `RepairPublishedVersionAssets`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `GetVersionAssetPurgeStatus` are live Game Design control-plane APIs. The `version_asset_artifact` proof row currently records lifecycle state, state epoch, manifest hash, exported version number, and exported manifest asset keys. In the current first slice, `RepairPublishedVersionAssets` repairs ordinary assets from `game_assets.data` to those persisted exported version-scoped keys only while the process-local frozen version selection remains available; the proof row alone is not restart-safe, and an unavailable selection fails closed with `REPAIR_VERSION_SCOPE_UNAVAILABLE`. -- Content-addressed private-candidate publication and producer-owned derived-artifact handoff remain target-state. The current first slice still repairs ordinary bytes from `game_assets.data`, exports version-scoped objects, and persists a narrower `published_release_bundle` that lacks the complete target manifest-schema and mandatory actual-byte artifact-digest fields. -- The live `TombstoneVersionAssets` implementation accepts only `FAILED` and `PURGE_FAILED`; target tombstoning of an eligible retired `PUBLISHED` release is not implemented. The runbook must fail closed for that path rather than claim the current API supports it. -- The target failed-candidate path requires the Game Design-owned, idempotent `AbandonFailedVersionAssets` record/read proof bound to the caller tenant, `FAILED` version/artifact epochs, request identity/digest, and no release reachability. That abandonment record/API is not implemented; the current tombstone path does not enforce it. -- The current `CanDeleteVersionAssets` implementation has a fail-open gap: when the artifact exists but no caller-tenant version authority exists (including when only a wrong-tenant row exists), and no caller-tenant release bundle remains, it can return `deletable=true`. Operators must treat both absent and wrong-tenant-only authority as non-eligible and must not tombstone or purge until this guard is closed; the owning target contract and focused proof are tracked in [Asset Storage](./microservices/game-design-service/asset-storage.md#deletion-eligibility-authority). -- Lifecycle CAS/lock serialization described below is target-only. The current repositories compare artifact/Version epochs in service memory and then update each row by ID without an epoch predicate or affected-row check; neither update is concurrency-safe and neither proves serialization against a competing lifecycle writer. This blocks using `expectedVersionStateEpoch` as durable abandonment/retirement invalidation proof. -- The live `CompareAndSetVersionState` operation has an additional transition-safety gap: it accepts any non-null lifecycle enum after its in-memory epoch check, without requiring a committed release bundle/artifact for `DRAFT -> PUBLISHED` or enforcing active-instance/template/in-flight-activation predicates before retirement. Operators must not treat this API as activation- or retirement-safe until the legal transition matrix and focused proof are implemented. -- The target destructive lifecycle operations share the ADR 0048 owner-local operation envelope and durable result ledger: caller-supplied operation/workflow identity, canonical `mutationDigest/v1`, exact replay, and `IDEMPOTENCY_CONFLICT` for changed input. The current first slice has no shared ledger/digest contract; `BeginPurgeVersionAssets` still mints a random workflow ID, so lost responses cannot be reliably replayed. -- Purge failure status is not currently durable: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard the markers after object deletion. A resulting `PURGE_IN_PROGRESS` row has no reliable resume evidence until an independent durable failure/reconciliation boundary and focused deletion/post-delete-save proof are added. -- If publish fails after `published_release_bundle` may have committed, target recovery reads back bundle/attestation state and never deletes Version as compensation. The current catch path still attempts that delete; the non-cascading bundle foreign key can make the delete fail, so the promised terminal result is not reliable. -- The current first slice has one `ASSET_STORE_ENDPOINT` used by the S3 client and generated manifest URLs; it does not implement the target private-origin/public-delivery split or `ASSET_STORE_PUBLIC_BASE_URL`. The current Gateway has no `/assets/**` route or asset-store route ID, and private MinIO is not public delivery; target `/assets/**` delivery remains deferred pending a separate approved public origin/provisioner. +The canonical current implementation and remaining lifecycle gaps are maintained in [Asset Storage Setup](./microservices/game-design-service/asset-storage.md#implementation-status). Operators must distinguish the implemented source and object-writer checks from physical deployment proof: + +- Repair reads the durable per-version export snapshot twice and compares the selections. It reads the retained export candidate, stages and verifies the original source bytes, and checks the candidate against the published release attestation before shared object writes. Missing or mismatched evidence fails closed; repair does not fall back to a new tenant-wide selection after process loss. +- The exporter writes schema-versioned manifests and content-addressed artifact objects, uses conditional object creation, and verifies exact byte readback. These code paths do not establish physical S3/MinIO proof, a deployed public origin, complete release-attestation transport, global publication/purge fencing, or producer-owned derived-artifact handoff. +- Purge eligibility requires an existing caller-tenant `RETIRED` Version, including when no release bundle remains. Artifact-row updates use an epoch predicate and require one affected row, but Version lifecycle serialization and the complete reachability fence remain incomplete. State-changing `CompareAndSetVersionState` requests fail closed; that API cannot substitute for retirement. +- Prefix-based object deletion is hard-disabled with `CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED`. The exposed purge workflow is not a supported physical deletion procedure. Destructive-operation replay, durable purge-failure reconciliation, failed-candidate abandonment and retired-release tombstoning remain incomplete; preserve their owner-defined stop conditions. +- Private publish-failure handling retains the Version row and marks failure only after exact owner-local absence or empty staged-candidate readback. Committed, partial, mismatched or ambiguous evidence remains pending for reconciliation. This does not prove external-write recovery or make fresh full-version publication ingress available. +- Upload ingress refuses before file access or persistence because Account commit-bound authority is not wired. Existing source bytes remain retained. Generated links use a separately validated public base URL, but no public `/assets/**` origin, Gateway route or approved provisioner is implemented. Private MinIO remains private storage. +- Production attestation and lifecycle reads authenticate their exact candidate peers and deny before owner access pending genuine operation-specific authority. The separate operator-diagnostic read path remains unimplemented; source-local repair and readback code does not authorize an operator RPC invocation. See [launch and attestation read authorization](./microservices/game-design-service/version-control.md#launch-and-attestation-read-authorization-target-state). ## Health Checks - Monitor storage availability, latency, and error rates. -- Verify supported Game Design uploads and the persisted Game Design artifact/bundle metadata reads used by the current repair path. Game Design does not currently expose a version-asset object-store GET/HEAD or byte-readback operation; current repair re-exports from the process-local frozen snapshot and fails closed after process loss. Client-facing asset download remains target-only because the approved public `/assets/**` origin is not implemented. +- Preserve available owner-local artifact, snapshot, candidate and bundle evidence for an independently authorized investigation; current production read denial is not a health-check bypass. The internal exporter performs exact object-byte readback, but there is no client-facing asset download or operator object-byte GET/HEAD API. Upload admission remains denied, and public delivery remains unproved. Do not use a publication or repair mutation as a health probe. ## Incident Handling @@ -33,7 +31,7 @@ Game Design owns publication coordination, release descriptors, asset lifecycle, 2. **Degraded Performance** - Monitor throughput and latency; consider scaling the asset store or caching layers if documented. 3. **Data Integrity Concerns** - - **Target-state integrity check:** Verify the attested manifest digest and mandatory per-object SHA-256 content digests against delivery evidence. Missing object digests, mutable delivery keys, or an unattested manifest are publish contract violations; storage availability never makes a candidate launchable. The current first slice exposes only persisted `manifestHash`, exported manifest asset keys/version, and artifact/bundle metadata reads; it has no Game Design object-byte GET/HEAD or readback operation, and its narrower release bundle has no `artifactDigests[]`, so operators must not claim current actual-byte attestation from this check. + - **Target-state integrity check:** Verify the attested manifest digest and mandatory per-object SHA-256 content digests against delivery evidence. Missing object digests, mutable delivery keys, or an unattested manifest are publish contract violations; storage availability never makes a candidate launchable. The current exporter retains content-addressed candidate proofs and performs internal exact-byte readback. The release-bundle transport still lacks the complete target `artifactDigests[]`; operators must not synthesize missing attestation fields or treat internal readback as public delivery proof. - Coordinate with backup and recovery procedures if persistent corruption is suspected. ## MinIO Deployment and Configuration @@ -93,11 +91,11 @@ When using a self-hosted MinIO cluster as the asset store: - Once the trusted bootstrap has provisioned `firemud-assets-writer`, the Game Design Service is the **sole writer** to the asset bucket and uses `ASSET_STORE_*` environment variables to export assets and manifests during publish workflows. Target runtime services and clients consume published assets via CDN or gateway URLs derived from the manifest; they do not write directly to the bucket. The current private MinIO endpoint is not public delivery. - Keep the bucket private. The gateway or CDN origin uses authenticated object-store credentials and exposes only attested immutable published objects; private staging, quarantine, `FAILED`, and `EXPORTED_UNATTESTED` objects must not be publicly readable. - `ASSET_STORE_ENDPOINT` is the private authenticated MinIO/S3 API used by Game Design reads and writes, for example `http://minio:9000` inside the cluster. It is never the public gateway delivery URL. - - The target split uses `ASSET_STORE_PUBLIC_BASE_URL=https:///assets` only to generate public manifest links. That setting is not implemented in the current single-endpoint first slice; target `/assets/**` delivery remains pending a separate approved public origin/provisioner. Operators must not compensate by granting anonymous bucket-wide access. Any future public origin must expose only attested immutable published objects. + - `ASSET_STORE_PUBLIC_BASE_URL=https:///assets` generates manifest links separately from the private endpoint. The exporter validates its HTTPS `/assets` shape and rejects a host alias of the private endpoint; this setting does not deploy or authorize an origin. Target `/assets/**` delivery remains pending a separate approved public origin/provisioner. Operators must not compensate by granting anonymous bucket-wide access. Any future public origin must expose only attested immutable published objects. - Keep validation paths distinct: an unauthenticated GET to the private `ASSET_STORE_ENDPOINT` must be rejected, while a public-origin delivery test may request only an attested immutable published object. 5. **Scope of stored data** - The asset store holds only binary design-time assets and version-scoped `manifest.json` files managed by the Game Design Service. Logical world and entity templates remain in PostgreSQL schemas owned by World Management, Entity Management, and related domain services as described in their architecture documents; they are **not** stored in the object store. + The asset store holds binary design assets and schema-versioned manifests at content-addressed keys managed by the Game Design Service. The retained per-version snapshot and candidate bind the exact selected artifacts. Logical world and entity templates remain in PostgreSQL schemas owned by World Management, Entity Management, and related domain services as described in their architecture documents; they are **not** stored in the object store. 6. **Removing published versions** @@ -109,15 +107,15 @@ When using a self-hosted MinIO cluster as the asset store: - **Target-state procedure only:** For a published/release artifact, complete the canonical `RetireVersion` workflow before calling `CanDeleteVersionAssets(tenantId, versionId)`. It must leave the caller-tenant version authority in **`RETIRED`** state while removing launchability: no `game_instances` rows may reference the `version_id` as `runtime_version`, and no canonical Game Design release/version/launch descriptor may resolve that version for a new launch. Retirement does not delete the version authority or immutable release attestation; `GetPublishedReleaseBundle(tenantId, versionId)` remains queryable for lifecycle and reachability proof. The legacy untenant-qualified `game_manifest` is diagnostic/disposition-only and cannot gate retirement or launch. Retirement is necessary but not sufficient for asset deletion. No safe `RetireVersion` operation exists in the current service. Operators must stop rather than use `CompareAndSetVersionState` as a substitute, because that operation is not retirement-safe. An abandoned failed candidate follows the separate failed-candidate eligibility path below and must not be converted to `RETIRED` merely to enable purge. - Retired eligibility must also account for **design-time dependencies**: the version must not be referenced by any game templates. Operators should validate that no normalized `game_template_*_ref` rows in the Game Design Service still reference `(tenantId, versionId)` before requesting the corresponding purge through Game Design. - - Asset deletion eligibility must account for design-history reachability as well as version mappings. Use the Game Design control-plane check `CanDeleteVersionAssets(tenantId, versionId)` that validates no non-Retired `version_asset` references remain, no reachable `revision_asset` / branch references require retained bytes, and no template or launch metadata still points to the version prefix. Until the current fail-open guard is closed, a result for an artifact with no caller-tenant matching version authority—including a wrong-tenant-only row—must be treated as non-eligible regardless of the API's current boolean result. + - Asset deletion eligibility must account for design-history reachability as well as version mappings. Use the Game Design control-plane check `CanDeleteVersionAssets(tenantId, versionId)` that validates no non-Retired `version_asset` references remain, no reachable `revision_asset` / branch references require retained bytes, and no template or launch metadata still points to the version prefix. The current API fails closed when caller-tenant Version authority is absent, including a wrong-tenant-only row. A positive eligibility result still does not establish the complete global reachability/publication fence or authorize object deletion. - Before purge or repair, read `GetVersionAssetArtifactState(tenantId, versionId)` and treat its `artifactState`, `stateEpoch`, `manifestHash`, `exportedVersionNumber`, and exported manifest asset keys as the authoritative proof row. Do not infer lifecycle state from bucket listings. - - Do not run deletion as a separate check + manual delete sequence. The target order is `TombstoneVersionAssets(...)` first: it performs the pre-tombstone caller-tenant authority, retirement-or-abandonment, frozen-proof, and reachability checks and its CAS transition. For an abandoned failed candidate, record durable proof with `AbandonFailedVersionAssets(...)` before tombstoning; for an eligible retired `PUBLISHED` release, no abandonment proof is required. Reload the artifact row, run post-tombstone `CanDeleteVersionAssets(tenantId, versionId)`, then call `BeginPurgeVersionAssets(...)` with the caller-supplied workflow identity. Current implementation/order drift includes a fail-closed pre-tombstone state check: `CanDeleteVersionAssets` rejects pre-tombstone `FAILED`/`PUBLISHED`, while tombstone lacks the target authority checks and retired `PUBLISHED` transition. Separately, the current `CanDeleteVersionAssets` authority lookup can fail open when no caller-tenant version row exists, including a wrong-tenant-only row; that remains a non-eligibility warning until the guard is fixed. + - Do not run deletion as a separate check + manual delete sequence. The target order is `TombstoneVersionAssets(...)` first: it performs the pre-tombstone caller-tenant authority, retirement-or-abandonment, frozen-proof, and reachability checks and its CAS transition. For an abandoned failed candidate, record durable proof with `AbandonFailedVersionAssets(...)` before tombstoning; for an eligible retired `PUBLISHED` release, no abandonment proof is required. Reload the artifact row, run post-tombstone `CanDeleteVersionAssets(tenantId, versionId)`, then call `BeginPurgeVersionAssets(...)` with the caller-supplied workflow identity. Current implementation/order drift includes a fail-closed pre-tombstone state check: `CanDeleteVersionAssets` rejects pre-tombstone `FAILED`/`PUBLISHED`, while tombstone lacks the target authority checks and retired `PUBLISHED` transition. The current `CanDeleteVersionAssets` authority lookup rejects absent or wrong-tenant-only Version authority; retain that denial while completing the remaining lifecycle checks. - Operators must verify the persisted artifact lifecycle row (`version_asset_artifact`) is `TOMBSTONED` before issuing purge actions. **Target-state procedure only:** `BeginPurgeVersionAssets` must re-check eligibility and transition state to `PURGE_IN_PROGRESS` before bytes are removed, and `FinalizePurgeVersionAssets` must transition to retained terminal state `PURGED` after bytes are removed. The current path is subject to the non-atomic implementation-status gap above; do not infer lifecycle state solely from object-store contents. - `EXPORTED_UNATTESTED` means bytes were exported but publish did not complete. Such prefixes are not launchable and must be repaired or failed through the documented workflow; operators must not treat them as equivalent to `PUBLISHED`. - - Published-asset discovery and post-tombstone deletion recheck use `CanDeleteVersionAssets(tenantId, versionId)` and `GetVersionAssetArtifactState(tenantId, versionId)`; pre-tombstone authority/reachability belongs to `TombstoneVersionAssets`. The `version_asset` mapping checks are target-state because the current implementation has no mapping authoring path; operators must never delete referenced objects or bypass the Game Design reachability/CAS lifecycle. In particular, absence of a caller-tenant matching version authority, including a wrong-tenant-only row, remains a fail-closed stop condition until the current guard is remediated. - - If object-store contents drift from the database (for example missing objects for a still-published version), do not use the current `RepairPublishedVersionAssets` path for Published/Active repair: it writes objects and `manifest.json` before `VersionAssetArtifactServiceImpl` performs the exact repair-match check, so a mismatch can write or overwrite live prefix keys before returning `REPAIR_ATTESTATION_MISMATCH`. Keep the release closed and escalate until repair either fails closed before every write or uses independently verified exact selection; process loss also remains `REPAIR_VERSION_SCOPE_UNAVAILABLE` for Published/Active, and a RETIRED version must not fall through to a fresh tenant-wide snapshot. The target content-addressed candidate and per-object digest procedure is defined in `asset-storage.md`. - - The target `RepairPublishedVersionAssets(tenantId, versionId, expectedArtifactStateEpoch, repairWorkflowId)` operation may be used only after that pre-write exact-selection gate exists. It must produce deterministic `REPAIR_ATTESTATION_MISMATCH` or `ASSET_ARTIFACT_STATE_CONFLICT` outcomes and never mutate attested bytes on a mismatch; until then, operators must not recommend or invoke the current path as a repair procedure. - - **Target-state content-addressed repair:** Because Published/Active versions are immutable, the target workflow must produce bit-for-bit identical bytes matching the existing `published_release_bundle` attestation returned by `GetPublishedReleaseBundle(tenantId, versionId)`, verify mandatory per-object actual-byte digests, and restore only exact immutable content-addressed objects. Producer-owned derived artifacts must come from their immutable producer contracts. If any required artifact cannot reproduce the attested bytes, fail closed rather than “fixing” the published version in place; this target procedure does not describe the current first-slice version-scoped repair path above. + - Published-asset discovery and post-tombstone deletion recheck use `CanDeleteVersionAssets(tenantId, versionId)` and `GetVersionAssetArtifactState(tenantId, versionId)`; pre-tombstone authority/reachability belongs to `TombstoneVersionAssets`. Current `version_asset` mappings come from the synchronized ordinary source snapshot, while direct association remains denied. Operators must never delete referenced objects or bypass the Game Design reachability/CAS lifecycle; absent or wrong-tenant-only Version authority is a fail-closed stop condition. + - If object-store contents drift from the database, preserve the artifact, candidate, snapshot and release-attestation evidence. The current repair implementation verifies the retained selection and exact attestation before object writes, then conditionally writes and reads back content-addressed objects. It does not recreate missing selection or candidate evidence. Physical object-store and global-fence proof remain unavailable; escalate rather than using manual overwrite or assuming this source-level correction qualifies a deployment. + - For `RepairPublishedVersionAssets(tenantId, versionId, expectedArtifactStateEpoch, repairWorkflowId)`, retain exact artifact epoch, caller-tenant scope and the original attestation. A pre-write mismatch fails closed, and an artifact epoch conflict requires owner readback. Code-level checks do not replace qualification of the actual object-store, failure and recovery boundary before operational use. + - **Target-state content-addressed repair:** Because Published/Active versions are immutable, the target workflow must produce bit-for-bit identical bytes matching the existing `published_release_bundle` attestation returned by `GetPublishedReleaseBundle(tenantId, versionId)`, verify mandatory per-object actual-byte digests, and restore only exact immutable content-addressed objects. Producer-owned derived artifacts must come from their immutable producer contracts. If any required artifact cannot reproduce the attested bytes, fail closed rather than “fixing” the published version in place. The implemented ordinary-asset writer checks described above cover only their named source boundary, not the complete producer, deployment or global-fence contract. - **Target-state workflow only:** Route deletion through pre-tombstone `TombstoneVersionAssets(...)`, post-tombstone `CanDeleteVersionAssets(tenantId, versionId)`, `BeginPurgeVersionAssets(tenantId, versionId, expectedArtifactStateEpoch, purgeWorkflowId)`, and `FinalizePurgeVersionAssets(...)`. Every mutation carries the shared ADR 0048 operation envelope and caller-supplied workflow identity. The target workflow re-checks reachability and CAS state before deletion, and the lifecycle APIs retain terminal metadata after physical bytes are removed. The current path is subject to the order, idempotency, and non-atomic implementation gaps above. - Direct object-store commands such as `mc rm` are outside the supported lifecycle. Incident recovery may preserve or isolate evidence for escalation, but it must not bypass the Game Design reachability/CAS APIs or claim to finalize lifecycle state. @@ -126,31 +124,17 @@ When using a self-hosted MinIO cluster as the asset store: Occasionally the asset-export step of `PublishVersion` may fail in a way that leaves a version incomplete or unusable: -- **Target-state workflow only:** When the Game Design publication workflow - coordinated by Temporal marks a version as **Failed**, the canonical Game - Design release/version/launch descriptor and attestation surfaces must not - make it launchable, and operators must not attempt to start game instances - against it. Any retained legacy `game_manifest` row is - diagnostic/disposition-only and is neither evidence nor a launch gate. The - current first slice executes publication synchronously when Temporal is - disabled; its failure handling is incomplete as documented above and is not - equivalent to durable Temporal failure coordination. -- **Target-state only:** Failed versions may have partially written candidates in a private quarantine namespace; do not delete those candidates manually. If there is no intention to retry publish, use the target Game Design `AbandonFailedVersionAssets(...)` operation to record durable abandonment, then invoke pre-tombstone `TombstoneVersionAssets(tenantId, versionId, expectedArtifactStateEpoch, tombstoneWorkflowId)` to prove caller-tenant `FAILED` authority, frozen proof, and no reachability before its CAS transition. **Target-state only:** the abandonment record and target authority/CAS transition are not implemented. The current exporter writes directly to the private `tenant/version/` prefix and has no separate quarantine namespace. +- **Target-state workflow only:** When the Game Design publication workflow coordinated by Temporal marks a version as **Failed**, the canonical Game Design release/version/launch descriptor and attestation surfaces must not make it launchable, and operators must not attempt to start game instances against it. Any retained legacy `game_manifest` row is diagnostic/disposition-only and is neither evidence nor a launch gate. Current fresh and `PENDING` full-version publication ingress is denied; the private owner-local failure mechanics described above do not establish operational Temporal failure coordination. +- **Target-state only:** Failed versions may have partially written candidates in a private quarantine namespace; do not delete those candidates manually. If there is no intention to retry publish, use the target Game Design `AbandonFailedVersionAssets(...)` operation to record durable abandonment, then invoke pre-tombstone `TombstoneVersionAssets(tenantId, versionId, expectedArtifactStateEpoch, tombstoneWorkflowId)` to prove caller-tenant `FAILED` authority, frozen proof, and no reachability before its CAS transition. **Target-state only:** the abandonment record and target authority/CAS transition are not implemented. The current exporter uses content-addressed keys, but complete private candidate isolation and the abandonment workflow remain unimplemented. - **Target-state only:** Failed or `EXPORTED_UNATTESTED` candidates are never launchable, never used as fallback, and never repaired in place while runtime admission continues. A retry creates a new approved workflow attempt and either completes a fully attested `PUBLISHED` release or remains non-launchable. In the current first slice, a failed `PublishAttempt` is terminal for that workflow identity and no retry-publish or repair-version orchestration is exposed; only the published-artifact repair API exists. - The canonical lifecycle states, transitions, bundle-readback rules, and target serialization fence are defined in [Asset Storage Setup](./microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). Operators must preserve these local consequences: - `FAILED` and `EXPORTED_UNATTESTED` remain non-launchable and non-fallback; retry uses the documented workflow, while failed-candidate purge requires caller-tenant `FAILED` authority plus durable explicit abandonment proof. - A published/release purge requires caller-tenant `RETIRED` authority, and target `PUBLISHED -> TOMBSTONED -> PURGE_IN_PROGRESS -> PURGED` proceeds only through the control-plane APIs after eligibility and epoch reload. `PURGED` retains lifecycle metadata; physical deletion never removes the artifact row. - A failed-candidate purge uses the separate abandoned-candidate path and must not invent a `FAILED -> RETIRED` transition. `PURGE_FAILED` retry/resume and abandonment remain explicit workflow actions. - - **Target-state only:** lifecycle transitions and publication/failure readback are CAS/lock serialized for both artifact and Version rows. The current row-ID updates have no database epoch predicate or affected-row check, so they must not be treated as concurrency protection; CAS loss requires fresh readback and approved workflow retry, never manual object-store edits. The target owner ledger also supplies exact operation replay/conflict handling under ADR 0048; the current random-only Begin workflow identity does not. + - **Target-state only:** lifecycle transitions and publication/failure readback are CAS/lock serialized for both artifact and Version rows. Artifact updates have a database epoch predicate and affected-row check; Version lifecycle and global-fence proof remain incomplete, so that artifact check must not be treated as complete concurrency protection; CAS loss requires fresh readback and approved workflow retry, never manual object-store edits. The target owner ledger also supplies exact operation replay/conflict handling under ADR 0048; the current random-only Begin workflow identity does not. - Preferred recovery is to: - Investigate and fix the underlying issue (for example missing assets or permission errors). - - **Target-state only:** Trigger a documented “retry publish” or “repair version” workflow through the Game Design Service, the publication workflow owner, so its Temporal-coordinated workflow re-runs the asset export step and transitions the version back to Draft/Published as appropriate. If the request starts in Logging & Admin, that service is only the audited operator facade forwarding the typed request to Game Design; it does not own or execute publication. No retry-publish or failed-candidate repair-version operation is currently exposed by Game Design or Logging & Admin. Game Design does expose `RepairPublishedVersionAssets(...)` for an already-published artifact; it is exact-bytes repair against the existing release attestation, not a retry of failed publication. The current first slice writes a plain filename-to-URL - `manifest.json` map without a `schemaVersion` field. The target manifest - contract adds an explicit schema version; until that target is implemented, - operators must not claim current schema-versioned manifest discovery. For - Published/Active releases, do not use repair to move the release to a newer - manifest schema version; repair is exact-bytes only unless a separate - re-attestation workflow is explicitly defined. + - **Target-state only:** Trigger a documented “retry publish” or “repair version” workflow through the Game Design Service, the publication workflow owner, so its Temporal-coordinated workflow re-runs the asset export step and transitions the version back to Draft/Published as appropriate. If the request starts in Logging & Admin, that service is only the audited operator facade forwarding the typed request to Game Design; it does not own or execute publication. No retry-publish or failed-candidate repair-version operation is currently exposed by Game Design or Logging & Admin. Game Design does expose `RepairPublishedVersionAssets(...)` for an already-published artifact; it is exact-bytes repair against the existing release attestation, not a retry of failed publication. The current exporter writes a schema-versioned manifest with per-artifact digests and content-addressed keys. This does not supply missing release-bundle transport fields or qualify public manifest discovery. For Published/Active releases, do not use repair to move the release to a newer manifest schema version; repair is exact-bytes only unless a separate re-attestation workflow is explicitly defined. - For Published/Active versions, treat the workflow as exact-bytes repair only: it must verify the current `GetPublishedReleaseBundle` attestation and fail if the regenerated bytes would change the attested `manifestHash`. - If clean-up is required after deciding to abandon a Failed version, first record the durable abandonment proof with `AbandonFailedVersionAssets(...)`, then use pre-tombstone `TombstoneVersionAssets(...)`, post-tombstone `CanDeleteVersionAssets(tenantId, versionId)`, and the **target-state CAS-guarded** `BeginPurgeVersionAssets(..., purgeWorkflowId)` / `FinalizePurgeVersionAssets(...)` workflow. The current abandonment, order, idempotency, and CAS paths are not implemented; do not remove the corresponding prefix directly.