From e9462c944c63c266ee7b487f881d261e16352e6a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 10:32:22 +1300 Subject: [PATCH 01/22] Prepare original StartSession evidence continuation and exact owner pins --- .../game-session-service/api-contracts.md | 6 + .../player-access-and-session.md | 2 + ...start_session_operator_authorization.proto | 119 ++ .../game-design/v1/game_design_service.proto | 100 ++ ...session_template_association_service.proto | 101 ++ .../v1/world_management_service.proto | 113 ++ .../common-platform-core/build.gradle.kts | 1 + ...sionRedeemedOperationProjectionClient.java | 330 +++++ ...uthoredWorldLaunchDescriptorGrpcCodec.java | 533 +++++++ ...thoredWorldReleaseAttestationEvidence.java | 153 +- ...GameDesignPublicationTerminalEvidence.java | 16 +- ...StartSessionLaunchDescriptorGrpcCodec.java | 239 ++++ ...tartSessionLaunchDescriptorReadClient.java | 164 +++ ...tSessionTemplateAssociationReadClient.java | 164 +++ ...essionTemplateAssociationReadEvidence.java | 365 +++++ ...ssionTemplateAssociationReadGrpcCodec.java | 203 +++ ...InstanceLaunchAssociationReadEvidence.java | 128 ++ .../WorldAuthoredSourceIntakeGrpcCodec.java | 534 +++++++ .../WorldPublishedStartLocationEvidence.java | 2 +- ...RedeemedOperationProjectionClientTest.java | 687 +++++++++ ...edWorldReleaseAttestationSelectorTest.java | 502 +++++++ ...tSessionLaunchDescriptorGrpcCodecTest.java | 527 +++++++ ...SessionLaunchDescriptorReadClientTest.java | 294 ++++ ...sionTemplateAssociationReadClientTest.java | 267 ++++ ...nTemplateAssociationReadGrpcCodecTest.java | 295 ++++ ...lishedRealmEntryPolicySetEvidenceTest.java | 2 +- ...ldPublishedStartLocationGrpcCodecTest.java | 5 +- ...anonicalGameInstanceLaunchAssociation.java | 92 ++ ...CanonicalInitialAdmissionLaunchTarget.java | 28 + .../dto/CanonicalRealmCatalogSnapshot.java | 62 + .../CreateCanonicalRealmCatalogRequest.java | 95 ++ ...meInstanceLaunchAssociationRepository.java | 1265 +++++++++++++++++ .../GameSessionAuthoredWorldIntakeDigest.java | 65 + ...eSessionAuthoredWorldSourceRepository.java | 515 +++++++ ...essionCanonicalRealmCatalogRepository.java | 1146 +++++++++++++++ ...onCanonicalStartingInstanceRepository.java | 468 ++++++ ...ssionFreshTenantAssociationRepository.java | 437 ++++++ ...tartSessionLaunchDescriptorRepository.java | 595 ++++++++ ...StartSessionOperatorAttemptRepository.java | 789 ++++++++++ ...tSessionTemplateAssociationRepository.java | 441 ++++++ .../FreshGameSessionTenantAssociation.java | 26 + ...onLaunchDescriptorContinuationService.java | 210 +++ ...__start_session_operator_owner_attempt.sql | 100 ++ ...start_session_template_association_pin.sql | 93 ++ ...8__start_session_launch_descriptor_pin.sql | 61 + ...SessionAssociationReadIntegrationTest.java | 386 +++++ ...chDescriptorRepositoryIntegrationTest.java | 618 ++++++++ ...ratorAttemptRepositoryIntegrationTest.java | 671 +++++++++ ...eAssociationRepositoryIntegrationTest.java | 961 +++++++++++++ ...stanceLaunchAssociationRepositoryTest.java | 89 ++ ...eSessionAuthoredWorldIntakeDigestTest.java | 118 ++ ...SessionLaunchDescriptorRepositoryTest.java | 79 + ...tSessionOperatorAttemptRepositoryTest.java | 64 + ...sionTemplateAssociationRepositoryTest.java | 74 + ...unchDescriptorContinuationServiceTest.java | 554 ++++++++ 55 files changed, 15932 insertions(+), 22 deletions(-) create mode 100644 protos/account/v1/start_session_operator_authorization.proto create mode 100644 protos/game-design/v1/start_session_template_association_service.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V37__start_session_template_association_pin.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 44ed3630df..8fce3878ac 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -127,6 +127,12 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay The current proto and admission-pointer mutation flow remain incomplete against this target. `SetAdmissionPointerRequest` and `ExecutePreparedVersionCutoverRequest` still identify routes by `worldSlug`/`realmSlug` and do not carry durable `realmId`; the persisted/read models and callers have not proved migration to `{tenantId, realmId}`. `StartSessionRequest`, `PauseTicksForScopeRequest`, `ResumeTicksForScopeRequest`, and `GameplayAdmissionPointerMutation` for `SetAdmissionPointer` carry `controlPlaneRequestId` but not `mutationDigest`; those operations must not be reported as ADR-0048-complete until the missing request-field propagation, authorization binding, owner-side digest verification, replay persistence, and focused proof converge together. +#### Restricted original-claim evidence continuation + +Under approved original-claim continuation decision `ae27ed99`, this narrowly bounded owner-internal read/pin continuation is separate from mutating operator RPC execution and does not change the ADR-0048 mutation digest, terminal-result, or retry rules above. It may continue only the exact original attached Account authorization projection and complete original tuple under the same stored, unexpired `PENDING` owner claim, attempt, and fence. Account remains the authority for current authorization: under its [operator-authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references), it must revalidate the original actor, `jti`, current source, reference expiry, and original redeemed attempt. The retained projection is not itself permission for another mutation. + +The continuation is restricted to reading and exact replay of an existing immutable association pin. It must not replay redemption, create or reselect an association, create a claim, attempt, fence, or authorization reference, renew or transfer ownership, mutate domain state, or admit a player. Remote Account/source reads occur outside SQL; Game Session then locks and rechecks the same owner state before returning the association. The actual pin/read statement enforces claim expiry using the database clock. Missing or unattached projections, absent or changed pins, changed tuples, expired claims, and ambiguous outcomes remain reconciliation-only and cannot be treated as authorization or admission. + ### gRPC Outcome Handling Game Session follows the [canonical gRPC outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification). A successfully produced command, control-plane, or read outcome uses its typed response contract; a failure that prevents producing that domain result uses canonical non-OK status with bounded structured details. Game Session preserves stable mutation request identities and reconciles ambiguous timeouts or transport failures before replaying work. Current handlers use a mixture of response-level `ErrorDetail` and transport failures, so exact per-RPC classifications and focused migration proof remain implementation gaps rather than a new service contract. 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 1bd6e7798a..5326d55d5a 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,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +Game Session has an unregistered original-claim evidence-continuation preparation: owner repositories, typed read/pin carriers, before-and-after authenticated Account projection reads outside SQL, and database-clock claim/reference-expiry checks at descriptor pinning. Consolidated Common/Game Session unit and non-container integration checks pass, as do generated-source compilation, formatting, static analysis, and documentation checks. PostgreSQL fixtures cover expiry, exact replay, mismatch, and pin races but remain unexecuted locally without Docker. Genuine Account original-redeemed receiver revalidation and full pointer/audit/live-owner composition remain required; mocked responses do not prove that receiver. This preparation grants no new mutation authorization or admission and does not establish playable closure. The bounded contract is owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). + The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. Account and Common unit checks and Account compile/static-analysis gates passed; the Account integration sources also compiled. Physical fresh-install/V73-upgrade PostgreSQL proof remains pending because the PostgreSQL cases were skipped with Docker disabled; exact scope and counts are recorded in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. The hosted-terms workflow, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898/#2848 and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). Proof qualification for the Account source/currentness cut: the earlier local results above belong to `1f5045fe0a8e66f33f0e6c046f77f099e749c45b`, whose hosted Account physical suite ran 88 cases with 26 failures. The corrected batch passes the consolidated Account check with 636 unit cases, compilation and static analysis, while all 245 unchanged Common unit cases remain green. Its local integration run executed two cases and skipped 83 without Docker; physical fresh-install/V73-upgrade proof remains pending on corrected-head CI. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for exact proof scope and limitations. diff --git a/protos/account/v1/start_session_operator_authorization.proto b/protos/account/v1/start_session_operator_authorization.proto new file mode 100644 index 0000000000..7f781d5515 --- /dev/null +++ b/protos/account/v1/start_session_operator_authorization.proto @@ -0,0 +1,119 @@ +syntax = "proto3"; + +package account.v1; + +import "google/protobuf/timestamp.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Internal mTLS-only Account boundary for the human tenant-admin StartSession authorization flow. +service StartSessionOperatorAuthorizationService { + rpc IssueHumanOperatorAuthorizationReference( + IssueHumanOperatorAuthorizationReferenceRequest) + returns (IssueHumanOperatorAuthorizationReferenceResponse); + rpc RecoverOperatorAuthorizationReference(RecoverOperatorAuthorizationReferenceRequest) + returns (RecoverOperatorAuthorizationReferenceResponse); + rpc RedeemOperatorAuthorization(RedeemOperatorAuthorizationRequest) + returns (RedeemOperatorAuthorizationResponse); + rpc ReadRedeemedOperationProjection(ReadRedeemedOperationProjectionRequest) + returns (ReadRedeemedOperationProjectionResponse); +} + +message IssueHumanOperatorAuthorizationReferenceRequest { + // Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. + bytes canonical_pre_authorization_tuple_bytes = 1; + // Forwarded control-ui token. It is consumed only by Account and is never returned. + string control_ui_jwt = 2; + string reservation_owner_id = 3; + uint64 reservation_claim_fence = 4; + string current_claim_owner_id = 5; + uint64 current_claim_fence = 6; +} + +message RecoverOperatorAuthorizationReferenceRequest { + // Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. + bytes canonical_pre_authorization_tuple_bytes = 1; + string reservation_owner_id = 2; + uint64 reservation_claim_fence = 3; + string current_claim_owner_id = 4; + uint64 current_claim_fence = 5; +} + +message RedeemOperatorAuthorizationRequest { + // Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. + bytes canonical_pre_authorization_tuple_bytes = 1; + // Transient only: sent over authenticated TLS and never persisted by Logging & Admin. + string operator_authorization_reference = 2; + string authorization_reference_fingerprint = 3; + string reservation_owner_id = 4; + uint64 reservation_claim_fence = 5; + string owner_attempt_id = 6; + uint64 owner_fence = 7; +} + +message IssueHumanOperatorAuthorizationReferenceResponse { + string operator_authorization_reference = 1; + string authorization_reference_fingerprint = 2; + google.protobuf.Timestamp expires_at = 3; + bytes authority_evidence_bundle = 4; + AuthorityEvidenceBundleReference bundle_reference = 5; + // Exact Logging/Admin SPIFFE identity verified from the authenticated request TLS peer. + string authenticated_logging_workload_identity = 6; +} + +message RecoverOperatorAuthorizationReferenceResponse { + string operator_authorization_reference = 1; + string authorization_reference_fingerprint = 2; + google.protobuf.Timestamp expires_at = 3; + bytes authority_evidence_bundle = 4; + AuthorityEvidenceBundleReference bundle_reference = 5; + // Exact Logging/Admin SPIFFE identity verified from the authenticated request TLS peer. + string authenticated_logging_workload_identity = 6; +} + +message RedeemOperatorAuthorizationResponse { + string authorization_reference_fingerprint = 1; + bytes authority_evidence_bundle = 2; + string issuance_operation_id = 3; + uint64 issuance_fence = 4; + bool replay = 5; +} + +// Read-only projection of the exact original operation after its owner redemption. +// It contains no JWT or opaque authorization reference. +message ReadRedeemedOperationProjectionRequest { + // Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. + bytes canonical_pre_authorization_tuple_bytes = 1; + string authorization_reference_fingerprint = 2; + string reservation_owner_id = 3; + uint64 reservation_claim_fence = 4; + string owner_attempt_id = 5; + uint64 owner_fence = 6; +} + +message ReadRedeemedOperationProjectionResponse { + string control_plane_request_id = 1; + bytes canonical_pre_authorization_tuple_bytes = 2; + string mutation_digest = 3; + string authorization_reference_fingerprint = 4; + string reservation_owner_id = 5; + uint64 reservation_claim_fence = 6; + // The original redeemer identity authenticated and recorded by Account at redemption. + string authenticated_redeemer_workload_identity = 7; + string owner_attempt_id = 8; + uint64 owner_fence = 9; + google.protobuf.Timestamp reference_expires_at = 10; + google.protobuf.Timestamp redeemed_at = 11; + string issuance_operation_id = 12; + uint64 issuance_fence = 13; + AuthorityEvidenceBundleReference bundle_reference = 14; + bytes authority_evidence_bundle = 15; +} + +message AuthorityEvidenceBundleReference { + string bundle_version = 1; + string source_version = 2; + string source_fence = 3; + string linearization = 4; +} diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index b7739f7145..c59681c8af 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -35,6 +35,9 @@ service GameDesignService { returns (CompareAndSetVersionStateResponse); rpc ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse); + rpc GetLaunchDescriptor(GetLaunchDescriptorRequest) returns (GetLaunchDescriptorResponse); + rpc GetCompleteLaunchBinding(GetLaunchDescriptorRequest) + returns (GetCompleteLaunchBindingResponse); rpc CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse); rpc ApproveTemplateRemapSet(ApproveTemplateRemapSetRequest) @@ -344,6 +347,11 @@ message ResolveLaunchDescriptorRequest { optional int64 source_version_id = 5; optional int64 target_version_id = 6; optional string requested_runtime_flags_json = 7; + string world_slug = 8; + string authored_world_source_operation_id = 9; + string expected_authored_world_source_evidence_digest = 10; + // Canonical source identity is distinct from the retained legacy tenant selector. + string canonical_tenant_id = 11; } message ResolveLaunchDescriptorResponse { @@ -351,6 +359,28 @@ message ResolveLaunchDescriptorResponse { shared.v1.ErrorDetail error = 2; } +message GetLaunchDescriptorRequest { + string request_id = 1; + string canonical_tenant_id = 2; + string world_slug = 3; + string control_plane_request_id = 4; + string expected_request_digest = 5; + string expected_result_digest = 6; +} + +message GetLaunchDescriptorResponse { + string request_id = 1; + LaunchDescriptor launch_descriptor = 2; + shared.v1.ErrorDetail error = 3; +} + +message GetCompleteLaunchBindingResponse { + string request_id = 1; + LaunchDescriptor launch_descriptor = 2; + AuthoredWorldReleaseAttestationEvidence release_attestation = 3; + shared.v1.ErrorDetail error = 4; +} + message CreateTemplateRemapSetRequest { string tenant_id = 1; int64 source_version_id = 2; @@ -491,6 +521,20 @@ message PublishedReleaseBundle { string workflow_status = 14; string workflow_family = 15; repeated string command_definitions = 16; + string published_release_bundle_ref = 17; + string canonical_tenant_id = 18; + string canonical_version_id = 19; + optional int32 manifest_schema_version = 20; + repeated PublishedArtifactDigest artifact_digests = 21; +} + +message PublishedArtifactDigest { + string usage_key = 1; + string artifact_kind = 2; + string immutable_object_key = 3; + string content_digest = 4; + string content_type = 5; + int32 artifact_schema_version = 6; } message LaunchDescriptor { @@ -506,6 +550,61 @@ message LaunchDescriptor { int64 release_bundle_id = 10; string published_release_bundle_ref = 11; string remap_set_id = 12; + AuthoredWorldLaunchDescriptorEvidence authored_world_binding = 13; + string canonical_tenant_id = 14; +} + +message AuthoredWorldLaunchDescriptorEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string control_plane_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string authored_world_source_operation_id = 6; + string authored_world_source_evidence_digest = 7; + int64 game_template_id = 8; + optional string requested_script_patch_version = 9; + optional int64 source_version_id = 10; + optional int64 target_version_id = 11; + optional string requested_runtime_flags_json = 12; + string request_digest = 13; + string launch_descriptor_id = 14; + int64 version_id = 15; + optional string script_patch_version = 16; + string runtime_flags_json = 17; + string generation_config_revision = 18; + int64 version_state_epoch = 19; + int64 release_bundle_id = 20; + string published_release_bundle_ref = 21; + optional string remap_set_id = 22; + string result_digest = 23; +} + +// Separate closed evidence: never extends or reinterprets descriptor/v1. +message AuthoredWorldReleaseAttestationEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string descriptor_result_digest = 3; + string canonical_tenant_id = 4; + string canonical_version_id = 5; + string world_slug = 6; + string authored_world_source_operation_id = 7; + string authored_world_source_evidence_digest = 8; + string launch_descriptor_id = 9; + string published_release_bundle_ref = 10; + int64 version_state_epoch = 11; + string publish_workflow_id = 12; + string commit_id = 13; + repeated ParticipantDigest participant_digests = 14; + string manifest_hash = 15; + int32 manifest_schema_version = 16; + repeated string required_manifest_asset_keys = 17; + repeated PublishedArtifactDigest artifact_digests = 18; + repeated string command_definitions = 19; + string generation_config_revision = 20; + string evidence_digest = 21; + // Closed original World Account/APPLIED/receipt evidence. Absent in schema 1, required in 2/3. + optional bytes world_start_location_evidence = 22; } message TemplateRemapSet { @@ -556,6 +655,7 @@ message ParticipantDigest { string applied_commit_id = 3; string content_digest = 4; int32 digest_schema_version = 5; + optional string ability_schema_digest = 6; } enum VersionLifecycleState { diff --git a/protos/game-design/v1/start_session_template_association_service.proto b/protos/game-design/v1/start_session_template_association_service.proto new file mode 100644 index 0000000000..c183cf045a --- /dev/null +++ b/protos/game-design/v1/start_session_template_association_service.proto @@ -0,0 +1,101 @@ +syntax = "proto3"; + +package game_design.v1; + +import "game-design/v1/game_design_service.proto"; +import "world-management/v1/world_management_service.proto"; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Standalone read-only handoff. Authenticate the exact same-namespace Game Session +// peer before decoding, then independently verify the original redeemed Account +// operation before reading content. This does not authorize source mutation, +// descriptor mutation, World preparation, or admission. +service GameDesignStartSessionTemplateAssociationReadService { + rpc ReadStartSessionTemplateAssociation(ReadStartSessionTemplateAssociationRequest) + returns (ReadStartSessionTemplateAssociationResponse); +} + +// Standalone exact-replay descriptor projection for the existing authorized StartSession flow. +// The server authenticates the same-namespace Game Session workload before decoding or invoking +// the producer. This service is deliberately separate from the read-only association service. +service GameDesignStartSessionLaunchDescriptorService { + rpc ResolveStartSessionLaunchDescriptor(ReadStartSessionTemplateAssociationRequest) + returns (ResolveStartSessionLaunchDescriptorResponse); +} + +message ReadStartSessionTemplateAssociationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical StartSessionPostAuthorizationExecutionTuple bytes. + // No JWT or opaque authorization reference is forwarded here. + bytes canonical_post_authorization_tuple = 4; + string owner_attempt_id = 5; + int64 owner_fence = 6; + // Initial selection has no caller-supplied version override. A retry checks the + // first immutable result already pinned by Game Session; it cannot reselect. + oneof selection { + StartSessionConfiguredTemplateSelection initial_configured = 7; + StartSessionExactTemplateAssociationSelection exact_replay = 8; + } +} + +message StartSessionConfiguredTemplateSelection {} + +message StartSessionExactTemplateAssociationSelection { + string canonical_version_id = 1; + string selected_commit_id = 2; + string publish_workflow_id = 3; + string association_digest = 4; +} + +message ReadStartSessionTemplateAssociationResponse { + // Echo the entire exact request. Missing, ambiguous, unavailable or conflicting + // owner evidence is a non-OK RPC, never a partial or repaired result. + ReadStartSessionTemplateAssociationRequest request = 1; + StartSessionTemplateWorldSourceAssociationEvidence association = 2; + gamedesign.v1.PublishedReleaseBundle release_bundle = 3; + // Canonical typed World selector evidence committed with the original release terminal. + // This is not a launch descriptor and is not reconstructed from the source-intake receipt. + bytes world_published_start_location_evidence = 4; + // Positive, same-owner-snapshot phase evidence; neither a runtime lifecycle + // epoch nor independent admission permission. + int64 reference_phase_epoch = 5; +} + +// Closed versioned result for one exact Game Session-pinned association replay. The association +// read is included unchanged as the source binding for either outcome. Exactly one of +// launch_descriptor and application_failure must be present. +message ResolveStartSessionLaunchDescriptorResponse { + int32 schema_version = 1; + ReadStartSessionTemplateAssociationResponse association_read = 2; + gamedesign.v1.LaunchDescriptor launch_descriptor = 3; + StartSessionLaunchDescriptorApplicationFailure application_failure = 4; +} + +message StartSessionLaunchDescriptorApplicationFailure { + string code = 1; + string message = 2; +} + +// Closed public projection of the immutable Game Design association. Private operation, +// capture, template snapshot, entry, and canonical-association bytes never cross this API. +message StartSessionTemplateWorldSourceAssociationEvidence { + string canonical_tenant_id = 1; + int64 template_id = 2; + string canonical_version_id = 3; + string selected_commit_id = 4; + string publish_workflow_id = 5; + string publication_selection_digest = 6; + string association_digest = 7; + string target_namespace = 8; + string intake_request_id = 9; + string world_operation_id = 10; + string source_operation_id = 11; + string world_slug = 12; + string source_evidence_digest = 13; + world_management.v1.ReadAuthoredWorldSourceIntakeByIdRequest world_read_request = 14; + world_management.v1.ReadAuthoredWorldSourceIntakeByIdResponse world_read_response = 15; +} diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index d9c7fd624c..8c0edb0683 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -34,6 +34,119 @@ service WorldManagementService { rpc ApplyRoomAmbientStatePatch(ApplyRoomAmbientStatePatchRequest) returns (ApplyRoomAmbientStatePatchResponse); } +// Explicitly unwired authenticated authored-source intake boundary. This service remains separate +// from the runtime WorldManagementService until its caller and deployment path are authorized. +service WorldAuthoredSourceIntakeService { + rpc IntakeAuthoredWorldSource(IntakeAuthoredWorldSourceRequest) + returns (IntakeAuthoredWorldSourceResponse); + rpc ReadAuthoredWorldSourceIntake(ReadAuthoredWorldSourceIntakeRequest) + returns (ReadAuthoredWorldSourceIntakeResponse); + rpc ReadAuthoredWorldSourceIntakeById(ReadAuthoredWorldSourceIntakeByIdRequest) + returns (ReadAuthoredWorldSourceIntakeByIdResponse); +} + +message IntakeAuthoredWorldSourceRequest { + int32 schema_version = 1; + string target_namespace = 2; + string intake_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; +} + +message IntakeAuthoredWorldSourceResponse { + int32 schema_version = 1; + string target_namespace = 2; + string intake_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; + string operation_id = 8; + // Recomputable from the echoed intake binding using the World request digest contract. + string request_digest = 9; + // Opaque authenticated World attestation; it binds private World state and is not client-recomputable. + string receipt_digest = 10; +} + +message ReadAuthoredWorldSourceIntakeRequest { + int32 schema_version = 1; + string target_namespace = 2; + // A distinct nonnil identity for this read; intake_request_id remains the stored receipt key. + string request_id = 3; + string intake_request_id = 4; + string canonical_tenant_id = 5; + string world_slug = 6; + string source_operation_id = 7; + string expected_source_evidence_digest = 8; +} + +message ReadAuthoredWorldSourceIntakeResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + string intake_request_id = 4; + string canonical_tenant_id = 5; + string world_slug = 6; + string source_operation_id = 7; + string expected_source_evidence_digest = 8; + string operation_id = 9; + // Recomputable from the echoed intake binding using the World request digest contract. + string request_digest = 10; + // Opaque authenticated World attestation; it binds private World state and is not client-recomputable. + string receipt_digest = 11; +} + +message ReadAuthoredWorldSourceIntakeByIdRequest { + int32 schema_version = 1; + string target_namespace = 2; + // A distinct caller-owned identity for this read; it is not the stored receipt key. + string read_request_id = 3; + string intake_request_id = 4; + string canonical_tenant_id = 5; +} + +message AuthoredWorldSourceEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string registration_request_id = 3; + string operation_id = 4; + string request_digest = 5; + string canonical_tenant_id = 6; + string tenant_slug = 7; + string world_slug = 8; + string world_display_name = 9; + int64 source_game_row_id = 10; + string source_game_tenant_key = 11; + string provenance_kind = 12; + string evidence_digest = 13; +} + +// Public immutable receipt fields only. World-local tenant/version keys are deliberately omitted. +message AuthoredWorldSourceIntakePublicReceipt { + int32 schema_version = 1; + string target_namespace = 2; + string intake_request_id = 3; + string operation_id = 4; + string canonical_tenant_id = 5; + string world_slug = 6; + string source_operation_id = 7; + string source_evidence_digest = 8; + string request_digest = 9; + string receipt_digest = 10; + AuthoredWorldSourceEvidence source = 11; +} + +message ReadAuthoredWorldSourceIntakeByIdResponse { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intake_request_id = 4; + string canonical_tenant_id = 5; + AuthoredWorldSourceIntakePublicReceipt receipt = 6; +} + enum WorldInstanceLifecycleStatus { WORLD_INSTANCE_LIFECYCLE_STATUS_UNSPECIFIED = 0; WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING = 1; diff --git a/services/common-platform-core/build.gradle.kts b/services/common-platform-core/build.gradle.kts index 7e67ecc121..8f5694b6ca 100644 --- a/services/common-platform-core/build.gradle.kts +++ b/services/common-platform-core/build.gradle.kts @@ -18,6 +18,7 @@ dependencies { implementation(libs.spring.boot.starter) implementation(libs.spring.boot.starter.actuator) implementation(libs.spring.boot.starter.validation) + implementation("org.springframework:spring-tx") compileOnly(libs.spring.boot.starter.web) compileOnly(libs.spring.boot.starter.webflux) compileOnly("com.fasterxml.jackson.core:jackson-annotations") diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java new file mode 100644 index 0000000000..b8e1f33c0d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java @@ -0,0 +1,330 @@ +package net.firedevops.firemud.common.account; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +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 net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; + +/** Explicit mTLS client for Account's read-only redeemed StartSession operation projection. */ +public final class StartSessionRedeemedOperationProjectionClient + extends AbstractReloadingBlockingGrpcClient< + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private final Clock clock; + private volatile boolean initialized; + private volatile boolean closed; + + public StartSessionRedeemedOperationProjectionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + this(endpoints, tlsProperties, channelFactory, workloadNamespace, Clock.systemUTC()); + } + + StartSessionRedeemedOperationProjectionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace, + Clock clock) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + StartSessionRedeemedOperationProjectionClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("StartSession projection client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("StartSession projection client has no gRPC stub"); + } + initialized = true; + } + + /** + * Reads Account's immutable projection for the exact previously redeemed owner attempt. + * + *

This call sends no JWT or opaque authorization reference and does not retry, renew, mutate, + * or authorize owner execution. + */ + public ReadRedeemedOperationProjectionResponse read( + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple, + UUID ownerAttemptId, + long ownerFence) { + Objects.requireNonNull(postAuthorizationTuple, "post-authorization tuple is required"); + requireNonNil(ownerAttemptId, "ownerAttemptId"); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + + StartSessionPreAuthorizationReservationTuple preTuple = + postAuthorizationTuple.preAuthorizationTuple(); + String targetNamespace = preTuple.action().scope().targetNamespace(); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "StartSession projection must use the configured workload namespace"); + } + + byte[] canonicalPreTuple = preTuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + ReadRedeemedOperationProjectionRequest request = + ReadRedeemedOperationProjectionRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(canonicalPreTuple)) + .setAuthorizationReferenceFingerprint( + postAuthorizationTuple.authorizationReferenceFingerprint()) + .setReservationOwnerId(postAuthorizationTuple.reservationOwnerId().toString()) + .setReservationClaimFence(postAuthorizationTuple.reservationClaimFence()) + .setOwnerAttemptId(ownerAttemptId.toString()) + .setOwnerFence(ownerFence) + .build(); + + ReadRedeemedOperationProjectionResponse response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readRedeemedOperationProjection(request); + try { + validateResponse( + postAuthorizationTuple, ownerAttemptId, ownerFence, canonicalPreTuple, response); + return response; + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned an invalid redeemed StartSession operation projection", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "StartSession projection client is not initialized and available"); + } + return currentStub; + } + + private void validateResponse( + StartSessionPostAuthorizationExecutionTuple postTuple, + UUID ownerAttemptId, + long ownerFence, + byte[] canonicalPreTuple, + ReadRedeemedOperationProjectionResponse response) { + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasBundleReference() + || !response.hasReferenceExpiresAt() + || !response.hasRedeemedAt() + || !response.getBundleReference().getUnknownFields().asMap().isEmpty() + || !response.getReferenceExpiresAt().getUnknownFields().asMap().isEmpty() + || !response.getRedeemedAt().getUnknownFields().asMap().isEmpty()) { + throw invalid("projection response contains unknown or missing fields"); + } + + StartSessionPreAuthorizationReservationTuple preTuple = postTuple.preAuthorizationTuple(); + if (!preTuple.controlPlaneRequestId().equals(response.getControlPlaneRequestId()) + || !MessageDigest.isEqual( + canonicalPreTuple, response.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + || !preTuple.mutationDigest().equals(response.getMutationDigest()) + || !postTuple + .authorizationReferenceFingerprint() + .equals(response.getAuthorizationReferenceFingerprint()) + || !postTuple.reservationOwnerId().toString().equals(response.getReservationOwnerId()) + || postTuple.reservationClaimFence() != response.getReservationClaimFence() + || !ownerAttemptId.toString().equals(response.getOwnerAttemptId()) + || ownerFence != response.getOwnerFence()) { + throw invalid("projection differs from the exact original operation or owner attempt"); + } + if (response.getReservationClaimFence() <= 0L || response.getOwnerFence() <= 0L) { + throw invalid("projection fences must be positive"); + } + + String expectedRedeemerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + GrpcPeerIdentity redeemer = + GrpcPeerIdentity.parseUri(response.getAuthenticatedRedeemerWorkloadIdentity()) + .orElseThrow(() -> invalid("projection redeemer identity is invalid")); + if (!expectedRedeemerUri.equals(redeemer.uri()) + || !workloadNamespace.equals(redeemer.namespace()) + || !"game-session-service".equals(redeemer.service())) { + throw invalid("projection redeemer is not the exact same-namespace Game Session workload"); + } + + UUID issuanceOperationId = requireCanonicalNonNilUuid(response.getIssuanceOperationId()); + if (response.getIssuanceFence() <= 0L) { + throw invalid("projection issuance fence must be positive"); + } + + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode( + response.getAuthorityEvidenceBundle().toByteArray()); + if (!MessageDigest.isEqual(postTuple.authorityEvidenceBundleBytes(), bundle.canonicalBytes())) { + throw invalid("projection authority bundle changed from the original Account response"); + } + bundle.requireTupleBinding(preTuple); + bundle.requireReferenceBinding(postTuple.bundleReference()); + if (!issuanceOperationId.equals(bundle.issuanceOperationId()) + || !Long.toString(response.getIssuanceFence()).equals(bundle.issuanceFence())) { + throw invalid("projection issuance identity differs from the original Account bundle"); + } + + var protoReference = response.getBundleReference(); + StartSessionAuthorityEvidenceBundle.BundleReference responseReference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + protoReference.getBundleVersion(), + protoReference.getSourceVersion(), + protoReference.getSourceFence(), + protoReference.getLinearization()); + if (!postTuple.bundleReference().equals(responseReference)) { + throw invalid("projection bundle reference differs from the original Account response"); + } + + Instant referenceExpiresAt = timestamp(response.getReferenceExpiresAt(), "referenceExpiresAt"); + Instant redeemedAt = timestamp(response.getRedeemedAt(), "redeemedAt"); + Instant originalExpiresAt; + try { + originalExpiresAt = Instant.parse(bundle.authorizationExpiresAt()); + } catch (RuntimeException malformed) { + throw invalid("original Account bundle expiry is invalid"); + } + if (!referenceExpiresAt.equals(originalExpiresAt) + || !referenceExpiresAt.isAfter(redeemedAt) + || !referenceExpiresAt.isAfter(clock.instant())) { + throw invalid("projection reference is expired or differs from the original Account expiry"); + } + } + + private static Instant timestamp(Timestamp value, String field) { + if (value.getSeconds() <= 0L || value.getNanos() < 0 || value.getNanos() >= 1_000_000_000) { + throw invalid(field + " timestamp is invalid"); + } + try { + return Instant.ofEpochSecond(value.getSeconds(), value.getNanos()); + } catch (RuntimeException malformed) { + throw invalid(field + " timestamp is outside the supported range"); + } + } + + private static UUID requireCanonicalNonNilUuid(String value) { + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (RuntimeException malformed) { + throw invalid("projection issuance operation ID is invalid"); + } + if (parsed.equals(new UUID(0L, 0L)) || !parsed.toString().equals(value)) { + throw invalid("projection issuance operation ID is not canonical and non-nil"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(field + " must not be nil"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("StartSession projection reads require 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( + "StartSession projection reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "StartSession projection reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "StartSession projection " + label + " must be a readable file-backed path", malformed); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "StartSession projection " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java new file mode 100644 index 0000000000..ac1740309d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java @@ -0,0 +1,533 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; + +/** Closed mapping and exact-readback validation for authored-world launch descriptor RPCs. */ +public final class AuthoredWorldLaunchDescriptorGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + /** Exact owner read identity and the immutable resolve tuple whose result is being recovered. */ + public record GetRequest( + UUID requestId, + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, + String expectedResultDigest) { + public GetRequest { + if (requestId == null || NIL_UUID.equals(requestId)) { + throw new IllegalArgumentException( + "A nonnil launch descriptor read request ID is required"); + } + Objects.requireNonNull(expectedRequest, "expectedRequest"); + if (requestId.equals(expectedRequest.authoredWorldSourceOperationId()) + || requestId.toString().equals(expectedRequest.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Launch descriptor read request ID must be distinct from the original request"); + } + if (expectedResultDigest == null || !SHA256.matcher(expectedResultDigest).matches()) { + throw new IllegalArgumentException( + "Expected launch descriptor result digest must be canonical SHA-256 text"); + } + } + } + + private AuthoredWorldLaunchDescriptorGrpcCodec() {} + + /** Encodes only the exact request fields owned by the immutable shared request value. */ + public static ResolveLaunchDescriptorRequest toResolveRequest( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + Objects.requireNonNull(request, "request"); + ResolveLaunchDescriptorRequest.Builder builder = + ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setGameTemplateId(request.gameTemplateId()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setWorldSlug(request.worldSlug()) + .setAuthoredWorldSourceOperationId(request.authoredWorldSourceOperationId().toString()) + .setExpectedAuthoredWorldSourceEvidenceDigest( + request.authoredWorldSourceEvidenceDigest()); + if (request.requestedScriptPatchVersionPresent()) { + builder.setRequestedScriptPatchVersion(request.requestedScriptPatchVersion()); + } + if (request.sourceVersionIdPresent()) { + builder.setSourceVersionId(request.sourceVersionId()); + } + if (request.targetVersionIdPresent()) { + builder.setTargetVersionId(request.targetVersionId()); + } + if (request.requestedRuntimeFlagsJsonPresent()) { + builder.setRequestedRuntimeFlagsJson(request.requestedRuntimeFlagsJson()); + } + return builder.build(); + } + + /** Encodes an exact persisted owner read, kept distinct from the original resolve identity. */ + public static GetLaunchDescriptorRequest toGetRequest(GetRequest request) { + Objects.requireNonNull(request, "request"); + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(request.requestId().toString()) + .setCanonicalTenantId(expected.canonicalTenantId().toString()) + .setWorldSlug(expected.worldSlug()) + .setControlPlaneRequestId(expected.controlPlaneRequestId()) + .setExpectedRequestDigest(expected.requestDigest()) + .setExpectedResultDigest(request.expectedResultDigest()) + .build(); + } + + /** Validates the complete response and flat descriptor duplicates against the exact request. */ + public static AuthoredWorldLaunchDescriptorEvidence fromResolveResponse( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, + ResolveLaunchDescriptorResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ResolveLaunchDescriptor response"); + if (response.hasError()) { + throw new IllegalArgumentException("Game Design rejected launch descriptor resolution"); + } + if (!response.hasLaunchDescriptor()) { + throw new IllegalArgumentException("Launch descriptor resolution returned no descriptor"); + } + return decodeDescriptor(expectedRequest, response.getLaunchDescriptor()); + } + + /** Validates an exact read echo, original request tuple, result digest, and duplicate fields. */ + public static AuthoredWorldLaunchDescriptorEvidence fromGetResponse( + GetRequest request, GetLaunchDescriptorResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "GetLaunchDescriptor response"); + if (response.hasError()) { + throw new IllegalArgumentException("Game Design rejected the exact launch descriptor read"); + } + UUID echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "read request ID"); + if (!request.requestId().equals(echoedRequestId)) { + throw new IllegalArgumentException("Launch descriptor read request ID echo changed"); + } + if (!response.hasLaunchDescriptor()) { + throw new IllegalArgumentException("Exact launch descriptor read returned no descriptor"); + } + AuthoredWorldLaunchDescriptorEvidence evidence = + decodeDescriptor(request.expectedRequest(), response.getLaunchDescriptor()); + if (!request.expectedResultDigest().equals(evidence.resultDigest())) { + throw new IllegalArgumentException( + "Launch descriptor result digest does not match the exact read request"); + } + return evidence; + } + + /** + * Validates the complete owner response as one atomic descriptor and attestation pair. The + * request is the exact immutable read selector; neither component is accepted alone. + */ + public static CompleteLaunchBindingEvidence fromCompleteResponse( + GetLaunchDescriptorRequest request, GetCompleteLaunchBindingResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(request, "GetCompleteLaunchBinding request"); + requireNoUnknownFields(response, "GetCompleteLaunchBinding response"); + if (response.hasError()) { + requireNoUnknownFields(response.getError(), "GetCompleteLaunchBinding error"); + throw new IllegalArgumentException("Game Design rejected the complete launch binding read"); + } + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId(), "read request ID"); + UUID echoedRequestId = + parseCanonicalNonNilUuid(response.getRequestId(), "read request ID echo"); + if (!readRequestId.equals(echoedRequestId)) { + throw new IllegalArgumentException("Complete launch binding read request ID echo changed"); + } + if (!response.hasLaunchDescriptor() || !response.hasReleaseAttestation()) { + throw new IllegalArgumentException( + "Complete launch binding read must return both descriptor and release attestation"); + } + + AuthoredWorldLaunchDescriptorEvidence descriptor = + decodeDescriptor(response.getLaunchDescriptor()); + if (readRequestId.equals(descriptor.authoredWorldSourceOperationId()) + || readRequestId.toString().equals(descriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Complete launch binding read request ID must be distinct from the original request"); + } + if (!descriptor.canonicalTenantId().toString().equals(request.getCanonicalTenantId()) + || !descriptor.worldSlug().equals(request.getWorldSlug()) + || !descriptor.controlPlaneRequestId().equals(request.getControlPlaneRequestId()) + || !descriptor.requestDigest().equals(request.getExpectedRequestDigest()) + || !descriptor.resultDigest().equals(request.getExpectedResultDigest())) { + throw new IllegalArgumentException( + "Complete launch binding does not match the exact read selector"); + } + + AuthoredWorldReleaseAttestationEvidence releaseAttestation = + decodeReleaseAttestation(response.getReleaseAttestation()); + try { + return new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Complete launch binding evidence is invalid", exception); + } + } + + /** Encodes and revalidates the exact immutable descriptor and release-attestation pair. */ + public static GetCompleteLaunchBindingResponse toCompleteResponse( + GetLaunchDescriptorRequest request, CompleteLaunchBindingEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + evidence.descriptor().requireValid(); + evidence.releaseAttestation().requireValid(evidence.descriptor()); + GetCompleteLaunchBindingResponse response = + GetCompleteLaunchBindingResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setLaunchDescriptor(toLaunchDescriptor(evidence.descriptor())) + .setReleaseAttestation(toReleaseAttestation(evidence.releaseAttestation())) + .build(); + fromCompleteResponse(request, response); + return response; + } + + private static LaunchDescriptor toLaunchDescriptor( + AuthoredWorldLaunchDescriptorEvidence evidence) { + evidence.requireValid(); + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.Builder binding = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setControlPlaneRequestId(evidence.controlPlaneRequestId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setWorldSlug(evidence.worldSlug()) + .setAuthoredWorldSourceOperationId(evidence.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()) + .setGameTemplateId(evidence.gameTemplateId()) + .setRequestDigest(evidence.requestDigest()) + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setVersionId(evidence.versionId()) + .setRuntimeFlagsJson(evidence.runtimeFlagsJson()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setReleaseBundleId(evidence.releaseBundleId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setResultDigest(evidence.resultDigest()); + if (evidence.requestedScriptPatchVersionPresent()) { + binding.setRequestedScriptPatchVersion(evidence.requestedScriptPatchVersion()); + } + if (evidence.sourceVersionIdPresent()) { + binding.setSourceVersionId(evidence.sourceVersionId()); + } + if (evidence.targetVersionIdPresent()) { + binding.setTargetVersionId(evidence.targetVersionId()); + } + if (evidence.requestedRuntimeFlagsJsonPresent()) { + binding.setRequestedRuntimeFlagsJson(evidence.requestedRuntimeFlagsJson()); + } + if (evidence.scriptPatchVersionPresent()) { + binding.setScriptPatchVersion(evidence.scriptPatchVersion()); + } + if (evidence.remapSetIdPresent()) { + binding.setRemapSetId(evidence.remapSetId()); + } + return LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setGameTemplateId(evidence.gameTemplateId()) + .setControlPlaneRequestId(evidence.controlPlaneRequestId()) + .setVersionId(evidence.versionId()) + .setScriptPatchVersion( + evidence.scriptPatchVersionPresent() ? evidence.scriptPatchVersion() : "") + .setRuntimeFlagsJson(evidence.runtimeFlagsJson()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setReleaseBundleId(evidence.releaseBundleId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setRemapSetId(evidence.remapSetIdPresent() ? evidence.remapSetId() : "") + .setAuthoredWorldBinding(binding.build()) + .build(); + } + + /** Public closed wrapper for contracts that carry the canonical launch descriptor message. */ + public static LaunchDescriptor toLaunchDescriptorMessage( + AuthoredWorldLaunchDescriptorEvidence evidence) { + return toLaunchDescriptor(Objects.requireNonNull(evidence, "evidence")); + } + + /** Decodes the existing closed descriptor grammar and binds it to an exact resolve request. */ + public static AuthoredWorldLaunchDescriptorEvidence fromLaunchDescriptorMessage( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, LaunchDescriptor descriptor) { + return decodeDescriptor( + Objects.requireNonNull(expectedRequest, "expectedRequest"), + Objects.requireNonNull(descriptor, "descriptor")); + } + + /** Encodes the separate closed release attestation without changing descriptor/v1. */ + public static net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence + toReleaseAttestation(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + evidence.requireValid(); + var builder = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setDescriptorResultDigest(evidence.descriptorResultDigest()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setCanonicalVersionId(evidence.canonicalVersionId().toString()) + .setWorldSlug(evidence.worldSlug()) + .setAuthoredWorldSourceOperationId(evidence.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()) + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setPublishWorkflowId(evidence.publishWorkflowId()) + .setCommitId(evidence.commitId()) + .setManifestHash(evidence.manifestHash()) + .setManifestSchemaVersion(evidence.manifestSchemaVersion()) + .addAllRequiredManifestAssetKeys(evidence.requiredManifestAssetKeys()) + .addAllCommandDefinitions(evidence.commandDefinitions()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setEvidenceDigest(evidence.evidenceDigest()); + if (evidence.worldStartLocationEvidence() != null) { + builder.setWorldStartLocationEvidence( + ByteString.copyFrom(evidence.worldStartLocationEvidence().canonicalBytes())); + } + for (AuthoredWorldReleaseAttestationEvidence.Participant participant : + evidence.participantDigests()) { + ParticipantDigest.Builder participantBuilder = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigestPresent()) { + participantBuilder.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + } + builder.addParticipantDigests(participantBuilder); + } + for (AuthoredWorldReleaseAttestationEvidence.Artifact artifact : evidence.artifactDigests()) { + builder.addArtifactDigests( + PublishedArtifactDigest.newBuilder() + .setUsageKey(artifact.usageKey()) + .setArtifactKind(artifact.artifactKind()) + .setImmutableObjectKey(artifact.immutableObjectKey()) + .setContentDigest(artifact.contentDigest()) + .setContentType(artifact.contentType()) + .setArtifactSchemaVersion(artifact.artifactSchemaVersion())); + } + return builder.build(); + } + + private static AuthoredWorldLaunchDescriptorEvidence decodeDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, LaunchDescriptor descriptor) { + AuthoredWorldLaunchDescriptorEvidence evidence = decodeDescriptor(descriptor); + if (!evidence.request().equals(expectedRequest)) { + throw new IllegalArgumentException( + "Launch descriptor does not match the exact authored-world resolve request"); + } + return evidence; + } + + private static AuthoredWorldLaunchDescriptorEvidence decodeDescriptor( + LaunchDescriptor descriptor) { + requireNoUnknownFields(descriptor, "LaunchDescriptor"); + if (!descriptor.getTenantId().isEmpty()) { + throw new IllegalArgumentException( + "Canonical descriptor cannot contain a legacy tenant selector"); + } + if (!descriptor.hasAuthoredWorldBinding()) { + throw new IllegalArgumentException("Launch descriptor has no authored-world binding"); + } + var binding = descriptor.getAuthoredWorldBinding(); + requireNoUnknownFields(binding, "AuthoredWorldLaunchDescriptorEvidence"); + + AuthoredWorldLaunchDescriptorEvidence evidence; + try { + evidence = + new AuthoredWorldLaunchDescriptorEvidence( + binding.getSchemaVersion(), + binding.getTargetNamespace(), + binding.getControlPlaneRequestId(), + parseCanonicalNonNilUuid(binding.getCanonicalTenantId(), "canonical tenant ID"), + binding.getWorldSlug(), + parseCanonicalNonNilUuid( + binding.getAuthoredWorldSourceOperationId(), + "authored-world source operation ID"), + binding.getAuthoredWorldSourceEvidenceDigest(), + binding.getGameTemplateId(), + binding.hasRequestedScriptPatchVersion(), + binding.hasRequestedScriptPatchVersion() + ? binding.getRequestedScriptPatchVersion() + : null, + binding.hasSourceVersionId(), + binding.hasSourceVersionId() ? binding.getSourceVersionId() : null, + binding.hasTargetVersionId(), + binding.hasTargetVersionId() ? binding.getTargetVersionId() : null, + binding.hasRequestedRuntimeFlagsJson(), + binding.hasRequestedRuntimeFlagsJson() + ? binding.getRequestedRuntimeFlagsJson() + : null, + binding.getRequestDigest(), + binding.getLaunchDescriptorId(), + binding.getVersionId(), + binding.hasScriptPatchVersion(), + binding.hasScriptPatchVersion() ? binding.getScriptPatchVersion() : null, + binding.getRuntimeFlagsJson(), + binding.getGenerationConfigRevision(), + binding.getVersionStateEpoch(), + binding.getReleaseBundleId(), + binding.getPublishedReleaseBundleRef(), + binding.hasRemapSetId(), + binding.hasRemapSetId() ? binding.getRemapSetId() : null, + binding.getResultDigest()); + evidence.requireValid(); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Authored-world launch evidence is invalid", exception); + } + + requireFlatDuplicate( + descriptor.getLaunchDescriptorId(), evidence.launchDescriptorId(), "launchDescriptorId"); + requireFlatDuplicate( + descriptor.getCanonicalTenantId(), + evidence.canonicalTenantId().toString(), + "canonicalTenantId"); + requireFlatDuplicate( + descriptor.getGameTemplateId(), evidence.gameTemplateId(), "gameTemplateId"); + requireFlatDuplicate( + descriptor.getControlPlaneRequestId(), + evidence.controlPlaneRequestId(), + "controlPlaneRequestId"); + requireFlatDuplicate(descriptor.getVersionId(), evidence.versionId(), "versionId"); + requireFlatDuplicate( + descriptor.getScriptPatchVersion(), + evidence.scriptPatchVersionPresent() ? evidence.scriptPatchVersion() : "", + "scriptPatchVersion"); + requireFlatDuplicate( + descriptor.getRuntimeFlagsJson(), evidence.runtimeFlagsJson(), "runtimeFlagsJson"); + requireFlatDuplicate( + descriptor.getGenerationConfigRevision(), + evidence.generationConfigRevision(), + "generationConfigRevision"); + requireFlatDuplicate( + descriptor.getVersionStateEpoch(), evidence.versionStateEpoch(), "versionStateEpoch"); + requireFlatDuplicate( + descriptor.getReleaseBundleId(), evidence.releaseBundleId(), "releaseBundleId"); + requireFlatDuplicate( + descriptor.getPublishedReleaseBundleRef(), + evidence.publishedReleaseBundleRef(), + "publishedReleaseBundleRef"); + requireFlatDuplicate( + descriptor.getRemapSetId(), + evidence.remapSetIdPresent() ? evidence.remapSetId() : "", + "remapSetId"); + return evidence; + } + + private static AuthoredWorldReleaseAttestationEvidence decodeReleaseAttestation( + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence wire) { + requireNoUnknownFields(wire, "AuthoredWorldReleaseAttestationEvidence"); + List participants = + new java.util.ArrayList<>(wire.getParticipantDigestsCount()); + for (ParticipantDigest participant : wire.getParticipantDigestsList()) { + requireNoUnknownFields(participant, "ParticipantDigest"); + participants.add( + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.getParticipantKey(), + participant.getScopeValue(), + false, + null, + participant.getAppliedCommitId(), + participant.getContentDigest(), + participant.getDigestSchemaVersion(), + participant.hasAbilitySchemaDigest(), + participant.hasAbilitySchemaDigest() ? participant.getAbilitySchemaDigest() : null)); + } + List artifacts = + new java.util.ArrayList<>(wire.getArtifactDigestsCount()); + for (PublishedArtifactDigest artifact : wire.getArtifactDigestsList()) { + requireNoUnknownFields(artifact, "PublishedArtifactDigest"); + artifacts.add( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + artifact.getUsageKey(), + artifact.getArtifactKind(), + artifact.getImmutableObjectKey(), + artifact.getContentDigest(), + artifact.getContentType(), + artifact.getArtifactSchemaVersion())); + } + try { + return new AuthoredWorldReleaseAttestationEvidence( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + wire.getDescriptorResultDigest(), + parseCanonicalNonNilUuid(wire.getCanonicalTenantId(), "canonical tenant ID"), + parseCanonicalNonNilUuid(wire.getCanonicalVersionId(), "canonical version ID"), + wire.getWorldSlug(), + parseCanonicalNonNilUuid( + wire.getAuthoredWorldSourceOperationId(), "authored-world source operation ID"), + wire.getAuthoredWorldSourceEvidenceDigest(), + wire.getLaunchDescriptorId(), + wire.getPublishedReleaseBundleRef(), + wire.getVersionStateEpoch(), + wire.getPublishWorkflowId(), + wire.getCommitId(), + participants, + wire.getManifestHash(), + wire.getManifestSchemaVersion(), + wire.getRequiredManifestAssetKeysList(), + artifacts, + wire.getCommandDefinitionsList(), + wire.getGenerationConfigRevision(), + wire.getEvidenceDigest(), + wire.hasWorldStartLocationEvidence() + ? WorldPublishedStartLocationEvidence.fromStored( + wire.getWorldStartLocationEvidence().toByteArray()) + : null); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Release-attestation evidence is invalid", exception); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + 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 (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static void requireFlatDuplicate(String actual, String expected, String field) { + if (!Objects.equals(actual, expected)) { + throw new IllegalArgumentException( + "Flat launch descriptor " + field + " does not match evidence"); + } + } + + private static void requireFlatDuplicate(long actual, long expected, String field) { + if (actual != expected) { + throw new IllegalArgumentException( + "Flat launch descriptor " + field + " does not match evidence"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java index b58a5b34d1..6f5319096a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java @@ -49,9 +49,12 @@ public record AuthoredWorldReleaseAttestationEvidence( WorldPublishedStartLocationEvidence worldStartLocationEvidence) { public static final int SCHEMA_VERSION = 1; public static final int SELECTOR_SCHEMA_VERSION = 2; + public static final int CLOSURE_SELECTOR_SCHEMA_VERSION = 3; private static final String EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v1"; private static final String SELECTOR_EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v2"; + private static final String CLOSURE_SELECTOR_EVIDENCE_DOMAIN = + "game-design-authored-world-release-attestation/v3"; private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); private static final Pattern PARTICIPANT_CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); @@ -82,12 +85,36 @@ public static List requiredParticipantOrder() { /** Returns the one supported digest schema for a required participant owner. */ public static int supportedParticipantDigestSchema(String participantKey) { + return supportedParticipantDigestSchema(participantKey, SCHEMA_VERSION); + } + + /** Selects owner schemas from the retained-v1, selected-v2, or closure-selected-v3 contract. */ + public static int supportedParticipantDigestSchema( + String participantKey, int attestationSchemaVersion) { + if (attestationSchemaVersion != SCHEMA_VERSION + && attestationSchemaVersion != SELECTOR_SCHEMA_VERSION + && attestationSchemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); + } Objects.requireNonNull(participantKey, "participantKey"); Integer version = SUPPORTED_PARTICIPANT_DIGEST_SCHEMAS.get(participantKey); if (version == null) { throw new IllegalArgumentException("Unsupported full-Version participant owner"); } - return version; + if (attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION + && "WORLD_MANAGEMENT".equals(participantKey)) { + return 4; + } + return (attestationSchemaVersion == SELECTOR_SCHEMA_VERSION + || attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION) + && "GAME_DESIGN_CONTROL_PLANE".equals(participantKey) + ? 2 + : version; + } + + public static boolean requiresWorldStartLocationEvidence(int attestationSchemaVersion) { + return attestationSchemaVersion == SELECTOR_SCHEMA_VERSION + || attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION; } /** One successful, immutable owner digest included in the release attestation. */ @@ -143,7 +170,9 @@ public record Artifact( } public AuthoredWorldReleaseAttestationEvidence { - if (schemaVersion != SCHEMA_VERSION && schemaVersion != SELECTOR_SCHEMA_VERSION) { + if (schemaVersion != SCHEMA_VERSION + && schemaVersion != SELECTOR_SCHEMA_VERSION + && schemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION) { throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); } Objects.requireNonNull(targetNamespace, "targetNamespace"); @@ -165,7 +194,7 @@ public record Artifact( requireText(commitId, "commitId"); participantDigests = List.copyOf(Objects.requireNonNull(participantDigests, "participantDigests")); - validateParticipants(participantDigests, commitId); + validateParticipants(participantDigests, commitId, schemaVersion); requireDigest(manifestHash, "manifestHash"); requireSupportedSchema(manifestSchemaVersion, "manifestSchemaVersion"); requiredManifestAssetKeys = @@ -180,9 +209,9 @@ public record Artifact( } requireText(generationConfigRevision, "generationConfigRevision"); requireDigest(evidenceDigest, "evidenceDigest"); - if ((schemaVersion == SELECTOR_SCHEMA_VERSION) != (worldStartLocationEvidence != null)) { + if (requiresWorldStartLocationEvidence(schemaVersion) != (worldStartLocationEvidence != null)) { throw new IllegalArgumentException( - "Only release-attestation/v2 requires World selector evidence"); + "Selected release-attestation schemas require World selector evidence"); } if (worldStartLocationEvidence != null) { WorldPublishedStartLocationEvidence.fromStored(worldStartLocationEvidence.canonicalBytes()); @@ -271,10 +300,102 @@ public static AuthoredWorldReleaseAttestationEvidence create( List commandDefinitions, String generationConfigRevision, WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + return createSelected( + SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + worldStartLocationEvidence); + } + + /** Creates v3 for a selected World closure-qualified schema-4 participant digest. */ + public static AuthoredWorldReleaseAttestationEvidence createClosureSelector( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + return createSelected( + CLOSURE_SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + worldStartLocationEvidence); + } + + private static AuthoredWorldReleaseAttestationEvidence createSelected( + int schemaVersion, + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { Objects.requireNonNull(worldStartLocationEvidence, "worldStartLocationEvidence"); var provisional = new AuthoredWorldReleaseAttestationEvidence( - SELECTOR_SCHEMA_VERSION, + schemaVersion, targetNamespace, descriptorResultDigest, canonicalTenantId, @@ -297,7 +418,7 @@ public static AuthoredWorldReleaseAttestationEvidence create( "sha256:" + "0".repeat(64), worldStartLocationEvidence); return new AuthoredWorldReleaseAttestationEvidence( - SELECTOR_SCHEMA_VERSION, + schemaVersion, targetNamespace, descriptorResultDigest, canonicalTenantId, @@ -514,19 +635,25 @@ public static byte[] evidencePreimage(AuthoredWorldReleaseAttestationEvidence ev field("commandDefinitions[" + index + "]", evidence.commandDefinitions().get(index))); } fields.add(field("generationConfigRevision", evidence.generationConfigRevision())); - if (evidence.schemaVersion() == SELECTOR_SCHEMA_VERSION) { + if (requiresWorldStartLocationEvidence(evidence.schemaVersion())) { fields.add( field( "worldStartLocationEvidence.canonicalBytesBase64", Base64.getEncoder() .encodeToString(evidence.worldStartLocationEvidence().canonicalBytes()))); } - return preimage( - evidence.schemaVersion() == SCHEMA_VERSION ? EVIDENCE_DOMAIN : SELECTOR_EVIDENCE_DOMAIN, - fields.toArray(Field[]::new)); + String domain = + switch (evidence.schemaVersion()) { + case SCHEMA_VERSION -> EVIDENCE_DOMAIN; + case SELECTOR_SCHEMA_VERSION -> SELECTOR_EVIDENCE_DOMAIN; + case CLOSURE_SELECTOR_SCHEMA_VERSION -> CLOSURE_SELECTOR_EVIDENCE_DOMAIN; + default -> throw new IllegalArgumentException("Unsupported release-attestation schema"); + }; + return preimage(domain, fields.toArray(Field[]::new)); } - private static void validateParticipants(List participants, String commitId) { + private static void validateParticipants( + List participants, String commitId, int attestationSchemaVersion) { if (participants.size() != PARTICIPANT_ORDER.size()) { throw new IllegalArgumentException( "A complete attestation requires exactly five participants"); @@ -538,7 +665,7 @@ private static void validateParticipants(List participants, String if (!expectedKey.equals(participant.participantKey())) { throw new IllegalArgumentException("Participant digests are not in canonical owner order"); } - if (supportedParticipantDigestSchema(participant.participantKey()) + if (supportedParticipantDigestSchema(participant.participantKey(), attestationSchemaVersion) != participant.digestSchemaVersion()) { throw new IllegalArgumentException( "Participant digest schema is unsupported for its owner"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java index bd6e98647a..a0e29e8e4f 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -79,10 +79,16 @@ public record ReleaseContent( text(publishedReleaseBundleRef); text(publishWorkflowId); text(generationConfigRevision); - if (versionNumber <= 0 - || !"v2".equals(attestationSchemaVersion) - || manifestSchemaVersion != 1) { - throw new IllegalArgumentException("Complete full-Version bundle/v2 required"); + int selectedAttestationSchema = + switch (attestationSchemaVersion) { + case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case "v3" -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + default -> + throw new IllegalArgumentException( + "Complete full-Version bundle/v2 or bundle/v3 required"); + }; + if (versionNumber <= 0 || manifestSchemaVersion != 1) { + throw new IllegalArgumentException("Complete full-Version bundle/v2 or bundle/v3 required"); } digest(manifestHash); artifactDigests = List.copyOf(artifactDigests); @@ -108,7 +114,7 @@ public record ReleaseContent( if (!owners.get(i).equals(p.participantKey()) || p.digestSchemaVersion() != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - p.participantKey()) + p.participantKey(), selectedAttestationSchema) || p.baseVersionId() != null || !selected.appliedCommitId().equals(p.appliedCommitId()) || !p.scopeValue().matches("[1-9][0-9]*") diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java new file mode 100644 index 0000000000..0445572e45 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java @@ -0,0 +1,239 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.StartSessionLaunchDescriptorApplicationFailure; + +/** Closed request/result mapping for the exact-replay StartSession descriptor projection. */ +public final class StartSessionLaunchDescriptorGrpcCodec { + public static final int RESPONSE_SCHEMA_VERSION = 1; + private static final String EMPTY_RUNTIME_FLAGS = "{}"; + private static final Set FAILURE_CODES = + Set.of( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", + "INVALID_TEMPLATE_CONFIGURATION", + "SCRIPT_PATCH_OVERRIDE_CONFLICT", + "SCRIPT_PATCH_NOT_READY", + "RELEASE_BUNDLE_NOT_FOUND", + "RELEASE_ATTESTATION_MISMATCH", + "VERSION_STATE_EPOCH_STALE", + "LAUNCH_REMAP_REQUIRED"); + + private StartSessionLaunchDescriptorGrpcCodec() {} + + public sealed interface Outcome permits DescriptorOutcome, ApplicationFailure {} + + public record DescriptorOutcome(AuthoredWorldLaunchDescriptorEvidence descriptor) + implements Outcome { + public DescriptorOutcome { + Objects.requireNonNull(descriptor, "descriptor"); + } + } + + /** A persisted domain denial; transport and dependency failures are not represented here. */ + public record ApplicationFailure(String code, String message) implements Outcome { + public ApplicationFailure { + Objects.requireNonNull(code, "code"); + Objects.requireNonNull(message, "message"); + if (!FAILURE_CODES.contains(code) + || message.length() > 1024 + || !message.startsWith(code + ": ")) { + throw new IllegalArgumentException("Known deterministic StartSession failure required"); + } + } + } + + /** Validated association evidence paired with exactly one descriptor outcome. */ + public record Resolved(Result associationRead, Outcome outcome) { + public Resolved { + Objects.requireNonNull(associationRead, "associationRead"); + Objects.requireNonNull(outcome, "outcome"); + } + } + + /** + * The descriptor endpoint accepts exact replay only; initial selection remains a separate read. + */ + public static ReadStartSessionTemplateAssociationRequest toRequest(Request request) { + requireExactReplay(request); + return StartSessionTemplateAssociationReadGrpcCodec.toRequest(request); + } + + /** Decode the reused association request and reject initial or absent selection modes. */ + public static Request fromRequest(ReadStartSessionTemplateAssociationRequest request) { + Request decoded = StartSessionTemplateAssociationReadGrpcCodec.fromRequest(request); + requireExactReplay(decoded); + return decoded; + } + + public static ResolveStartSessionLaunchDescriptorResponse toDescriptorResponse( + Request expectedRequest, + Result associationRead, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return toResponse( + expectedRequest, + associationRead, + new DescriptorOutcome(Objects.requireNonNull(descriptor))); + } + + public static ResolveStartSessionLaunchDescriptorResponse toFailureResponse( + Request expectedRequest, Result associationRead, String code, String message) { + return toResponse(expectedRequest, associationRead, new ApplicationFailure(code, message)); + } + + /** Encodes one complete result and runs the same closed decoder used by receiving callers. */ + public static ResolveStartSessionLaunchDescriptorResponse toResponse( + Request expectedRequest, Result associationRead, Outcome outcome) { + requireAssociationBinding(expectedRequest, associationRead); + Objects.requireNonNull(outcome, "outcome"); + var builder = + ResolveStartSessionLaunchDescriptorResponse.newBuilder() + .setSchemaVersion(RESPONSE_SCHEMA_VERSION) + .setAssociationRead( + StartSessionTemplateAssociationReadGrpcCodec.toResponse(associationRead)); + if (outcome instanceof DescriptorOutcome descriptorOutcome) { + requireDescriptorBinding(expectedRequest, associationRead, descriptorOutcome.descriptor()); + builder.setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + descriptorOutcome.descriptor())); + } else if (outcome instanceof ApplicationFailure failure) { + builder.setApplicationFailure( + StartSessionLaunchDescriptorApplicationFailure.newBuilder() + .setCode(failure.code()) + .setMessage(failure.message())); + } else { + throw new IllegalArgumentException("Unsupported StartSession descriptor outcome"); + } + ResolveStartSessionLaunchDescriptorResponse response = builder.build(); + fromResponse(expectedRequest, response); + return response; + } + + /** Validates the complete nested association read and exact descriptor or stored denial. */ + public static Resolved fromResponse( + Request expectedRequest, ResolveStartSessionLaunchDescriptorResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireExactReplay(expectedRequest); + requireNoUnknownFields(response, "ResolveStartSessionLaunchDescriptorResponse"); + if (response.getSchemaVersion() != RESPONSE_SCHEMA_VERSION + || !response.hasAssociationRead() + || response.hasLaunchDescriptor() == response.hasApplicationFailure()) { + throw new IllegalArgumentException( + "Versioned StartSession descriptor response must contain one complete outcome"); + } + Result associationRead = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + expectedRequest, response.getAssociationRead()); + requireAssociationBinding(expectedRequest, associationRead); + Outcome outcome; + if (response.hasLaunchDescriptor()) { + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + expectedDescriptorRequest(expectedRequest, associationRead.association()), + response.getLaunchDescriptor()); + requireDescriptorBinding(expectedRequest, associationRead, descriptor); + outcome = new DescriptorOutcome(descriptor); + } else { + var failure = response.getApplicationFailure(); + requireNoUnknownFields(failure, "StartSessionLaunchDescriptorApplicationFailure"); + outcome = new ApplicationFailure(failure.getCode(), failure.getMessage()); + } + return new Resolved(associationRead, outcome); + } + + private static void requireAssociationBinding(Request expectedRequest, Result associationRead) { + requireExactReplay(expectedRequest); + Objects.requireNonNull(associationRead, "associationRead"); + if (!expectedRequest.equals(associationRead.request())) { + throw new IllegalArgumentException( + "Association read differs from the exact StartSession request"); + } + } + + private static void requireDescriptorBinding( + Request request, Result associationRead, AuthoredWorldLaunchDescriptorEvidence descriptor) { + Objects.requireNonNull(descriptor, "descriptor"); + descriptor.requireValid(); + var association = associationRead.association(); + if (!expectedDescriptorRequest(request, association).equals(descriptor.request())) { + throw new IllegalArgumentException( + "Launch descriptor request differs from the original StartSession tuple and association"); + } + var release = associationRead.releaseBundle(); + if (release.getIsScriptOnly() + || !release.getScriptPatchVersion().isEmpty() + || descriptor.scriptPatchVersionPresent() + || descriptor.remapSetIdPresent() + || !EMPTY_RUNTIME_FLAGS.equals(descriptor.runtimeFlagsJson()) + || descriptor.versionId() != release.getVersionId() + || descriptor.releaseBundleId() != release.getId() + || !descriptor.publishedReleaseBundleRef().equals(release.getPublishedReleaseBundleRef()) + || !descriptor.generationConfigRevision().equals(release.getGenerationConfigRevision()) + || !descriptor.canonicalTenantId().toString().equals(release.getCanonicalTenantId()) + || !association.canonicalVersionId().toString().equals(release.getCanonicalVersionId()) + || !association.publishWorkflowId().equals(release.getPublishWorkflowId())) { + throw new IllegalArgumentException( + "Launch descriptor version or release differs from the exact association response"); + } + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request expectedDescriptorRequest( + Request request, StartSessionTemplateAssociationReadEvidence.Association association) { + var action = request.decodedTuple().preAuthorizationTuple().action(); + if (!action.scope().tenantId().equals(association.canonicalTenantId()) + || action.target().gameTemplateId() != association.templateId() + || !request.targetNamespace().equals(association.targetNamespace())) { + throw new IllegalArgumentException( + "Association differs from the original authorized StartSession target"); + } + return new AuthoredWorldLaunchDescriptorEvidence.Request( + request.targetNamespace(), + request.decodedTuple().controlPlaneRequestId(), + association.canonicalTenantId(), + association.worldSlug(), + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.templateId(), + false, + null, + false, + null, + false, + null, + true, + EMPTY_RUNTIME_FLAGS); + } + + private static void requireExactReplay(Request request) { + Objects.requireNonNull(request, "request"); + if (!(request.selection() instanceof ExactReplay)) { + throw new IllegalArgumentException("Exact Game Session-pinned association replay required"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) continue; + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClient.java new file mode 100644 index 0000000000..d8ccef0248 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClient.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.common.gamedesign; + +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.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +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 net.firedevops.firemud.gamedesign.v1.GameDesignStartSessionLaunchDescriptorServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for the exact-replay Game Design StartSession descriptor. */ +public final class StartSessionLaunchDescriptorReadClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignStartSessionLaunchDescriptorServiceGrpc + .GameDesignStartSessionLaunchDescriptorServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public StartSessionLaunchDescriptorReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + StartSessionLaunchDescriptorReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("StartSession descriptor read client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("StartSession descriptor read client has no gRPC stub"); + } + initialized = true; + } + + /** + * Resolves one exact pinned association outside owner transactions; it grants no runtime + * authority. + */ + public StartSessionLaunchDescriptorGrpcCodec.Resolved resolve(Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "StartSession descriptor read requires no ambient owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "StartSession descriptor request must use the configured workload namespace"); + } + + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveStartSessionLaunchDescriptor( + StartSessionLaunchDescriptorGrpcCodec.toRequest(request)); + try { + return StartSessionLaunchDescriptorGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid StartSession launch descriptor evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignStartSessionLaunchDescriptorServiceGrpc + .GameDesignStartSessionLaunchDescriptorServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignStartSessionLaunchDescriptorServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignStartSessionLaunchDescriptorServiceGrpc + .GameDesignStartSessionLaunchDescriptorServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "StartSession descriptor read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("StartSession descriptor reads require 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( + "StartSession descriptor reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "StartSession descriptor reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "StartSession descriptor " + label + " must be a readable file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "StartSession descriptor " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClient.java new file mode 100644 index 0000000000..8126646f72 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClient.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.common.gamedesign; + +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.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +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 net.firedevops.firemud.gamedesign.v1.GameDesignStartSessionTemplateAssociationReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for the exact Game Design StartSession association read. */ +public final class StartSessionTemplateAssociationReadClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignStartSessionTemplateAssociationReadServiceGrpc + .GameDesignStartSessionTemplateAssociationReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public StartSessionTemplateAssociationReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + StartSessionTemplateAssociationReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Template association read client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Template association read client has no gRPC stub"); + } + initialized = true; + } + + /** + * Reads one exact owner association outside all owner transactions. The result is source and + * release evidence only; it is not a launch commit, World lifecycle proof, or admission grant. + */ + public Result read(Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Template association read requires no ambient owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Template association request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readStartSessionTemplateAssociation( + StartSessionTemplateAssociationReadGrpcCodec.toRequest(request)); + try { + return StartSessionTemplateAssociationReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid StartSession template association evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignStartSessionTemplateAssociationReadServiceGrpc + .GameDesignStartSessionTemplateAssociationReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignStartSessionTemplateAssociationReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignStartSessionTemplateAssociationReadServiceGrpc + .GameDesignStartSessionTemplateAssociationReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Template association read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Template association reads require 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( + "Template association reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Template association reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Template association " + label + " must be a readable file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Template association " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java new file mode 100644 index 0000000000..7658e47a9b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java @@ -0,0 +1,365 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Message; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; + +/** Closed, public evidence returned by the standalone StartSession template-association read. */ +public final class StartSessionTemplateAssociationReadEvidence { + public static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + private StartSessionTemplateAssociationReadEvidence() {} + + public sealed interface Selection permits InitialConfigured, ExactReplay {} + + /** Resolve only the owner-proved current configured reference, never a caller version. */ + public record InitialConfigured() implements Selection {} + + /** Reuse one exact selection already pinned by Game Session to the original control-plane ID. */ + public record ExactReplay( + UUID canonicalVersionId, + UUID selectedCommitId, + String publishWorkflowId, + String associationDigest) + implements Selection { + public ExactReplay { + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(selectedCommitId, "selectedCommitId"); + requireText(publishWorkflowId, "publishWorkflowId", 256); + requireDigest(associationDigest, "associationDigest"); + } + } + + /** Exact authenticated StartSession identity plus the actual Game Session owner attempt/fence. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] canonicalPostAuthorizationTuple, + UUID ownerAttemptId, + long ownerFence, + Selection selection) { + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported template association read schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Game Session namespace is required"); + } + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(ownerAttemptId, "ownerAttemptId"); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + Objects.requireNonNull(selection, "selection"); + if (canonicalPostAuthorizationTuple == null + || canonicalPostAuthorizationTuple.length == 0 + || canonicalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException("Complete bounded StartSession tuple is required"); + } + canonicalPostAuthorizationTuple = canonicalPostAuthorizationTuple.clone(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(canonicalPostAuthorizationTuple); + if (!Arrays.equals(tuple.canonicalBytes(), canonicalPostAuthorizationTuple) + || !targetNamespace.equals( + tuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw new IllegalArgumentException( + "Exact canonical StartSession tuple and namespace are required"); + } + } + + @Override + public byte[] canonicalPostAuthorizationTuple() { + return canonicalPostAuthorizationTuple.clone(); + } + + public StartSessionPostAuthorizationExecutionTuple decodedTuple() { + return StartSessionPostAuthorizationExecutionTuple.decode(canonicalPostAuthorizationTuple); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals(canonicalPostAuthorizationTuple, that.canonicalPostAuthorizationTuple) + && ownerAttemptId.equals(that.ownerAttemptId) + && ownerFence == that.ownerFence + && selection.equals(that.selection); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + schemaVersion, + targetNamespace, + readRequestId, + ownerAttemptId, + ownerFence, + selection) + + Arrays.hashCode(canonicalPostAuthorizationTuple); + } + } + + /** Public projection only; the persisted canonical association bytes are deliberately private. */ + public record Association( + UUID canonicalTenantId, + long templateId, + UUID canonicalVersionId, + UUID selectedCommitId, + String publishWorkflowId, + String publicationSelectionDigest, + String associationDigest, + String targetNamespace, + UUID intakeRequestId, + UUID worldOperationId, + UUID sourceOperationId, + String worldSlug, + String sourceEvidenceDigest, + ByIdReadRequest worldReadRequest, + PublicReceipt worldReceipt) { + public Association { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (templateId <= 0L) throw new IllegalArgumentException("templateId must be positive"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(selectedCommitId, "selectedCommitId"); + requireText(publishWorkflowId, "publishWorkflowId", 256); + requireDigest(publicationSelectionDigest, "publicationSelectionDigest"); + requireDigest(associationDigest, "associationDigest"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical target namespace is required"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(worldOperationId, "worldOperationId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + requireText(worldSlug, "worldSlug", 128); + requireDigest(sourceEvidenceDigest, "sourceEvidenceDigest"); + Objects.requireNonNull(worldReadRequest, "worldReadRequest"); + Objects.requireNonNull(worldReceipt, "worldReceipt"); + if (worldReadRequest.schemaVersion() != SCHEMA_VERSION + || !targetNamespace.equals(worldReadRequest.targetNamespace()) + || !canonicalTenantId.equals(worldReadRequest.canonicalTenantId()) + || !intakeRequestId.equals(worldReadRequest.intakeRequestId()) + || !targetNamespace.equals(worldReceipt.targetNamespace()) + || !canonicalTenantId.equals(worldReceipt.canonicalTenantId()) + || !intakeRequestId.equals(worldReceipt.intakeRequestId()) + || !worldOperationId.equals(worldReceipt.operationId()) + || !sourceOperationId.equals(worldReceipt.sourceOperationId()) + || !worldSlug.equals(worldReceipt.worldSlug()) + || !sourceEvidenceDigest.equals(worldReceipt.sourceEvidenceDigest())) { + throw new IllegalArgumentException( + "Public World intake receipt differs from the exact stored association"); + } + // Re-encode through the established owner codec to ensure its complete public receipt stays + // closed and satisfies the original by-ID request correlation. + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse(worldReadRequest, worldReceipt); + } + + public static Association fromStoredProjection( + UUID canonicalTenantId, + long templateId, + UUID canonicalVersionId, + UUID selectedCommitId, + String publishWorkflowId, + String publicationSelectionDigest, + String associationDigest, + String targetNamespace, + UUID intakeRequestId, + UUID worldOperationId, + UUID sourceOperationId, + String worldSlug, + String sourceEvidenceDigest, + ReadAuthoredWorldSourceIntakeByIdRequest worldReadRequest, + ReadAuthoredWorldSourceIntakeByIdResponse worldReadResponse) { + ByIdReadRequest typedRequest = + WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdRequest(worldReadRequest); + PublicReceipt typedReceipt = + WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdResponse(typedRequest, worldReadResponse); + return new Association( + canonicalTenantId, + templateId, + canonicalVersionId, + selectedCommitId, + publishWorkflowId, + publicationSelectionDigest, + associationDigest, + targetNamespace, + intakeRequestId, + worldOperationId, + sourceOperationId, + worldSlug, + sourceEvidenceDigest, + typedRequest, + typedReceipt); + } + } + + public record Result( + Request request, + Association association, + PublishedReleaseBundle releaseBundle, + WorldPublishedStartLocationEvidence worldPublishedStartLocationEvidence, + long phaseEpoch) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Generated protobuf release bundles are immutable value messages.") + public Result { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(association, "association"); + Objects.requireNonNull(releaseBundle, "releaseBundle"); + Objects.requireNonNull( + worldPublishedStartLocationEvidence, "worldPublishedStartLocationEvidence"); + if (phaseEpoch <= 0L) throw new IllegalArgumentException("Positive phase epoch is required"); + StartSessionPostAuthorizationExecutionTuple tuple = request.decodedTuple(); + var action = tuple.preAuthorizationTuple().action(); + if (!request.targetNamespace().equals(association.targetNamespace()) + || !action.scope().tenantId().equals(association.canonicalTenantId()) + || action.target().gameTemplateId() != association.templateId() + || !association + .canonicalTenantId() + .toString() + .equals(releaseBundle.getCanonicalTenantId()) + || !association + .canonicalVersionId() + .toString() + .equals(releaseBundle.getCanonicalVersionId()) + || !association.publishWorkflowId().equals(releaseBundle.getPublishWorkflowId())) { + throw new IllegalArgumentException( + "Association and release differ from the exact authorized StartSession target"); + } + var worldSelector = worldPublishedStartLocationEvidence.request(); + if (!request.targetNamespace().equals(worldSelector.targetNamespace()) + || !association.canonicalTenantId().equals(worldSelector.canonicalTenantId()) + || !association.canonicalVersionId().equals(worldSelector.canonicalVersionId()) + || !association.publishWorkflowId().equals(worldSelector.publishWorkflowId()) + || !association.selectedCommitId().toString().equals(worldSelector.appliedCommitId())) { + throw new IllegalArgumentException( + "World published selector differs from exact association and release identity"); + } + requireNoUnknownFields(releaseBundle, "PublishedReleaseBundle"); + requireCompleteRelease(releaseBundle, worldPublishedStartLocationEvidence); + if (request.selection() instanceof ExactReplay replay + && (!replay.canonicalVersionId().equals(association.canonicalVersionId()) + || !replay.selectedCommitId().equals(association.selectedCommitId()) + || !replay.publishWorkflowId().equals(association.publishWorkflowId()) + || !replay.associationDigest().equals(association.associationDigest()))) { + throw new IllegalArgumentException( + "Exact replay differs from the originally pinned result"); + } + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf release bundles are immutable value messages.") + public PublishedReleaseBundle releaseBundle() { + return releaseBundle; + } + } + + 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"); + } + + private static void requireText(String value, String field, int maxLength) { + Objects.requireNonNull(value, field); + if (value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(field + " must be nonblank and bounded"); + } + } + + private static void requireDigest(String value, String field) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a canonical SHA-256 digest"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : + message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() + != com.google.protobuf.Descriptors.FieldDescriptor.JavaType.MESSAGE) continue; + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } + + private static void requireCompleteRelease( + PublishedReleaseBundle bundle, WorldPublishedStartLocationEvidence worldEvidence) { + if (bundle.getId() <= 0L + || bundle.getVersionId() <= 0L + || bundle.getVersionNumber() <= 0 + || !bundle.hasManifestSchemaVersion()) { + throw new IllegalArgumentException("Complete selector-bearing published release is required"); + } + List artifacts = + bundle.getArtifactDigestsList().stream() + .map( + value -> + new AuthoredWorldReleaseAttestationEvidence.Artifact( + value.getUsageKey(), + value.getArtifactKind(), + value.getImmutableObjectKey(), + value.getContentDigest(), + value.getContentType(), + value.getArtifactSchemaVersion())) + .toList(); + List participants = + bundle.getParticipantDigestsList().stream() + .map( + value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.getParticipantKey(), + value.getScopeValue(), + null, + value.getAppliedCommitId(), + value.getContentDigest(), + value.getDigestSchemaVersion(), + value.hasAbilitySchemaDigest() ? value.getAbilitySchemaDigest() : null, + null, + null)) + .toList(); + new GameDesignPublicationTerminalEvidence.ReleaseContent( + UUID.fromString(bundle.getCanonicalTenantId()), + UUID.fromString(bundle.getCanonicalVersionId()), + bundle.getPublishedReleaseBundleRef(), + bundle.getVersionNumber(), + bundle.getAttestationSchemaVersion(), + bundle.getPublishWorkflowId(), + bundle.getManifestHash(), + bundle.getManifestSchemaVersion(), + artifacts, + bundle.getRequiredManifestAssetKeysList(), + participants, + bundle.getCommandDefinitionsList(), + bundle.getGenerationConfigRevision(), + worldEvidence); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodec.java new file mode 100644 index 0000000000..f7a5255a4a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodec.java @@ -0,0 +1,203 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse; +import net.firedevops.firemud.gamedesign.v1.StartSessionExactTemplateAssociationSelection; +import net.firedevops.firemud.gamedesign.v1.StartSessionTemplateWorldSourceAssociationEvidence; + +/** Closed public request/response mapping for the authenticated StartSession owner read. */ +public final class StartSessionTemplateAssociationReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private StartSessionTemplateAssociationReadGrpcCodec() {} + + public static ReadStartSessionTemplateAssociationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var builder = + ReadStartSessionTemplateAssociationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalPostAuthorizationTuple( + ByteString.copyFrom(request.canonicalPostAuthorizationTuple())) + .setOwnerAttemptId(request.ownerAttemptId().toString()) + .setOwnerFence(request.ownerFence()); + if (request.selection() instanceof InitialConfigured) { + builder.setInitialConfigured( + net.firedevops.firemud.gamedesign.v1.StartSessionConfiguredTemplateSelection + .getDefaultInstance()); + } else if (request.selection() instanceof ExactReplay replay) { + builder.setExactReplay( + StartSessionExactTemplateAssociationSelection.newBuilder() + .setCanonicalVersionId(replay.canonicalVersionId().toString()) + .setSelectedCommitId(replay.selectedCommitId().toString()) + .setPublishWorkflowId(replay.publishWorkflowId()) + .setAssociationDigest(replay.associationDigest())); + } else { + throw new IllegalArgumentException("Unsupported template association selection mode"); + } + return builder.build(); + } + + /** Decode only after the receiver authenticated its exact same-namespace Game Session peer. */ + public static Request fromRequest(ReadStartSessionTemplateAssociationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadStartSessionTemplateAssociationRequest"); + try { + var selection = + switch (request.getSelectionCase()) { + case INITIAL_CONFIGURED -> new InitialConfigured(); + case EXACT_REPLAY -> + new ExactReplay( + parseCanonicalUuid( + request.getExactReplay().getCanonicalVersionId(), "canonicalVersionId"), + parseCanonicalUuid( + request.getExactReplay().getSelectedCommitId(), "selectedCommitId"), + request.getExactReplay().getPublishWorkflowId(), + request.getExactReplay().getAssociationDigest()); + case SELECTION_NOT_SET -> + throw new IllegalArgumentException( + "Explicit initial or exact replay mode required"); + }; + return new Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalUuid(request.getReadRequestId(), "readRequestId"), + request.getCanonicalPostAuthorizationTuple().toByteArray(), + parseCanonicalUuid(request.getOwnerAttemptId(), "ownerAttemptId"), + request.getOwnerFence(), + selection); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Canonical StartSession template association request required", invalid); + } + } + + public static ReadStartSessionTemplateAssociationResponse toResponse(Result result) { + Objects.requireNonNull(result, "result"); + Association association = result.association(); + var worldRequest = + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(association.worldReadRequest()); + var worldResponse = + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse( + association.worldReadRequest(), association.worldReceipt()); + var associationMessage = + StartSessionTemplateWorldSourceAssociationEvidence.newBuilder() + .setCanonicalTenantId(association.canonicalTenantId().toString()) + .setTemplateId(association.templateId()) + .setCanonicalVersionId(association.canonicalVersionId().toString()) + .setSelectedCommitId(association.selectedCommitId().toString()) + .setPublishWorkflowId(association.publishWorkflowId()) + .setPublicationSelectionDigest(association.publicationSelectionDigest()) + .setAssociationDigest(association.associationDigest()) + .setTargetNamespace(association.targetNamespace()) + .setIntakeRequestId(association.intakeRequestId().toString()) + .setWorldOperationId(association.worldOperationId().toString()) + .setSourceOperationId(association.sourceOperationId().toString()) + .setWorldSlug(association.worldSlug()) + .setSourceEvidenceDigest(association.sourceEvidenceDigest()) + .setWorldReadRequest(worldRequest) + .setWorldReadResponse(worldResponse); + return ReadStartSessionTemplateAssociationResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setAssociation(associationMessage) + .setReleaseBundle(result.releaseBundle()) + .setWorldPublishedStartLocationEvidence( + ByteString.copyFrom(result.worldPublishedStartLocationEvidence().canonicalBytes())) + .setReferencePhaseEpoch(result.phaseEpoch()) + .build(); + } + + /** Validates the full exact request echo and every public release/source correlation. */ + public static Result fromResponse( + Request expectedRequest, ReadStartSessionTemplateAssociationResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadStartSessionTemplateAssociationResponse"); + if (!response.hasRequest() || !response.hasAssociation() || !response.hasReleaseBundle()) { + throw new IllegalArgumentException( + "Complete exact template association read response required"); + } + Request echoed = fromRequest(response.getRequest()); + if (!expectedRequest.equals(echoed)) { + throw new IllegalArgumentException("Game Design changed the exact read request echo"); + } + var wireAssociation = response.getAssociation(); + if (!wireAssociation.hasWorldReadRequest() || !wireAssociation.hasWorldReadResponse()) { + throw new IllegalArgumentException("Complete public World source receipt is required"); + } + Association association = + Association.fromStoredProjection( + parseCanonicalUuid(wireAssociation.getCanonicalTenantId(), "canonicalTenantId"), + wireAssociation.getTemplateId(), + parseCanonicalUuid(wireAssociation.getCanonicalVersionId(), "canonicalVersionId"), + parseCanonicalUuid(wireAssociation.getSelectedCommitId(), "selectedCommitId"), + wireAssociation.getPublishWorkflowId(), + wireAssociation.getPublicationSelectionDigest(), + wireAssociation.getAssociationDigest(), + wireAssociation.getTargetNamespace(), + parseCanonicalUuid(wireAssociation.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalUuid(wireAssociation.getWorldOperationId(), "worldOperationId"), + parseCanonicalUuid(wireAssociation.getSourceOperationId(), "sourceOperationId"), + wireAssociation.getWorldSlug(), + wireAssociation.getSourceEvidenceDigest(), + wireAssociation.getWorldReadRequest(), + wireAssociation.getWorldReadResponse()); + WorldPublishedStartLocationEvidence worldEvidence = + WorldPublishedStartLocationEvidence.fromStored( + response.getWorldPublishedStartLocationEvidence().toByteArray()); + try { + return new Result( + expectedRequest, + association, + response.getReleaseBundle(), + worldEvidence, + response.getReferencePhaseEpoch()); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Game Design returned conflicting association, release, or phase evidence", invalid); + } + } + + private static UUID parseCanonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, field)); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) continue; + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java new file mode 100644 index 0000000000..d7476b32f2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.common.gamesession; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** + * Exact selector and readback evidence for a Game Session-owned launch association. + * + *

Value construction and codec validation alone do not authenticate the owner; the explicit mTLS + * client establishes the Game Session peer before accepting response headers or content. + */ +public final class CanonicalGameInstanceLaunchAssociationReadEvidence { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + private CanonicalGameInstanceLaunchAssociationReadEvidence() {} + + /** Separate transient read identity and the complete immutable association selector. */ + public record Request( + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID gameInstanceUuid, + String controlPlaneRequestId, + String launchDescriptorId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationEvidenceDigest) { + public Request { + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireText(controlPlaneRequestId, "controlPlaneRequestId"); + requireText(launchDescriptorId, "launchDescriptorId"); + requireDigest(expectedDescriptorRequestDigest, "expectedDescriptorRequestDigest"); + requireDigest(expectedDescriptorResultDigest, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationEvidenceDigest, "expectedReleaseAttestationEvidenceDigest"); + } + } + + /** Current Game Session row states; these do not represent World lifecycle or admission. */ + public enum CurrentGameInstanceStatus { + STARTING, + RUNNING, + STOPPING, + STOPPED + } + + /** + * The exact World composition result, including the original owner attempt identity and the + * independently closed descriptor/release pair. The identity is read evidence, not a reusable + * owner claim or lifecycle authority. + */ + public record Result( + Request request, + UUID playableStateNamespaceId, + RealmEntryPolicy.StateScope playableStateScope, + boolean publicProduction, + CurrentGameInstanceStatus currentGameInstanceStatus, + long currentRowVersion, + UUID ownerAttemptId, + long ownerFence, + CompleteLaunchBindingEvidence launchBindingEvidence) { + public Result { + Objects.requireNonNull(request, "request"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (playableStateScope != RealmEntryPolicy.StateScope.SHARED) { + throw new IllegalArgumentException( + "Launch association read requires SHARED playable state"); + } + if (!publicProduction) { + throw new IllegalArgumentException("Launch association read requires public production"); + } + Objects.requireNonNull(currentGameInstanceStatus, "currentGameInstanceStatus"); + if (currentRowVersion < 0) { + throw new IllegalArgumentException("currentRowVersion must not be negative"); + } + requireNonNil(ownerAttemptId, "ownerAttemptId"); + if (ownerFence <= 0) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + Objects.requireNonNull(launchBindingEvidence, "launchBindingEvidence"); + var descriptor = launchBindingEvidence.descriptor(); + descriptor.requireValid(); + launchBindingEvidence.releaseAttestation().requireValid(descriptor); + if (!request.targetNamespace().equals(descriptor.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.worldSlug().equals(descriptor.worldSlug()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(launchBindingEvidence.releaseAttestation().evidenceDigest())) { + throw new IllegalArgumentException( + "Launch association read result differs from its exact selector or complete binding"); + } + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank() || value.length() > 256) { + throw new IllegalArgumentException(name + " must be non-blank and bounded"); + } + } + + private static void requireDigest(String value, String name) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java new file mode 100644 index 0000000000..8fe3d7f7d0 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodec.java @@ -0,0 +1,534 @@ +package net.firedevops.firemud.common.tenant; + +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; + +/** Closed request mapping and exact echo validation for the World authored-source intake RPCs. */ +public final class WorldAuthoredSourceIntakeGrpcCodec { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String REQUEST_DIGEST_DOMAIN = "world-authored-source-intake-request/v1"; + + /** Complete canonical binding accepted by intake and echoed by both complete-selector RPCs. */ + public record IntakeRequest( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest) { + public IntakeRequest { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source intake version"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireDigest(expectedSourceEvidenceDigest, "expectedSourceEvidenceDigest"); + } + } + + /** A committed World receipt read using a distinct request identity and the full intake tuple. */ + public record ReadRequest(IntakeRequest binding, UUID requestId) { + public ReadRequest { + Objects.requireNonNull(binding, "binding"); + requireNonNil(requestId, "requestId"); + if (requestId.equals(binding.intakeRequestId())) { + throw new IllegalArgumentException("Read requestId must differ from intakeRequestId"); + } + } + } + + /** Public receipt fields. receiptDigest is opaque because it also binds World's private key. */ + public record CommittedReceipt( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID operationId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + String requestDigest, + String receiptDigest) { + public CommittedReceipt { + IntakeRequest binding = + new IntakeRequest( + schemaVersion, + targetNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest); + requireNonNil(operationId, "operationId"); + requireDigest(requestDigest, "requestDigest"); + requireDigest(receiptDigest, "receiptDigest"); + if (!WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding).equals(requestDigest)) { + throw new IllegalArgumentException("World intake requestDigest does not match its binding"); + } + } + } + + /** Closed read selector that does not require caller-supplied source fields. */ + public record ByIdReadRequest( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + UUID intakeRequestId, + UUID canonicalTenantId) { + public ByIdReadRequest { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source intake version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical targetNamespace is required"); + } + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (readRequestId.equals(intakeRequestId)) { + throw new IllegalArgumentException("Read requestId must differ from intakeRequestId"); + } + } + } + + /** Full public portion of a retained World intake receipt and its immutable source evidence. */ + public record PublicReceipt( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID operationId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + String requestDigest, + String receiptDigest, + AuthoredWorldSourceEvidence source) { + public PublicReceipt { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source intake version"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(operationId, "operationId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireDigest(sourceEvidenceDigest, "sourceEvidenceDigest"); + requireDigest(requestDigest, "requestDigest"); + requireDigest(receiptDigest, "receiptDigest"); + Objects.requireNonNull(source, "source"); + if (!"NEW_GAME_ROW".equals(source.provenanceKind()) + || !targetNamespace.equals(source.targetNamespace()) + || !canonicalTenantId.equals(source.canonicalTenantId()) + || !worldSlug.equals(source.worldSlug()) + || !sourceOperationId.equals(source.operationId()) + || !sourceEvidenceDigest.equals(source.evidenceDigest())) { + throw new IllegalArgumentException( + "World intake receipt differs from its complete fresh source evidence"); + } + IntakeRequest binding = + new IntakeRequest( + schemaVersion, + targetNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest); + if (!WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding).equals(requestDigest)) { + throw new IllegalArgumentException("World intake requestDigest does not match its source"); + } + } + } + + private WorldAuthoredSourceIntakeGrpcCodec() {} + + /** Encodes exactly the validated original intake binding. */ + public static IntakeAuthoredWorldSourceRequest toIntakeRequest(IntakeRequest request) { + Objects.requireNonNull(request, "request"); + return IntakeAuthoredWorldSourceRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .build(); + } + + /** Encodes the full intake binding and the caller-owned read request identity. */ + public static ReadAuthoredWorldSourceIntakeRequest toReadRequest(ReadRequest request) { + Objects.requireNonNull(request, "request"); + IntakeRequest binding = request.binding(); + return ReadAuthoredWorldSourceIntakeRequest.newBuilder() + .setSchemaVersion(binding.schemaVersion()) + .setTargetNamespace(binding.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setIntakeRequestId(binding.intakeRequestId().toString()) + .setCanonicalTenantId(binding.canonicalTenantId().toString()) + .setWorldSlug(binding.worldSlug()) + .setSourceOperationId(binding.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(binding.expectedSourceEvidenceDigest()) + .build(); + } + + /** Decodes the complete closed intake request before any owner access. */ + public static IntakeRequest fromIntakeRequest(IntakeAuthoredWorldSourceRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "IntakeAuthoredWorldSource request"); + return new IntakeRequest( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getSourceOperationId(), "sourceOperationId"), + request.getExpectedSourceEvidenceDigest()); + } + + /** Decodes a closed exact-read request; requestId belongs only to the read itself. */ + public static ReadRequest fromReadRequest(ReadAuthoredWorldSourceIntakeRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadAuthoredWorldSourceIntake request"); + IntakeRequest binding = + new IntakeRequest( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getSourceOperationId(), "sourceOperationId"), + request.getExpectedSourceEvidenceDigest()); + return new ReadRequest(binding, parseCanonicalNonNilUuid(request.getRequestId(), "requestId")); + } + + /** Encodes only a fully validated committed receipt and its exact original request binding. */ + public static IntakeAuthoredWorldSourceResponse toIntakeResponse( + IntakeRequest request, CommittedReceipt receipt) { + requireExactBinding(request, receipt); + return IntakeAuthoredWorldSourceResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .setOperationId(receipt.operationId().toString()) + .setRequestDigest(receipt.requestDigest()) + .setReceiptDigest(receipt.receiptDigest()) + .build(); + } + + /** Encodes a fully validated committed receipt and echoes the distinct read identity. */ + public static ReadAuthoredWorldSourceIntakeResponse toReadResponse( + ReadRequest request, CommittedReceipt receipt) { + Objects.requireNonNull(request, "request"); + requireExactBinding(request.binding(), receipt); + return ReadAuthoredWorldSourceIntakeResponse.newBuilder() + .setSchemaVersion(request.binding().schemaVersion()) + .setTargetNamespace(request.binding().targetNamespace()) + .setRequestId(request.requestId().toString()) + .setIntakeRequestId(request.binding().intakeRequestId().toString()) + .setCanonicalTenantId(request.binding().canonicalTenantId().toString()) + .setWorldSlug(request.binding().worldSlug()) + .setSourceOperationId(request.binding().sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.binding().expectedSourceEvidenceDigest()) + .setOperationId(receipt.operationId().toString()) + .setRequestDigest(receipt.requestDigest()) + .setReceiptDigest(receipt.receiptDigest()) + .build(); + } + + /** Encodes a closed exact source-receipt read selected only by retained intake identity. */ + public static ReadAuthoredWorldSourceIntakeByIdRequest toReadByIdRequest( + ByIdReadRequest request) { + Objects.requireNonNull(request, "request"); + return ReadAuthoredWorldSourceIntakeByIdRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .build(); + } + + /** Decodes the complete closed ID-based read before any owner access. */ + public static ByIdReadRequest fromReadByIdRequest( + ReadAuthoredWorldSourceIntakeByIdRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadAuthoredWorldSourceIntakeById request"); + return new ByIdReadRequest( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + parseCanonicalNonNilUuid(request.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId")); + } + + /** + * Encodes the exact read echo and complete public receipt; World-private keys are not emitted. + */ + public static ReadAuthoredWorldSourceIntakeByIdResponse toReadByIdResponse( + ByIdReadRequest request, PublicReceipt receipt) { + requireReceiptForByIdRequest(request, receipt); + return ReadAuthoredWorldSourceIntakeByIdResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setReceipt(toProtoReceipt(receipt)) + .build(); + } + + /** Validates exact echo, receipt identity and every source-evidence digest from the owner. */ + public static PublicReceipt fromReadByIdResponse( + ByIdReadRequest request, ReadAuthoredWorldSourceIntakeByIdResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadAuthoredWorldSourceIntakeById response"); + ByIdReadRequest echoed = + new ByIdReadRequest( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getReadRequestId(), "readRequestId"), + parseCanonicalNonNilUuid(response.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId")); + if (!request.equals(echoed)) { + throw new IllegalArgumentException( + "World authored-source intake by-ID response does not echo the exact request"); + } + if (!response.hasReceipt()) { + throw new IllegalArgumentException("World authored-source intake by-ID receipt is required"); + } + PublicReceipt receipt = fromProtoReceipt(response.getReceipt()); + requireReceiptForByIdRequest(request, receipt); + return receipt; + } + + private static void requireReceiptForByIdRequest(ByIdReadRequest request, PublicReceipt receipt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(receipt, "receipt"); + if (request.schemaVersion() != receipt.schemaVersion() + || !request.targetNamespace().equals(receipt.targetNamespace()) + || !request.intakeRequestId().equals(receipt.intakeRequestId()) + || !request.canonicalTenantId().equals(receipt.canonicalTenantId())) { + throw new IllegalArgumentException( + "World authored-source intake receipt differs from the exact by-ID request"); + } + } + + private static net.firedevops.firemud.worldmanagement.v1.AuthoredWorldSourceIntakePublicReceipt + toProtoReceipt(PublicReceipt receipt) { + var source = receipt.source(); + var sourceBuilder = + net.firedevops.firemud.worldmanagement.v1.AuthoredWorldSourceEvidence.newBuilder() + .setSchemaVersion(source.schemaVersion()) + .setTargetNamespace(source.targetNamespace()) + .setRegistrationRequestId(source.registrationRequestId().toString()) + .setOperationId(source.operationId().toString()) + .setRequestDigest(source.requestDigest()) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setTenantSlug(source.tenantSlug()) + .setWorldSlug(source.worldSlug()) + .setWorldDisplayName(source.worldDisplayName()) + .setSourceGameRowId(source.sourceGameRowId()) + .setSourceGameTenantKey(source.sourceGameTenantKey()) + .setProvenanceKind(source.provenanceKind()) + .setEvidenceDigest(source.evidenceDigest()); + return net.firedevops.firemud.worldmanagement.v1.AuthoredWorldSourceIntakePublicReceipt + .newBuilder() + .setSchemaVersion(receipt.schemaVersion()) + .setTargetNamespace(receipt.targetNamespace()) + .setIntakeRequestId(receipt.intakeRequestId().toString()) + .setOperationId(receipt.operationId().toString()) + .setCanonicalTenantId(receipt.canonicalTenantId().toString()) + .setWorldSlug(receipt.worldSlug()) + .setSourceOperationId(receipt.sourceOperationId().toString()) + .setSourceEvidenceDigest(receipt.sourceEvidenceDigest()) + .setRequestDigest(receipt.requestDigest()) + .setReceiptDigest(receipt.receiptDigest()) + .setSource(sourceBuilder) + .build(); + } + + private static PublicReceipt fromProtoReceipt( + net.firedevops.firemud.worldmanagement.v1.AuthoredWorldSourceIntakePublicReceipt receipt) { + Objects.requireNonNull(receipt, "receipt"); + requireNoUnknownFields(receipt, "AuthoredWorldSourceIntakePublicReceipt"); + if (!receipt.hasSource()) { + throw new IllegalArgumentException("Complete authored-world source evidence is required"); + } + var source = receipt.getSource(); + requireNoUnknownFields(source, "AuthoredWorldSourceEvidence"); + AuthoredWorldSourceEvidence evidence = + new AuthoredWorldSourceEvidence( + source.getSchemaVersion(), + source.getTargetNamespace(), + parseCanonicalNonNilUuid(source.getRegistrationRequestId(), "registrationRequestId"), + parseCanonicalNonNilUuid(source.getOperationId(), "sourceOperationId"), + source.getRequestDigest(), + parseCanonicalNonNilUuid(source.getCanonicalTenantId(), "canonicalTenantId"), + source.getTenantSlug(), + source.getWorldSlug(), + source.getWorldDisplayName(), + source.getSourceGameRowId(), + source.getSourceGameTenantKey(), + source.getProvenanceKind(), + source.getEvidenceDigest()); + return new PublicReceipt( + receipt.getSchemaVersion(), + receipt.getTargetNamespace(), + parseCanonicalNonNilUuid(receipt.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(receipt.getOperationId(), "operationId"), + parseCanonicalNonNilUuid(receipt.getCanonicalTenantId(), "canonicalTenantId"), + receipt.getWorldSlug(), + parseCanonicalNonNilUuid(receipt.getSourceOperationId(), "sourceOperationId"), + receipt.getSourceEvidenceDigest(), + receipt.getRequestDigest(), + receipt.getReceiptDigest(), + evidence); + } + + /** Validates all echoed request fields and the public, owner-authenticated receipt fields. */ + public static CommittedReceipt fromIntakeResponse( + IntakeRequest request, IntakeAuthoredWorldSourceResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "IntakeAuthoredWorldSource response"); + IntakeRequest echoed = + new IntakeRequest( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId"), + response.getWorldSlug(), + parseCanonicalNonNilUuid(response.getSourceOperationId(), "sourceOperationId"), + response.getExpectedSourceEvidenceDigest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException("World intake response does not echo the exact request"); + } + return new CommittedReceipt( + echoed.schemaVersion(), + echoed.targetNamespace(), + echoed.intakeRequestId(), + parseCanonicalNonNilUuid(response.getOperationId(), "operationId"), + echoed.canonicalTenantId(), + echoed.worldSlug(), + echoed.sourceOperationId(), + echoed.expectedSourceEvidenceDigest(), + response.getRequestDigest(), + response.getReceiptDigest()); + } + + /** Validates the separate read identity, full original binding, and committed receipt. */ + public static CommittedReceipt fromReadResponse( + ReadRequest request, ReadAuthoredWorldSourceIntakeResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadAuthoredWorldSourceIntake response"); + IntakeRequest echoed = + new IntakeRequest( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId"), + response.getWorldSlug(), + parseCanonicalNonNilUuid(response.getSourceOperationId(), "sourceOperationId"), + response.getExpectedSourceEvidenceDigest()); + UUID echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "requestId"); + if (!request.binding().equals(echoed) || !request.requestId().equals(echoedRequestId)) { + throw new IllegalArgumentException( + "World intake read response does not echo the exact request"); + } + return new CommittedReceipt( + echoed.schemaVersion(), + echoed.targetNamespace(), + echoed.intakeRequestId(), + parseCanonicalNonNilUuid(response.getOperationId(), "operationId"), + echoed.canonicalTenantId(), + echoed.worldSlug(), + echoed.sourceOperationId(), + echoed.expectedSourceEvidenceDigest(), + response.getRequestDigest(), + response.getReceiptDigest()); + } + + /** Recomputable request digest defined by the World intake contract. */ + public static String requestDigest(IntakeRequest request) { + Objects.requireNonNull(request, "request"); + return GameTenantCreationDigest.digest( + REQUEST_DIGEST_DOMAIN, + request.targetNamespace(), + request.intakeRequestId().toString(), + request.canonicalTenantId().toString(), + request.worldSlug(), + request.sourceOperationId().toString(), + request.expectedSourceEvidenceDigest()); + } + + private static void requireExactBinding(IntakeRequest request, CommittedReceipt receipt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(receipt, "receipt"); + if (receipt.schemaVersion() != request.schemaVersion() + || !receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.intakeRequestId().equals(request.intakeRequestId()) + || !receipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !receipt.worldSlug().equals(request.worldSlug()) + || !receipt.sourceOperationId().equals(request.sourceOperationId()) + || !receipt.sourceEvidenceDigest().equals(request.expectedSourceEvidenceDigest()) + || !receipt.requestDigest().equals(requestDigest(request))) { + throw new IllegalArgumentException( + "World committed receipt does not match the exact request"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + 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); + } + requireNonNil(parsed, label); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, String label) { + if (!GameTenantCreationDigest.isDigest(value)) { + throw new IllegalArgumentException(label + " must be canonical SHA-256 text"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java index 73e7691e73..c203eea267 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java @@ -438,7 +438,7 @@ public record Request( requireText(publishWorkflowId, "publishWorkflowId"); requireText(appliedCommitId, "appliedCommitId"); requireSha256(contentDigest, "contentDigest"); - if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + if (digestSchemaVersion != 2 && digestSchemaVersion != 3 && digestSchemaVersion != 4) { throw new IllegalArgumentException("Unsupported World digest schema version"); } Objects.requireNonNull(worldAffectedTuples, "worldAffectedTuples"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java new file mode 100644 index 0000000000..76c4839df2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java @@ -0,0 +1,687 @@ +package net.firedevops.firemud.common.account; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.Timestamp; +import com.google.protobuf.UnknownFieldSet; +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 io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +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.CertificateEncodingException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +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.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +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 tools.jackson.databind.json.JsonMapper; + +/** Physical mTLS proof for Game Design's read-only Account redeemed-operation projection client. */ +class StartSessionRedeemedOperationProjectionClientTest { + 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 OPAQUE_REFERENCE = "opaque-reference-never-sent"; + private static final String FORWARDED_JWT = "header.payload.signature"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID ACTOR_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("52345678-1234-4234-8234-123456789abc"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("62345678-1234-4234-8234-123456789abc"); + private static final UUID CONTROL_UI_JTI = + UUID.fromString("72345678-1234-4234-8234-123456789abc"); + private static final long RESERVATION_FENCE = 4L; + private static final long OWNER_FENCE = 9L; + private static final long ISSUANCE_FENCE = 23L; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final Instant CLOCK_NOW = Instant.parse("2035-01-01T00:00:00Z"); + private static final Clock FIXED_CLOCK = Clock.fixed(CLOCK_NOW, ZoneOffset.UTC); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private Server server; + private StartSessionRedeemedOperationProjectionClient client; + private AtomicInteger applicationCalls; + private AtomicReference receivedPeer; + private AtomicReference receivedRequest; + private CountDownLatch timeoutRelease; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (timeoutRelease != null) { + timeoutRelease.countDown(); + } + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void exactSameNamespaceWorkloadsReadTheOriginalProjectionOverPhysicalMtls() throws Exception { + Fixture fixture = fixture(CLOCK_NOW.plusSeconds(3_600L)); + startServer(fixture, ResponseMode.EXACT); + client = newClient(server); + client.init(); + + ReadRedeemedOperationProjectionResponse response = + client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE); + + assertThat(response.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly( + fixture + .postTuple() + .preAuthorizationTuple() + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)); + assertThat(response.getAuthorityEvidenceBundle().toByteArray()) + .containsExactly(fixture.postTuple().authorityEvidenceBundleBytes()); + assertThat(applicationCalls).hasValue(1); + assertThat(receivedPeer.get()) + .isNotNull() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(GAME_DESIGN_URI); + assertThat(receivedRequest.get().getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(receivedRequest.get().getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly( + fixture + .postTuple() + .preAuthorizationTuple() + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)); + assertThat(receivedRequest.get().getReservationOwnerId()) + .isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(receivedRequest.get().getReservationClaimFence()).isEqualTo(RESERVATION_FENCE); + assertThat(receivedRequest.get().getOwnerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID.toString()); + assertThat(receivedRequest.get().getOwnerFence()).isEqualTo(OWNER_FENCE); + assertThat(receivedRequest.get().toString()) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FORWARDED_JWT); + } + + @Test + void rejectsChangedOperationBindingAndUnknownResponseFields() throws Exception { + Fixture fixture = fixture(CLOCK_NOW.plusSeconds(3_600L)); + startServer(fixture, ResponseMode.CHANGED_DIGEST); + client = newClient(server); + client.init(); + + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid redeemed StartSession operation projection"); + assertThat(applicationCalls).hasValue(1); + + stopTransport(); + startServer(fixture, ResponseMode.UNKNOWN_FIELD); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid redeemed StartSession operation projection"); + } + + @Test + void rejectsExpiredAccountReferenceEvenWhenResponseEchoesOriginalBundle() throws Exception { + Fixture fixture = fixture(CLOCK_NOW.minusSeconds(60L)); + startServer(fixture, ResponseMode.EXACT); + client = newClient(server); + client.init(); + + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid redeemed StartSession operation projection"); + assertThat(applicationCalls).hasValue(1); + } + + @Test + void boundedDeadlineLeavesTransportUncertaintyAndDoesNotRetry() throws Exception { + Fixture fixture = fixture(CLOCK_NOW.plusSeconds(3_600L)); + startServer(fixture, ResponseMode.BLOCK_UNTIL_RELEASED); + client = newClient(server); + client.init(); + + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(applicationCalls).hasValue(1); + } + + @Test + void refusesReadOutsideConfiguredNamespaceAndBeforeExplicitInitialization() throws Exception { + Fixture fixture = fixture(CLOCK_NOW.plusSeconds(3_600L)); + Fixture otherNamespaceFixture = fixture(CLOCK_NOW.plusSeconds(3_600L), "other"); + client = newClientPropertiesOnly(); + + assertThatThrownBy( + () -> client.read(otherNamespaceFixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.read(fixture.postTuple(), new UUID(0L, 0L), OWNER_FENCE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not be nil"); + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be positive"); + } + + private void startServer(Fixture fixture, ResponseMode mode) throws Exception { + applicationCalls = new AtomicInteger(); + receivedPeer = new AtomicReference<>(); + receivedRequest = new AtomicReference<>(); + timeoutRelease = new CountDownLatch(1); + var service = + new StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceImplBase() { + @Override + public void readRedeemedOperationProjection( + ReadRedeemedOperationProjectionRequest request, + StreamObserver observer) { + applicationCalls.incrementAndGet(); + receivedPeer.set(GrpcPeerIdentity.current()); + receivedRequest.set(request); + if (mode == ResponseMode.BLOCK_UNTIL_RELEASED) { + try { + if (!timeoutRelease.await(10, TimeUnit.SECONDS)) { + observer.onError(Status.DEADLINE_EXCEEDED.asRuntimeException()); + return; + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + observer.onError(Status.CANCELLED.asRuntimeException()); + return; + } + } + + ReadRedeemedOperationProjectionResponse response = response(fixture); + if (mode == ResponseMode.CHANGED_DIGEST) { + response = response.toBuilder().setMutationDigest("0".repeat(64)).build(); + } else if (mode == ResponseMode.UNKNOWN_FIELD) { + response = + response.toBuilder() + .mergeUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + 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(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private StartSessionRedeemedOperationProjectionClient newClient(Server target) + throws IOException, CertificateEncodingException { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + target.getPort()); + return new StartSessionRedeemedOperationProjectionClient( + endpoints, + pki.clientProperties(tempDirectory), + new GrpcChannelFactory(), + NAMESPACE, + FIXED_CLOCK); + } + + private StartSessionRedeemedOperationProjectionClient newClientPropertiesOnly() throws Exception { + return new StartSessionRedeemedOperationProjectionClient( + new ServiceEndpointsProperties(), + pki.clientProperties(tempDirectory), + new GrpcChannelFactory(), + NAMESPACE, + FIXED_CLOCK); + } + + private static ReadRedeemedOperationProjectionResponse response(Fixture fixture) { + StartSessionPostAuthorizationExecutionTuple postTuple = fixture.postTuple(); + StartSessionAuthorityEvidenceBundle.BundleReference reference = postTuple.bundleReference(); + String targetNamespace = postTuple.preAuthorizationTuple().action().scope().targetNamespace(); + return ReadRedeemedOperationProjectionResponse.newBuilder() + .setControlPlaneRequestId(postTuple.controlPlaneRequestId()) + .setCanonicalPreAuthorizationTupleBytes( + com.google.protobuf.ByteString.copyFrom( + postTuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setMutationDigest(postTuple.mutationDigest()) + .setAuthorizationReferenceFingerprint(postTuple.authorizationReferenceFingerprint()) + .setReservationOwnerId(postTuple.reservationOwnerId().toString()) + .setReservationClaimFence(postTuple.reservationClaimFence()) + .setAuthenticatedRedeemerWorkloadIdentity( + "spiffe://firemud/ns/" + targetNamespace + "/sa/game-session-service") + .setOwnerAttemptId(OWNER_ATTEMPT_ID.toString()) + .setOwnerFence(OWNER_FENCE) + .setReferenceExpiresAt(timestamp(fixture.referenceExpiresAt())) + .setRedeemedAt(timestamp(fixture.redeemedAt())) + .setIssuanceOperationId(ISSUANCE_OPERATION_ID.toString()) + .setIssuanceFence(ISSUANCE_FENCE) + .setBundleReference( + net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference.newBuilder() + .setBundleVersion(reference.bundleVersion()) + .setSourceVersion(reference.sourceVersion()) + .setSourceFence(reference.sourceFence()) + .setLinearization(reference.linearization()) + .build()) + .setAuthorityEvidenceBundle( + com.google.protobuf.ByteString.copyFrom(postTuple.authorityEvidenceBundleBytes())) + .build(); + } + + private static Fixture fixture(Instant expiresAt) { + return fixture(expiresAt, NAMESPACE); + } + + private static Fixture fixture(Instant expiresAt, String targetNamespace) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, targetNamespace), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Read original StartSession source projection"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "redeemed-projection-request-β", ACTOR_ID, action); + StartSessionAuthorityEvidenceBundle.BundleReference reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + Long.toString(ISSUANCE_FENCE), + "18446744073709551615"); + byte[] bundle = authorityEvidenceBundle(preTuple, expiresAt, targetNamespace); + StartSessionPostAuthorizationExecutionTuple postTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + targetNamespace + "/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER_ID, + RESERVATION_FENCE, + bundle, + reference); + Instant redeemedAt = + expiresAt.isAfter(CLOCK_NOW) ? CLOCK_NOW.minusSeconds(60L) : expiresAt.minusSeconds(60L); + return new Fixture(postTuple, expiresAt, redeemedAt); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple tuple, + Instant expiresAt, + String targetNamespace) { + String tenantId = TENANT_ID.toString(); + Map value = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", targetNamespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + expiresAt.minusSeconds(600L).toString(), + "expiresAt", + expiresAt.toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_OPERATION_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", Long.toString(ISSUANCE_FENCE), + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + CONTROL_UI_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException malformed) { + throw new IllegalStateException("could not encode test Account authority bundle", malformed); + } + } + + private static Timestamp timestamp(Instant value) { + return Timestamp.newBuilder() + .setSeconds(value.getEpochSecond()) + .setNanos(value.getNano()) + .build(); + } + + private enum ResponseMode { + EXACT, + CHANGED_DIGEST, + UNKNOWN_FIELD, + BLOCK_UNTIL_RELEASED + } + + private record Fixture( + StartSessionPostAuthorizationExecutionTuple postTuple, + Instant referenceExpiresAt, + Instant redeemedAt) {} + + private record TestIdentity(String alias, 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 projection 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"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + 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 IOException, CertificateEncodingException { + Path clientCertificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + gameDesignClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + gameDesignClient.privateKey().getEncoded()); + Path trustCa = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(trustCa.toString()); + return properties; + } + + 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"); + List 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", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java new file mode 100644 index 0000000000..a0d3a67a2c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java @@ -0,0 +1,502 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AuthoredWorldReleaseAttestationSelectorTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void v2BindsCompleteOriginalEvidenceInItsOwnDomainAndSurvivesStoredReadback() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var release = release(descriptor, selector); + var stored = JSON.writeValueAsString(release); + var readback = JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class); + + assertThat(release.schemaVersion()).isEqualTo(2); + assertThat(readback).isEqualTo(release); + readback.requireValid(descriptor); + assertThat( + new String( + AuthoredWorldReleaseAttestationEvidence.evidencePreimage(release), + StandardCharsets.UTF_8)) + .startsWith("49:game-design-authored-world-release-attestation/v2") + .contains("worldStartLocationEvidence.canonicalBytesBase64") + .endsWith(Base64.getEncoder().encodeToString(selector.canonicalBytes())); + assertThat(readback.worldStartLocationEvidence().selectorReceiptBytes()) + .containsExactly(selector.selectorReceiptBytes()); + assertThat(readback.worldStartLocationEvidence().originalAccountBindingBytes()) + .containsExactly(selector.originalAccountBindingBytes()); + assertThat(readback.worldStartLocationEvidence().appliedResultBytes()) + .containsExactly(selector.appliedResultBytes()); + } + + @Test + void v3BindsClosureQualifiedWorldSchema4InItsOwnDomainAndSurvivesStoredReadback() + throws Exception { + var selector = selectorEvidence(4); + var descriptor = descriptor(selector); + var release = release(descriptor, selector, 3); + var stored = JSON.writeValueAsString(release); + var readback = JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class); + + assertThat(release.schemaVersion()) + .isEqualTo(AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION); + assertThat(release.participantDigests().getFirst().digestSchemaVersion()).isEqualTo(4); + assertThat(release.participantDigests().getLast().digestSchemaVersion()).isEqualTo(2); + assertThat(readback).isEqualTo(release); + readback.requireValid(descriptor); + assertThat( + new String( + AuthoredWorldReleaseAttestationEvidence.evidencePreimage(release), + StandardCharsets.UTF_8)) + .startsWith("49:game-design-authored-world-release-attestation/v3") + .contains("worldStartLocationEvidence.canonicalBytesBase64") + .endsWith(Base64.getEncoder().encodeToString(selector.canonicalBytes())); + + var wrongWorldSchema = + release.participantDigests().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + "WORLD_MANAGEMENT".equals(participant.participantKey()) + ? 3 + : participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) + .toList(); + assertThatThrownBy( + () -> + AuthoredWorldReleaseAttestationEvidence.createClosureSelector( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + release.publishWorkflowId(), + release.commitId(), + wrongWorldSchema, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision(), + selector)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + } + + @Test + void terminalReleaseProjectionAcceptsExactV2AndV3OwnerSchemasAndRejectsMixedSchemas() + throws Exception { + for (int schema : List.of(2, 3)) { + var selector = schema == 3 ? selectorEvidence(4) : selectorEvidence(); + var attestation = release(descriptor(selector), selector, schema); + var content = terminalReleaseContent(attestation, attestation.participantDigests()); + + assertThat( + GameDesignPublicationTerminalEvidence.ReleaseContent.fromStored( + content.canonicalBytes())) + .isEqualTo(content); + + var mixedParticipants = + attestation.participantDigests().stream() + .map( + participant -> + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + 1, + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest()) + : participant) + .toList(); + assertThatThrownBy(() -> terminalReleaseContent(attestation, mixedParticipants)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Incomplete or changed required participant proof"); + } + } + + private static GameDesignPublicationTerminalEvidence.ReleaseContent terminalReleaseContent( + AuthoredWorldReleaseAttestationEvidence attestation, + List participants) { + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + attestation.canonicalTenantId(), + attestation.canonicalVersionId(), + attestation.publishedReleaseBundleRef(), + 1, + "v" + attestation.schemaVersion(), + attestation.publishWorkflowId(), + attestation.manifestHash(), + attestation.manifestSchemaVersion(), + attestation.artifactDigests(), + attestation.requiredManifestAssetKeys(), + participants.stream() + .map( + participant -> + new GameDesignPublicationTerminalEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent() + ? participant.abilitySchemaDigest() + : null, + null, + null)) + .toList(), + attestation.commandDefinitions(), + attestation.generationConfigRevision(), + attestation.worldStartLocationEvidence()); + } + + @Test + void v1BytesAndDigestRemainUnchangedAndCannotBePromotedBySupplyingASelector() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var current = release(descriptor, selector); + var old = + AuthoredWorldReleaseAttestationEvidence.create( + current.targetNamespace(), + current.descriptorResultDigest(), + current.canonicalTenantId(), + current.canonicalVersionId(), + current.worldSlug(), + current.authoredWorldSourceOperationId(), + current.authoredWorldSourceEvidenceDigest(), + current.launchDescriptorId(), + current.publishedReleaseBundleRef(), + current.versionStateEpoch(), + current.publishWorkflowId(), + current.commitId(), + retainedV1Participants(current.participantDigests()), + current.manifestHash(), + current.manifestSchemaVersion(), + current.requiredManifestAssetKeys(), + current.artifactDigests(), + current.commandDefinitions(), + current.generationConfigRevision()); + String stored = JSON.writeValueAsString(old); + assertThat(stored).doesNotContain("worldStartLocationEvidence"); + assertThat( + JSON.writeValueAsString( + JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class))) + .isEqualTo(stored); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(old) + .hasWorldStartLocationEvidence()) + .isFalse(); + assertThat(old.evidenceDigest()).isNotEqualTo(current.evidenceDigest()); + assertThatThrownBy(() -> copy(old, 1, selector)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(current, 2, null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(current, 3, selector)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(old, 2, selector).requireValid()) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void selectorSubstitutionAtAnOtherwiseValidCheckpointChangesTheDigest() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var release = release(descriptor, selector); + var request = selector.request(); + var other = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + UUID.randomUUID(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + assertThat(release(descriptor, other).evidenceDigest()).isNotEqualTo(release.evidenceDigest()); + assertThatThrownBy(() -> copy(release, 2, other).requireValid()) + .isInstanceOf(IllegalArgumentException.class); + var wrongCheckpoint = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + "other-workflow", + request.appliedCommitId(), + "c".repeat(64), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + assertThatThrownBy(() -> copy(release, 2, wrongCheckpoint)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void selectedAttestationRejectsRetainedSchemaOneControlPlaneEvidence() throws Exception { + var selector = selectorEvidence(); + var selected = release(descriptor(selector), selector); + var retained = retainedV1Participants(selected.participantDigests()); + assertThat(retained.getLast().digestSchemaVersion()).isEqualTo(1); + assertThat(selected.participantDigests().getLast().digestSchemaVersion()).isEqualTo(2); + assertThatThrownBy( + () -> + new AuthoredWorldReleaseAttestationEvidence( + selected.schemaVersion(), + selected.targetNamespace(), + selected.descriptorResultDigest(), + selected.canonicalTenantId(), + selected.canonicalVersionId(), + selected.worldSlug(), + selected.authoredWorldSourceOperationId(), + selected.authoredWorldSourceEvidenceDigest(), + selected.launchDescriptorId(), + selected.publishedReleaseBundleRef(), + selected.versionStateEpoch(), + selected.publishWorkflowId(), + selected.commitId(), + retained, + selected.manifestHash(), + selected.manifestSchemaVersion(), + selected.requiredManifestAssetKeys(), + selected.artifactDigests(), + selected.commandDefinitions(), + selected.generationConfigRevision(), + selected.evidenceDigest(), + selector)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + } + + private static List retainedV1Participants( + List selected) { + // Stipulated historical evidence, independently scoped to the retained-v1 contract. + return selected.stream() + .map( + p -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionIdPresent(), + p.baseVersionId(), + p.appliedCommitId(), + "GAME_DESIGN_CONTROL_PLANE".equals(p.participantKey()) + ? "e".repeat(64) + : p.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + p.participantKey(), AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION), + p.abilitySchemaDigestPresent(), + p.abilitySchemaDigest())) + .toList(); + } + + static WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + return selectorEvidence(3); + } + + private static WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVersion) + throws Exception { + var base = AuthoringFixtures.startLocationEvidence(); + var original = base.request(); + var request = + new WorldPublishedStartLocationEvidence.Request( + original.targetNamespace(), + original.canonicalTenantId(), + original.canonicalVersionId(), + original.intakeRequestId(), + original.publicationFence(), + original.publicationRequestId(), + original.requestDigest(), + original.versionStateEpoch(), + original.publishWorkflowId(), + original.appliedCommitId(), + original.contentDigest(), + digestSchemaVersion, + original.worldAffectedTuples()); + return new WorldPublishedStartLocationEvidence( + request, + base.selectorReceiptBytes(), + base.originalAccountBindingBytes(), + base.appliedResultBytes()); + } + + static AuthoredWorldLaunchDescriptorEvidence descriptor( + WorldPublishedStartLocationEvidence selector) { + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "launch-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "b".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor", + 42L, + false, + null, + "{}", + "generation", + 9L, + 7L, + "release", + false, + null); + } + + static AuthoredWorldReleaseAttestationEvidence release( + AuthoredWorldLaunchDescriptorEvidence descriptor, + WorldPublishedStartLocationEvidence selector) { + return release( + descriptor, selector, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + } + + private static AuthoredWorldReleaseAttestationEvidence release( + AuthoredWorldLaunchDescriptorEvidence descriptor, + WorldPublishedStartLocationEvidence selector, + int attestationSchemaVersion) { + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, attestationSchemaVersion), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + if (attestationSchemaVersion + == AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION) { + return AuthoredWorldReleaseAttestationEvidence.createClosureSelector( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + selector); + } + return AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + selector); + } + + private static AuthoredWorldReleaseAttestationEvidence copy( + AuthoredWorldReleaseAttestationEvidence old, + int schema, + WorldPublishedStartLocationEvidence selector) { + return new AuthoredWorldReleaseAttestationEvidence( + schema, + old.targetNamespace(), + old.descriptorResultDigest(), + old.canonicalTenantId(), + old.canonicalVersionId(), + old.worldSlug(), + old.authoredWorldSourceOperationId(), + old.authoredWorldSourceEvidenceDigest(), + old.launchDescriptorId(), + old.publishedReleaseBundleRef(), + old.versionStateEpoch(), + old.publishWorkflowId(), + old.commitId(), + old.participantDigests(), + old.manifestHash(), + old.manifestSchemaVersion(), + old.requiredManifestAssetKeys(), + old.artifactDigests(), + old.commandDefinitions(), + old.generationConfigRevision(), + old.evidenceDigest(), + selector); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java new file mode 100644 index 0000000000..2be666331d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java @@ -0,0 +1,527 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.StartSessionLaunchDescriptorApplicationFailure; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionLaunchDescriptorGrpcCodecTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID REGISTRATION_ID = uuid("03333333-3333-4333-8333-333333333333"); + private static final UUID INTAKE_ID = uuid("04444444-4444-4444-8444-444444444444"); + private static final UUID WORLD_OPERATION_ID = uuid("05555555-5555-4555-8555-555555555555"); + private static final UUID SOURCE_OPERATION_ID = uuid("06666666-6666-4666-8666-666666666666"); + private static final UUID WORLD_READ_ID = uuid("07777777-7777-4777-8777-777777777777"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "test"; + private static final String WORLD_SLUG = "synthetic-world"; + private static final String CONTROL_PLANE_REQUEST_ID = "original-control-plane-request"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void exactReplayCarriesItsOriginalAssociationAndDescriptorWithoutUsingReadIdAsOperationId() + throws Exception { + Fixture fixture = fixture(); + var wireRequest = StartSessionLaunchDescriptorGrpcCodec.toRequest(fixture.request()); + var response = + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), fixture.descriptor()); + + var decoded = StartSessionLaunchDescriptorGrpcCodec.fromResponse(fixture.request(), response); + + assertThat(StartSessionLaunchDescriptorGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(fixture.request()); + assertThat(decoded.associationRead().request()).isEqualTo(fixture.request()); + assertThat(decoded.associationRead().request().readRequestId()) + .isNotEqualTo(fixture.descriptor().controlPlaneRequestId()); + assertThat( + ((StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome) decoded.outcome()) + .descriptor()) + .isEqualTo(fixture.descriptor()); + assertThat(response.getAssociationRead().getRequest().getExactReplay().getAssociationDigest()) + .isEqualTo(fixture.associationRead().association().associationDigest()); + } + + @Test + void rejectsInitialSelectionPartialMixedUnknownAndWrongVersionResponses() throws Exception { + Fixture fixture = fixture(); + var exact = StartSessionLaunchDescriptorGrpcCodec.toRequest(fixture.request()); + var initial = + exact.toBuilder() + .clearSelection() + .setInitialConfigured( + net.firedevops.firemud.gamedesign.v1.StartSessionConfiguredTemplateSelection + .getDefaultInstance()) + .build(); + assertThatThrownBy(() -> StartSessionLaunchDescriptorGrpcCodec.fromRequest(initial)) + .isInstanceOf(IllegalArgumentException.class); + + var complete = + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), fixture.descriptor()); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), complete.toBuilder().clearLaunchDescriptor().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), + complete.toBuilder() + .setApplicationFailure( + StartSessionLaunchDescriptorApplicationFailure.newBuilder() + .setCode("INVALID_TEMPLATE_CONFIGURATION") + .setMessage( + "INVALID_TEMPLATE_CONFIGURATION: captured source unavailable")) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), complete.toBuilder().setSchemaVersion(2).build())) + .isInstanceOf(IllegalArgumentException.class); + + var unknown = + complete.toBuilder() + .setAssociationRead( + complete.getAssociationRead().toBuilder() + .setAssociation( + complete.getAssociationRead().getAssociation().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 88, + UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> StartSessionLaunchDescriptorGrpcCodec.fromResponse(fixture.request(), unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var unknownDescriptorBinding = + complete.toBuilder() + .setLaunchDescriptor( + complete.getLaunchDescriptor().toBuilder() + .setAuthoredWorldBinding( + complete.getLaunchDescriptor().getAuthoredWorldBinding().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 89, + UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), unknownDescriptorBinding)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + @Test + void roundTripsAClosedCorrelatedApplicationFailureWireOutcome() throws Exception { + // Codec evidence only; constructing this value does not prove a producer persisted it. + Fixture fixture = fixture(); + String code = "INVALID_TEMPLATE_CONFIGURATION"; + String message = code + ": captured template has unsupported owner references"; + var response = + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + fixture.request(), fixture.associationRead(), code, message); + + var decoded = StartSessionLaunchDescriptorGrpcCodec.fromResponse(fixture.request(), response); + + assertThat(decoded.associationRead().request()).isEqualTo(fixture.request()); + assertThat(decoded.outcome()) + .isEqualTo(new StartSessionLaunchDescriptorGrpcCodec.ApplicationFailure(code, message)); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + fixture.request(), fixture.associationRead(), "UNAVAILABLE", "unavailable")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsDescriptorFieldsThatDoNotMatchTheOriginalAssociationAndRelease() throws Exception { + Fixture fixture = fixture(); + var original = fixture.descriptor(); + var alteredRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + original.targetNamespace(), + original.controlPlaneRequestId(), + original.canonicalTenantId(), + "substituted-world", + original.authoredWorldSourceOperationId(), + original.authoredWorldSourceEvidenceDigest(), + original.gameTemplateId(), + false, + null, + false, + null, + false, + null, + true, + "{}"); + var substituted = + AuthoredWorldLaunchDescriptorEvidence.create( + alteredRequest, + original.launchDescriptorId(), + original.versionId(), + false, + null, + "{}", + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + false, + null); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("original StartSession tuple and association"); + + var substitutedVersion = + AuthoredWorldLaunchDescriptorEvidence.create( + original.request(), + original.launchDescriptorId(), + original.versionId() + 1L, + false, + null, + "{}", + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + false, + null); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), substitutedVersion)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("version or release"); + + var changedRuntimeFlags = + AuthoredWorldLaunchDescriptorEvidence.create( + original.request(), + original.launchDescriptorId(), + original.versionId(), + false, + null, + "{\"runtime\":true}", + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + false, + null); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), changedRuntimeFlags)) + .isInstanceOf(IllegalArgumentException.class); + + var response = + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), original); + var changedFlatVersion = + response.toBuilder() + .setLaunchDescriptor( + response.getLaunchDescriptor().toBuilder() + .setVersionId(response.getLaunchDescriptor().getVersionId() + 1L) + .build()) + .build(); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), changedFlatVersion)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Fixture fixture() throws Exception { + var worldEvidence = AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); + UUID canonicalVersion = worldEvidence.request().canonicalVersionId(); + UUID selectedCommit = uuid(worldEvidence.request().appliedCommitId()); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_ID, TENANT, "tenant-key", WORLD_SLUG, "Synthetic World"); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + SOURCE_OPERATION_ID, + sourceRequestDigest, + TENANT, + "tenant-key", + WORLD_SLUG, + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + var source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_ID, + SOURCE_OPERATION_ID, + sourceRequestDigest, + TENANT, + "tenant-key", + WORLD_SLUG, + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW", + sourceEvidenceDigest); + var intake = + new IntakeRequest( + 1, NAMESPACE, INTAKE_ID, TENANT, WORLD_SLUG, SOURCE_OPERATION_ID, sourceEvidenceDigest); + var receipt = + new PublicReceipt( + 1, + NAMESPACE, + INTAKE_ID, + WORLD_OPERATION_ID, + TENANT, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidenceDigest, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intake), + digest('e'), + source); + var association = + new StartSessionTemplateAssociationReadEvidence.Association( + TENANT, + 91L, + canonicalVersion, + selectedCommit, + worldEvidence.request().publishWorkflowId(), + digest('c'), + digest('a'), + NAMESPACE, + INTAKE_ID, + WORLD_OPERATION_ID, + SOURCE_OPERATION_ID, + WORLD_SLUG, + sourceEvidenceDigest, + new ByIdReadRequest(1, NAMESPACE, WORLD_READ_ID, INTAKE_ID, TENANT), + receipt); + Request request = + new Request( + 1, + NAMESPACE, + READ_ID, + postTuple().canonicalBytes(), + ATTEMPT, + 8L, + new ExactReplay( + canonicalVersion, + selectedCommit, + worldEvidence.request().publishWorkflowId(), + association.associationDigest())); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + CONTROL_PLANE_REQUEST_ID, + TENANT, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidenceDigest, + 91L, + false, + null, + false, + null, + false, + null, + true, + "{}"); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "descriptor-1", + 42L, + false, + null, + "{}", + "generation", + 9L, + 7L, + "release-1", + false, + null); + var releaseEvidence = + AuthoredWorldReleaseAttestationSelectorTest.release(descriptor, worldEvidence); + PublishedReleaseBundle.Builder release = + PublishedReleaseBundle.newBuilder() + .setId(7L) + .setVersionId(42L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v2") + .setPublishWorkflowId(worldEvidence.request().publishWorkflowId()) + .setManifestHash(releaseEvidence.manifestHash()) + .setManifestSchemaVersion(releaseEvidence.manifestSchemaVersion()) + .addAllRequiredManifestAssetKeys(releaseEvidence.requiredManifestAssetKeys()) + .setGenerationConfigRevision(releaseEvidence.generationConfigRevision()) + .setPublishedReleaseBundleRef(releaseEvidence.publishedReleaseBundleRef()) + .setCanonicalTenantId(TENANT.toString()) + .setCanonicalVersionId(canonicalVersion.toString()) + .addAllCommandDefinitions(releaseEvidence.commandDefinitions()); + for (var participant : releaseEvidence.participantDigests()) { + ParticipantDigest.Builder participantMessage = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigestPresent()) { + participantMessage.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + } + release.addParticipantDigests(participantMessage); + } + Result associationRead = new Result(request, association, release.build(), worldEvidence, 23L); + return new Fixture(request, associationRead, descriptor); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple() { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + CONTROL_PLANE_REQUEST_ID, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact StartSession descriptor selection")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", TENANT.toString(), "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", TENANT.toString()), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(TENANT.toString(), 3L), + "membershipAuthorityGeneration", Map.of(TENANT.toString(), 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(TENANT.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + Request request, Result associationRead, AuthoredWorldLaunchDescriptorEvidence descriptor) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClientTest.java new file mode 100644 index 0000000000..6d374684a8 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorReadClientTest.java @@ -0,0 +1,294 @@ +package net.firedevops.firemud.common.gamedesign; + +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.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +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; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionLaunchDescriptorReadClientTest { + private static final String NAMESPACE = "runtime-a"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT_ID = uuid("02222222-2222-4222-8222-222222222222"); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionFlags() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void rejectsInvalidTlsBeforeChannelCreation(@TempDir Path dir) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = fileBackedMtls(dir); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedMtls(dir); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(dir.resolve("missing-client.crt").toString()); + missingFiles.setPrivateKey(dir.resolve("missing-client.key").toString()); + missingFiles.setCaCert(dir.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missingFiles, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void remainsUninitializedAndRejectsWrongNamespaceTransactionOrInitialSelection(@TempDir Path dir) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-design-service:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + StartSessionLaunchDescriptorReadClient client = newClient(fileBackedMtls(dir), channelFactory); + + assertThatThrownBy(() -> client.resolve(request(NAMESPACE, exactReplay()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.resolve(request("other-runtime", exactReplay()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + + client.init(); + assertThatThrownBy(() -> client.resolve(request(NAMESPACE, new InitialConfigured()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Exact Game Session-pinned association replay required"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.resolve(request(NAMESPACE, exactReplay()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + + TransactionSynchronizationManager.setActualTransactionActive(false); + client.close(); + assertThatThrownBy(() -> client.resolve(request(NAMESPACE, exactReplay()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + } + + @Test + void initializesOnlyTheConfiguredGameDesignTargetWithFileBackedTls(@TempDir Path dir) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + CommonGrpcClientProperties tls = fileBackedMtls(dir); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + StartSessionLaunchDescriptorReadClient client = + new StartSessionLaunchDescriptorReadClient(endpoints, tls, channelFactory, NAMESPACE); + + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static StartSessionLaunchDescriptorReadClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new StartSessionLaunchDescriptorReadClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws IOException { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + 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("server-ca.crt"), "CA certificate").toString()); + return tls; + } + + private static StartSessionTemplateAssociationReadEvidence.Request request( + String namespace, StartSessionTemplateAssociationReadEvidence.Selection selection) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "descriptor-read-client-request", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession descriptor read")); + StartSessionPostAuthorizationExecutionTuple post = + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre, namespace), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + return new StartSessionTemplateAssociationReadEvidence.Request( + 1, namespace, READ_ID, post.canonicalBytes(), ATTEMPT_ID, 8L, selection); + } + + private static ExactReplay exactReplay() { + return new ExactReplay( + uuid("03333333-3333-4333-8333-333333333333"), + uuid("04444444-4444-4444-8444-444444444444"), + "workflow-1", + digest('c')); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, String namespace) { + String tenant = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", namespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + digest('a'), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + "2026-10-09T00:00:00Z", + "expiresAt", + "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + ISSUANCE_ID.toString(), + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 2L, + "tenantAuthorityGeneration", + Map.of(tenant, 3L), + "membershipAuthorityGeneration", + Map.of(tenant, 4L), + "privateRealmGrantVersions", + List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClientTest.java new file mode 100644 index 0000000000..b897cfafaf --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadClientTest.java @@ -0,0 +1,267 @@ +package net.firedevops.firemud.common.gamedesign; + +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.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +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; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionTemplateAssociationReadClientTest { + private static final String NAMESPACE = "runtime-a"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT_ID = uuid("02222222-2222-4222-8222-222222222222"); + private static final String WORKLOAD = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionFlags() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void rejectsPlaintextMissingClasspathAndUnreadableTlsBeforeChannelCreation(@TempDir Path dir) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = fileBackedMtls(dir); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedMtls(dir); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(dir.resolve("missing-client.crt").toString()); + missingFiles.setPrivateKey(dir.resolve("missing-client.key").toString()); + missingFiles.setCaCert(dir.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missingFiles, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void keepsTheReadUninitializedAndRejectsWrongNamespaceOrAmbientOwnerTransaction(@TempDir Path dir) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + StartSessionTemplateAssociationReadClient client = + newClient(fileBackedMtls(dir), channelFactory); + var request = request(NAMESPACE); + + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.read(request("other-runtime"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + verifyNoInteractions(channelFactory); + } + + @Test + void initializesOnlyTheConfiguredGameDesignTargetWithFileBackedTls(@TempDir Path dir) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + CommonGrpcClientProperties tls = fileBackedMtls(dir); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + StartSessionTemplateAssociationReadClient client = + new StartSessionTemplateAssociationReadClient(endpoints, tls, channelFactory, NAMESPACE); + + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static StartSessionTemplateAssociationReadClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new StartSessionTemplateAssociationReadClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws IOException { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + 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("server-ca.crt"), "CA certificate").toString()); + return tls; + } + + private static StartSessionTemplateAssociationReadEvidence.Request request(String namespace) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "template-association-client-request", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession association read")); + StartSessionPostAuthorizationExecutionTuple post = + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre, namespace), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + return new StartSessionTemplateAssociationReadEvidence.Request( + 1, namespace, READ_ID, post.canonicalBytes(), ATTEMPT_ID, 8L, new InitialConfigured()); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, String namespace) { + String tenant = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", namespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + digest('a'), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + "2026-10-09T00:00:00Z", + "expiresAt", + "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + ISSUANCE_ID.toString(), + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java new file mode 100644 index 0000000000..acb7bce812 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java @@ -0,0 +1,295 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionTemplateAssociationReadGrpcCodecTest { + private static final int EXPECTED_TUPLE_BYTES = 4176; + private static final String EXPECTED_TUPLE_SHA256 = + "891de4fb1ae82664ffbe9837db71c19bbbe28e7db759836ddca0d4a2f7002807"; + private static final int EXPECTED_INITIAL_WIRE_BYTES = 4276; + private static final String EXPECTED_INITIAL_WIRE_SHA256 = + "593394efa9b972fce74beefbf23cd3ba3791f3b57fe4b86426f1dc3c2dcf71ab"; + private static final int EXPECTED_REPLAY_WIRE_BYTES = 4455; + private static final String EXPECTED_REPLAY_WIRE_SHA256 = + "38cfef3dc73b485e19618580e88ee545ac26f1857a91940cebd9cd5740d4add0"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID VERSION = uuid("03333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = uuid("04444444-4444-4444-8444-444444444444"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void initialAndExactReplayHaveClosedDeterministicRequestVectors() { + var initial = request(new InitialConfigured()); + var initialWire = StartSessionTemplateAssociationReadGrpcCodec.toRequest(initial); + assertThat(initial.canonicalPostAuthorizationTuple()).hasSize(EXPECTED_TUPLE_BYTES); + assertThat(sha256(initial.canonicalPostAuthorizationTuple())).isEqualTo(EXPECTED_TUPLE_SHA256); + assertThat(initialWire.toByteArray()).hasSize(EXPECTED_INITIAL_WIRE_BYTES); + assertThat(sha256(initialWire.toByteArray())).isEqualTo(EXPECTED_INITIAL_WIRE_SHA256); + assertThat(initialWire.getSelectionCase()) + .isEqualTo(ReadStartSessionTemplateAssociationRequest.SelectionCase.INITIAL_CONFIGURED); + assertThat(StartSessionTemplateAssociationReadGrpcCodec.fromRequest(initialWire)) + .isEqualTo(initial); + assertThat(StartSessionTemplateAssociationReadGrpcCodec.toRequest(initial).toByteArray()) + .containsExactly(initialWire.toByteArray()); + + var replay = + request(new ExactReplay(VERSION, COMMIT, "template-publish-workflow-1", digest('a'))); + var replayWire = StartSessionTemplateAssociationReadGrpcCodec.toRequest(replay); + assertThat(replayWire.toByteArray()).hasSize(EXPECTED_REPLAY_WIRE_BYTES); + assertThat(sha256(replayWire.toByteArray())).isEqualTo(EXPECTED_REPLAY_WIRE_SHA256); + assertThat(replayWire.getSelectionCase()) + .isEqualTo(ReadStartSessionTemplateAssociationRequest.SelectionCase.EXACT_REPLAY); + assertThat(StartSessionTemplateAssociationReadGrpcCodec.fromRequest(replayWire)) + .isEqualTo(replay); + assertThat(replayWire.getExactReplay().getCanonicalVersionId()).isEqualTo(VERSION.toString()); + assertThat(replayWire.getExactReplay().getSelectedCommitId()).isEqualTo(COMMIT.toString()); + assertThat(replayWire.getExactReplay().getAssociationDigest()).isEqualTo(digest('a')); + } + + @Test + void rejectsMissingSelectionUnknownFieldsNoncanonicalIdsAndChangedNamespace() { + var valid = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(request(new InitialConfigured())); + assertThatThrownBy( + () -> + StartSessionTemplateAssociationReadGrpcCodec.fromRequest( + valid.toBuilder().clearSelection().build())) + .isInstanceOf(IllegalArgumentException.class); + + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy(() -> StartSessionTemplateAssociationReadGrpcCodec.fromRequest(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var uppercaseId = + valid.toBuilder() + .setReadRequestId(TENANT.toString().toUpperCase(java.util.Locale.ROOT)) + .build(); + assertThatThrownBy(() -> StartSessionTemplateAssociationReadGrpcCodec.fromRequest(uppercaseId)) + .isInstanceOf(IllegalArgumentException.class); + + var tuple = postTuple("codec-namespace"); + assertThatThrownBy( + () -> + StartSessionTemplateAssociationReadGrpcCodec.toRequest( + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + "another-runtime", + READ_ID, + tuple.canonicalBytes(), + ATTEMPT, + 8L, + new InitialConfigured()))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsReplaySelectorsWithoutCanonicalPinnedDigestOrIds() { + assertThatThrownBy(() -> new ExactReplay(VERSION, COMMIT, "workflow", "A" + "a".repeat(70))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ExactReplay(new UUID(0L, 0L), COMMIT, "workflow", digest('b'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ExactReplay(VERSION, COMMIT, "", digest('b'))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void preservesChangedAttemptFieldsAndRejectsOversizedOrUnknownNestedFields() { + var valid = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(request(new InitialConfigured())); + var changedFence = valid.toBuilder().setOwnerFence(valid.getOwnerFence() + 1L).build(); + assertThat(StartSessionTemplateAssociationReadGrpcCodec.fromRequest(changedFence).ownerFence()) + .isEqualTo(valid.getOwnerFence() + 1L); + assertThat(StartSessionTemplateAssociationReadGrpcCodec.fromRequest(changedFence)) + .isNotEqualTo(request(new InitialConfigured())); + + byte[] oversized = + new byte + [net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple + .MAX_CANONICAL_TUPLE_BYTES + + 1]; + assertThatThrownBy( + () -> + new StartSessionTemplateAssociationReadEvidence.Request( + 1, "world-runtime", READ_ID, oversized, ATTEMPT, 8L, new InitialConfigured())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bounded"); + + var replay = + StartSessionTemplateAssociationReadGrpcCodec.toRequest( + request(new ExactReplay(VERSION, COMMIT, "template-publish-workflow-1", digest('a')))); + var nestedUnknown = + replay.toBuilder() + .setExactReplay( + replay.getExactReplay().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(77, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> StartSessionTemplateAssociationReadGrpcCodec.fromRequest(nestedUnknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + private static StartSessionTemplateAssociationReadEvidence.Request request( + StartSessionTemplateAssociationReadEvidence.Selection selection) { + return new StartSessionTemplateAssociationReadEvidence.Request( + 1, + "world-runtime", + READ_ID, + postTuple("codec-request").canonicalBytes(), + ATTEMPT, + 8L, + selection); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple(String requestId) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + WORKLOAD, + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static String sha256(byte[] bytes) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + StringBuilder result = new StringBuilder(digest.length * 2); + for (byte value : digest) result.append(String.format("%02x", value)); + return result.toString(); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is required by the Java runtime", impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java index 23a4df5eaf..91e1b4d921 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java @@ -615,7 +615,7 @@ static ReleaseContent release( request.appliedCommitId(), owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), owner.equals("GAME_LOGIC") ? DIGEST : null, null, null)) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java index e62f3dd8c2..3d9ce13d9e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java @@ -117,7 +117,7 @@ void rejectsChangedSelectionAndSubstitutedReceiptAccountOrAppliedBytes() throws } @Test - void requestCarrierAcceptsUnboundedDraftEpochAndRejectsMalformedCounters() throws Exception { + void requestCarrierSupportsSchemaFourAndUnboundedCanonicalDraftEpoch() throws Exception { WorldPublishedStartLocationEvidence.Request base = evidence().request(); var tuple = base.worldAffectedTuples().getFirst(); var largeEpochTuple = @@ -141,13 +141,14 @@ void requestCarrierAcceptsUnboundedDraftEpochAndRejectsMalformedCounters() throw base.publishWorkflowId(), base.appliedCommitId(), base.contentDigest(), - base.digestSchemaVersion(), + 4, List.of(largeEpochTuple)); var roundTrip = WorldPublishedStartLocationGrpcCodec.fromRequest( WorldPublishedStartLocationGrpcCodec.toRequest(carrierRequest)); assertThat(roundTrip).isEqualTo(carrierRequest); + assertThat(roundTrip.digestSchemaVersion()).isEqualTo(4); assertThat(roundTrip.worldAffectedTuples().getFirst().expectedEpoch()).isEqualTo(LARGE_EPOCH); assertInvalidExpectedEpoch(tuple, null); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java new file mode 100644 index 0000000000..d58cdedeba --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Durable fresh-tenant launch association plus a separate current Game Session row projection. */ +public record CanonicalGameInstanceLaunchAssociation( + String targetNamespace, + long gameSessionTenantId, + UUID tenantAssociationOperationId, + UUID canonicalTenantId, + UUID gameInstanceUuid, + String worldSlug, + UUID playableStateNamespaceId, + RealmEntryPolicy.StateScope playableStateScope, + boolean publicProduction, + String controlPlaneRequestId, + String launchDescriptorId, + long capturedStartingRowVersion, + CompleteLaunchBindingEvidence launchBindingEvidence, + CurrentGameInstanceStatus currentGameInstanceStatus, + long currentRowVersion) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public enum CurrentGameInstanceStatus { + STARTING, + RUNNING, + STOPPING, + STOPPED + } + + public CanonicalGameInstanceLaunchAssociation { + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requirePositive(gameSessionTenantId, "gameSessionTenantId"); + requireNonNil(tenantAssociationOperationId, "tenantAssociationOperationId"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + if (playableStateScope != RealmEntryPolicy.StateScope.SHARED) { + throw new IllegalArgumentException("Canonical launch association requires SHARED scope"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "Canonical launch association requires owner-confirmed public production"); + } + requireText(controlPlaneRequestId, "controlPlaneRequestId"); + requireText(launchDescriptorId, "launchDescriptorId"); + if (capturedStartingRowVersion < 0) { + throw new IllegalArgumentException("capturedStartingRowVersion must not be negative"); + } + Objects.requireNonNull(launchBindingEvidence, "launchBindingEvidence"); + Objects.requireNonNull(currentGameInstanceStatus, "currentGameInstanceStatus"); + if (currentRowVersion < capturedStartingRowVersion) { + throw new IllegalArgumentException( + "currentRowVersion must not precede the captured STARTING row version"); + } + + var descriptor = launchBindingEvidence.descriptor(); + descriptor.requireValid(); + launchBindingEvidence.releaseAttestation().requireValid(descriptor); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId())) { + throw new IllegalArgumentException( + "Launch association does not match its complete authored launch binding"); + } + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java new file mode 100644 index 0000000000..4a6a5502dc --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; + +/** The exact canonical launch association and its owner-local runtime row locked together. */ +public record CanonicalInitialAdmissionLaunchTarget( + CanonicalGameInstanceLaunchAssociation association, + UUID realmId, + long gameInstanceId, + long runtimeVersionId) { + public CanonicalInitialAdmissionLaunchTarget { + Objects.requireNonNull(association, "association"); + Objects.requireNonNull(realmId, "realmId"); + if (gameInstanceId <= 0L || runtimeVersionId <= 0L) { + throw new IllegalArgumentException("Canonical launch target identifiers must be positive"); + } + if (association.launchBindingEvidence().descriptor().versionId() != runtimeVersionId) { + throw new IllegalArgumentException( + "Current runtime version does not match the canonical launch descriptor"); + } + } + + /** Canonical content version from retained publication evidence, never from the numeric row. */ + public UUID canonicalVersionId() { + return association.launchBindingEvidence().releaseAttestation().canonicalVersionId(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java new file mode 100644 index 0000000000..c6ddb1c37e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; + +/** Immutable catalog evidence for one public-production realm; it is not admission authority. */ +public record CanonicalRealmCatalogSnapshot( + String targetNamespace, + UUID tenantId, + String tenantSlug, + String worldSlug, + UUID realmId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + UUID playableStateNamespaceId, + String characterCreationPolicy, + long catalogRevision, + UUID creationRequestId, + String requestDigest, + String receiptDigest, + IntakeReceipt sourceIntakeReceipt) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalRealmCatalogSnapshot { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(tenantId, "tenantId"); + Objects.requireNonNull(tenantSlug, "tenantSlug"); + Objects.requireNonNull(worldSlug, "worldSlug"); + requireNonNil(realmId, "realmId"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(realmDisplayName, "realmDisplayName"); + Objects.requireNonNull(stateScope, "stateScope"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(characterCreationPolicy, "characterCreationPolicy"); + requireNonNil(creationRequestId, "creationRequestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + if (!visible || !publicProduction || catalogRevision != 1L) { + throw new IllegalArgumentException("Unsupported canonical initial realm catalog state"); + } + var source = sourceIntakeReceipt.source(); + if (!targetNamespace.equals(source.targetNamespace()) + || !tenantId.equals(source.canonicalTenantId()) + || !tenantSlug.equals(source.tenantSlug()) + || !worldSlug.equals(source.worldSlug())) { + throw new IllegalArgumentException( + "Catalog selectors do not match the persisted authored-world source receipt"); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java new file mode 100644 index 0000000000..8bee96d53e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.gamesession.dto; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.lang.Nullable; + +/** Explicit input for one immutable public-production realm catalog creation. */ +public record CreateCanonicalRealmCatalogRequest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String characterCreationPolicy, + @Nullable UUID playtestLifecycleId, + @Nullable Long playtestStateGeneration) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "The two nullable lifecycle fields are rejected when supplied; null is their required ABSENT state for initial public production.") + public CreateCanonicalRealmCatalogRequest { + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceIntakeOperationId, "sourceIntakeOperationId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + Objects.requireNonNull(realmSlug, "realmSlug"); + if (realmSlug.isBlank() || strictUtf8(realmSlug, "realmSlug").length > 120) { + throw new IllegalArgumentException( + "realmSlug must be a nonblank selector of at most 120 UTF-8 bytes"); + } + Objects.requireNonNull(realmDisplayName, "realmDisplayName"); + if (realmDisplayName.isBlank() + || realmDisplayName.codePointCount(0, realmDisplayName.length()) > 100 + || strictUtf8(realmDisplayName, "realmDisplayName").length > 400) { + throw new IllegalArgumentException("realmDisplayName must be bounded and nonblank"); + } + if (!visible || !publicProduction) { + throw new IllegalArgumentException( + "Initial canonical realm creation requires visible public production"); + } + if (!"SHARED".equals(stateScope) && !"ISOLATED".equals(stateScope)) { + throw new IllegalArgumentException("stateScope must be exactly SHARED or ISOLATED"); + } + Objects.requireNonNull(characterCreationPolicy, "characterCreationPolicy"); + if (characterCreationPolicy.isBlank() + || characterCreationPolicy.codePointCount(0, characterCreationPolicy.length()) > 64 + || strictUtf8(characterCreationPolicy, "characterCreationPolicy").length > 256) { + throw new IllegalArgumentException( + "characterCreationPolicy must be an explicit bounded nonblank owner value"); + } + if (playtestLifecycleId != null || playtestStateGeneration != null) { + throw new IllegalArgumentException( + "Initial public-production creation cannot carry private/playtest lifecycle evidence"); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static byte[] strictUtf8(String value, String name) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(name + " must be well-formed UTF-8 text", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java new file mode 100644 index 0000000000..4b29e3106d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java @@ -0,0 +1,1265 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec.Resolved; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.jooq.JSONB; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; + +/** Explicit Game Session owner persistence for the exact launch-to-instance binding. */ +public final class CanonicalGameInstanceLaunchAssociationRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ASSOCIATION_TABLE = "game_session_canonical_instance_launch"; + + private final DSLContext dsl; + private final String workloadNamespace; + + public CanonicalGameInstanceLaunchAssociationRepository( + DSLContext dsl, String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * Captures an existing STARTING owner row and its exact launch binding in the same writable READ + * COMMITTED transaction. This method does not allocate or create a runtime row. + */ + public CanonicalGameInstanceLaunchAssociation capture( + FreshGameSessionTenantAssociation tenantAssociation, + long gameInstanceId, + CompleteLaunchBindingEvidence launchBindingEvidence) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(tenantAssociation, "tenantAssociation"); + requirePositive(gameInstanceId, "gameInstanceId"); + ValidatedBinding binding = validateBinding(launchBindingEvidence); + if (!workloadNamespace.equals(binding.descriptor().targetNamespace())) { + throw new IllegalArgumentException("Launch binding targets another Game Session namespace"); + } + + RuntimeTenantIdentityEvidence source = tenantAssociation.sourceEvidence(); + requireFreshSourceIdentity(tenantAssociation, source); + if (!binding.descriptor().canonicalTenantId().equals(source.canonicalTenantId())) { + throw new IllegalArgumentException("Launch binding does not match its fresh tenant owner"); + } + + lockRequest(binding.descriptor().controlPlaneRequestId()); + FreshTenantOwnerMapping mapping = requireFreshTenantMapping(tenantAssociation); + GameInstanceRow runtime = + requireLockedRuntime(tenantAssociation.legacyGameSessionTenantId(), gameInstanceId); + RealmOwnerProjection realm = requirePublicSharedRealm(binding.descriptor()); + CanonicalGameInstanceLaunchAssociation existing = + findByRequest(binding.descriptor().controlPlaneRequestId(), true) + .map(this::toAssociation) + .orElse(null); + if (existing != null) { + requireExactRetry( + existing, tenantAssociation, gameInstanceId, runtime, binding.evidence(), mapping, realm); + return existing; + } + + requireStartingRuntime(runtime, binding.evidence()); + String evidenceJson = serializeEvidence(binding.evidence()); + RuntimeTenantIdentityEvidence sourceEvidence = tenantAssociation.sourceEvidence(); + dsl.execute( + "INSERT INTO " + + ASSOCIATION_TABLE + + " (target_namespace, control_plane_request_id, game_session_tenant_id, " + + "canonical_tenant_id, tenant_association_operation_id, tenant_association_request_id, " + + "tenant_source_schema_version, tenant_source_target_namespace, " + + "tenant_source_request_id, tenant_source_canonical_tenant_id, " + + "tenant_source_game_row_id, tenant_source_game_tenant_key, " + + "tenant_source_provenance_kind, tenant_association_kind, game_instance_id, " + + "game_instance_uuid, canonical_realm_id, world_slug, playable_state_namespace_id, playable_state_scope, " + + "public_production, captured_starting_row_version, game_template_id, " + + "launch_descriptor_id, version_id, release_bundle_id, generation_config_revision, " + + "version_state_epoch, complete_launch_binding_evidence) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND', ?, ?, ?, ?, ?, " + + "'SHARED', TRUE, ?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb))", + workloadNamespace, + binding.descriptor().controlPlaneRequestId(), + tenantAssociation.legacyGameSessionTenantId(), + sourceEvidence.canonicalTenantId(), + mapping.operationId(), + sourceEvidence.requestId(), + sourceEvidence.schemaVersion(), + sourceEvidence.targetNamespace(), + sourceEvidence.requestId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.sourceGameRowId(), + sourceEvidence.sourceGameTenantKey(), + sourceEvidence.provenanceKind(), + gameInstanceId, + runtime.gameInstanceUuid(), + realm.realmId(), + binding.descriptor().worldSlug(), + realm.playableStateNamespaceId(), + runtime.rowVersion(), + binding.descriptor().gameTemplateId(), + binding.descriptor().launchDescriptorId(), + binding.descriptor().versionId(), + binding.descriptor().releaseBundleId(), + binding.descriptor().generationConfigRevision(), + binding.descriptor().versionStateEpoch(), + evidenceJson); + + CanonicalGameInstanceLaunchAssociation inserted = + findByRequest(binding.descriptor().controlPlaneRequestId(), true) + .map(this::toAssociation) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical launch association insert readback is missing")); + requireExactRetry( + inserted, tenantAssociation, gameInstanceId, runtime, binding.evidence(), mapping, realm); + return inserted; + } + + /** Serializes a STARTING-row producer on the exact namespace/request key used by capture. */ + public void lockRequestForStartingGameInstance(String controlPlaneRequestId) { + requireWritableReadCommittedOwnerTransaction(); + requireRequestId(controlPlaneRequestId); + lockRequest(controlPlaneRequestId); + } + + /** + * Reads one committed immutable owner association plus the transient current GameInstance row. + */ + public Optional read(String controlPlaneRequestId) { + requireOutsideTransaction(); + requireRequestId(controlPlaneRequestId); + return findByRequest(controlPlaneRequestId, false).map(this::toAssociation); + } + + /** + * Reads a STARTING association only when its original pending StartSession owner attempt and both + * immutable evidence pins are still present and exact. This returns read evidence, never a claim + * or continuation capability. + */ + public Optional readOriginalStartSessionAssociation( + net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence + .Request + selector) { + requireOutsideTransaction(); + Objects.requireNonNull(selector, "selector"); + if (!workloadNamespace.equals(selector.targetNamespace())) { + throw new IllegalArgumentException( + "Canonical launch association selector targets another Game Session namespace"); + } + requireRequestId(selector.controlPlaneRequestId()); + Record row = findOriginalStartSessionAssociation(selector); + if (row == null) { + return Optional.empty(); + } + try { + OriginalStartSessionAssociation result = decodeOriginalStartSessionAssociation(row); + requireExactOriginalStartSessionSelector(selector, result.association()); + return Optional.of(result); + } catch (LaunchAssociationOwnerReadMismatchException mismatch) { + throw mismatch; + } catch (RuntimeException malformed) { + throw new IllegalStateException( + "Persisted original StartSession association evidence is malformed", malformed); + } + } + + private Record findOriginalStartSessionAssociation( + net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence + .Request + selector) { + return dsl.fetchOne( + "SELECT association.*, current.status AS current_status, " + + "current.row_version AS current_row_version, " + + "current.game_instance_uuid AS current_game_instance_uuid, " + + "current.owner_account_uuid AS current_owner_account_uuid, " + + "current.game_template_id AS current_game_template_id, " + + "current.launch_descriptor_id AS current_launch_descriptor_id, " + + "current.version_id AS current_version_id, " + + "current.release_bundle_id AS current_release_bundle_id, " + + "current.generation_config_revision AS current_generation_config_revision, " + + "current.version_state_epoch AS current_version_state_epoch, " + + "current.run_owned_start_request_id AS current_run_owned_start_request_id, " + + "current.run_owned_start_published_release_bundle_ref " + + "AS current_run_owned_start_published_release_bundle_ref, " + + "attempt.canonical_tenant_id AS owner_canonical_tenant_id, " + + "attempt.owner_attempt_id AS owner_attempt_id, " + + "attempt.owner_fence AS owner_fence, " + + "attempt.post_authorization_execution_tuple AS owner_tuple, " + + "attempt.mutation_digest AS owner_mutation_digest, " + + "attempt.authorization_reference_fingerprint AS owner_authorization_fingerprint, " + + "attempt.account_redemption_projection AS owner_projection, " + + "association_pin.canonical_tenant_id AS pin_canonical_tenant_id, " + + "association_pin.owner_attempt_id AS pin_owner_attempt_id, " + + "association_pin.owner_fence AS pin_owner_fence, " + + "association_pin.post_authorization_execution_tuple AS pin_owner_tuple, " + + "association_pin.post_authorization_tuple_digest AS pin_tuple_digest, " + + "association_pin.account_redemption_projection_digest AS pin_projection_digest, " + + "association_pin.association_request_wire AS pin_association_request_wire, " + + "association_pin.association_response_wire AS pin_association_response_wire, " + + "association_pin.association_request_digest AS pin_association_request_digest, " + + "association_pin.association_response_digest AS pin_association_response_digest, " + + "association_pin.template_id AS pin_template_id, " + + "association_pin.canonical_version_id AS pin_canonical_version_id, " + + "association_pin.selected_commit_id AS pin_selected_commit_id, " + + "association_pin.publish_workflow_id AS pin_publish_workflow_id, " + + "association_pin.publication_selection_digest AS pin_publication_selection_digest, " + + "association_pin.association_digest AS pin_association_digest, " + + "association_pin.world_intake_request_id AS pin_world_intake_request_id, " + + "association_pin.world_operation_id AS pin_world_operation_id, " + + "association_pin.source_operation_id AS pin_source_operation_id, " + + "association_pin.source_evidence_digest AS pin_source_evidence_digest, " + + "descriptor_pin.canonical_tenant_id AS descriptor_canonical_tenant_id, " + + "descriptor_pin.owner_attempt_id AS descriptor_owner_attempt_id, " + + "descriptor_pin.owner_fence AS descriptor_owner_fence, " + + "descriptor_pin.association_request_digest AS descriptor_association_request_digest, " + + "descriptor_pin.association_response_digest AS descriptor_association_response_digest, " + + "descriptor_pin.descriptor_request_wire AS descriptor_request_wire, " + + "descriptor_pin.descriptor_response_wire AS descriptor_response_wire, " + + "descriptor_pin.descriptor_request_digest AS descriptor_request_digest, " + + "descriptor_pin.descriptor_response_digest AS descriptor_response_digest " + + "FROM " + + ASSOCIATION_TABLE + + " association JOIN game_instances current " + + "ON current.id = association.game_instance_id " + + "AND current.tenant_id = association.game_session_tenant_id " + + "JOIN game_session_canonical_realm_catalog realm " + + "ON realm.target_namespace = association.target_namespace " + + "AND realm.realm_id = association.canonical_realm_id " + + "AND realm.canonical_tenant_id = association.canonical_tenant_id " + + "AND realm.world_slug = association.world_slug " + + "AND realm.playable_state_namespace_id = association.playable_state_namespace_id " + + "AND realm.visible = TRUE AND realm.public_production = TRUE " + + "AND realm.state_scope = 'SHARED' " + + "JOIN game_session_start_session_operator_attempt attempt " + + "ON attempt.target_namespace = association.target_namespace " + + "AND attempt.control_plane_request_id = association.control_plane_request_id " + + "AND attempt.canonical_tenant_id = association.canonical_tenant_id " + + "AND attempt.phase_state = 'OWNER_EXECUTION_PENDING' " + + "AND attempt.account_redemption_projection IS NOT NULL " + + "AND attempt.lease_expires_at > clock_timestamp() " + + "JOIN game_session_start_session_template_association_pin association_pin " + + "ON association_pin.target_namespace = attempt.target_namespace " + + "AND association_pin.control_plane_request_id = attempt.control_plane_request_id " + + "AND association_pin.canonical_tenant_id = attempt.canonical_tenant_id " + + "AND association_pin.owner_attempt_id = attempt.owner_attempt_id " + + "AND association_pin.owner_fence = attempt.owner_fence " + + "AND association_pin.post_authorization_execution_tuple " + + "= attempt.post_authorization_execution_tuple " + + "JOIN game_session_start_session_launch_descriptor_pin descriptor_pin " + + "ON descriptor_pin.target_namespace = attempt.target_namespace " + + "AND descriptor_pin.control_plane_request_id = attempt.control_plane_request_id " + + "AND descriptor_pin.canonical_tenant_id = attempt.canonical_tenant_id " + + "AND descriptor_pin.owner_attempt_id = attempt.owner_attempt_id " + + "AND descriptor_pin.owner_fence = attempt.owner_fence " + + "AND descriptor_pin.association_request_digest " + + "= association_pin.association_request_digest " + + "AND descriptor_pin.association_response_digest " + + "= association_pin.association_response_digest " + + "WHERE association.target_namespace = ? " + + "AND association.control_plane_request_id = ? " + + "AND association.canonical_tenant_id = ? " + + "AND association.game_instance_uuid = ? " + + "AND current.status = 'STARTING'", + workloadNamespace, + selector.controlPlaneRequestId(), + selector.canonicalTenantId(), + selector.gameInstanceUuid()); + } + + private OriginalStartSessionAssociation decodeOriginalStartSessionAssociation(Record row) { + UUID ownerAttemptId = row.get("owner_attempt_id", UUID.class); + Long ownerFenceValue = row.get("owner_fence", Long.class); + if (ownerAttemptId == null + || NIL_UUID.equals(ownerAttemptId) + || ownerFenceValue == null + || ownerFenceValue <= 0) { + throw new IllegalStateException("Original StartSession owner identity is malformed"); + } + long ownerFence = ownerFenceValue; + UUID canonicalTenantId = row.get("owner_canonical_tenant_id", UUID.class); + byte[] ownerTupleBytes = requiredBytes(row, "owner_tuple"); + byte[] ownerProjectionBytes = requiredBytes(row, "owner_projection"); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(ownerTupleBytes); + if (!Arrays.equals(tuple.canonicalBytes(), ownerTupleBytes) + || !tuple.controlPlaneRequestId().equals(row.get("control_plane_request_id", String.class)) + || !workloadNamespace.equals( + tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !canonicalTenantId.equals(tuple.preAuthorizationTuple().action().scope().tenantId()) + || !tuple + .preAuthorizationTuple() + .action() + .target() + .ownerAccountId() + .equals(row.get("current_owner_account_uuid", UUID.class)) + || !canonicalTenantId.equals(row.get("canonical_tenant_id", UUID.class)) + || !tuple.mutationDigest().equals(row.get("owner_mutation_digest", String.class)) + || !tuple + .authorizationReferenceFingerprint() + .equals(row.get("owner_authorization_fingerprint", String.class))) { + throw new IllegalStateException( + "Original StartSession owner tuple differs from its retained association"); + } + StartSessionAuthorityEvidenceBundle authority = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + long issuanceFence; + try { + issuanceFence = Long.parseLong(tuple.issuanceFence()); + } catch (NumberFormatException invalid) { + throw new IllegalStateException("Original StartSession issuance fence is malformed", invalid); + } + GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection + expectedProjection = + new GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + issuanceFence); + if (!Arrays.equals(expectedProjection.canonicalBytes(), ownerProjectionBytes)) { + throw new IllegalStateException( + "Original StartSession Account projection differs from its canonical tuple"); + } + + byte[] associationTupleBytes = requiredBytes(row, "pin_owner_tuple"); + byte[] associationRequestWire = requiredBytes(row, "pin_association_request_wire"); + byte[] associationResponseWire = requiredBytes(row, "pin_association_response_wire"); + if (!Arrays.equals(ownerTupleBytes, associationTupleBytes) + || !ownerAttemptId.equals(row.get("pin_owner_attempt_id", UUID.class)) + || ownerFence != row.get("pin_owner_fence", Long.class) + || !canonicalTenantId.equals(row.get("pin_canonical_tenant_id", UUID.class)) + || !sha256(associationTupleBytes).equals(row.get("pin_tuple_digest", String.class)) + || !sha256(ownerProjectionBytes).equals(row.get("pin_projection_digest", String.class)) + || !sha256(associationRequestWire) + .equals(row.get("pin_association_request_digest", String.class)) + || !sha256(associationResponseWire) + .equals(row.get("pin_association_response_digest", String.class))) { + throw new IllegalStateException( + "Original StartSession association pin differs from its owner attempt"); + } + + Result associationPin = + decodeAssociationPin( + row, + tuple, + ownerAttemptId, + ownerFence, + associationRequestWire, + associationResponseWire); + byte[] descriptorRequestWire = requiredBytes(row, "descriptor_request_wire"); + byte[] descriptorResponseWire = requiredBytes(row, "descriptor_response_wire"); + if (!canonicalTenantId.equals(row.get("descriptor_canonical_tenant_id", UUID.class)) + || !ownerAttemptId.equals(row.get("descriptor_owner_attempt_id", UUID.class)) + || ownerFence != row.get("descriptor_owner_fence", Long.class) + || !row.get("pin_association_request_digest", String.class) + .equals(row.get("descriptor_association_request_digest", String.class)) + || !row.get("pin_association_response_digest", String.class) + .equals(row.get("descriptor_association_response_digest", String.class)) + || !sha256(descriptorRequestWire).equals(row.get("descriptor_request_digest", String.class)) + || !sha256(descriptorResponseWire) + .equals(row.get("descriptor_response_digest", String.class))) { + throw new IllegalStateException( + "Original StartSession descriptor pin differs from its association pin"); + } + + Resolved descriptorPin = + decodeDescriptorPin(associationPin, descriptorRequestWire, descriptorResponseWire); + CanonicalGameInstanceLaunchAssociation association = toOriginalAssociation(row); + if (!(descriptorPin.outcome() instanceof DescriptorOutcome descriptorOutcome) + || !descriptorOutcome.descriptor().equals(association.launchBindingEvidence().descriptor()) + || !associationPin.association().canonicalTenantId().equals(canonicalTenantId) + || associationPin.association().templateId() + != tuple.preAuthorizationTuple().action().target().gameTemplateId() + || !associationPin.association().worldSlug().equals(association.worldSlug()) + || !associationPin + .association() + .sourceOperationId() + .equals( + association.launchBindingEvidence().descriptor().authoredWorldSourceOperationId()) + || !associationPin + .association() + .sourceEvidenceDigest() + .equals( + association + .launchBindingEvidence() + .descriptor() + .authoredWorldSourceEvidenceDigest())) { + throw new IllegalStateException( + "Original StartSession descriptor or association pin differs from the STARTING binding"); + } + return new OriginalStartSessionAssociation(association, ownerAttemptId, ownerFence); + } + + private static Result decodeAssociationPin( + Record row, + StartSessionPostAuthorizationExecutionTuple tuple, + UUID ownerAttemptId, + long ownerFence, + byte[] requestWire, + byte[] responseWire) { + try { + ReadStartSessionTemplateAssociationRequest requestMessage = + ReadStartSessionTemplateAssociationRequest.parseFrom(requestWire); + Request request = StartSessionTemplateAssociationReadGrpcCodec.fromRequest(requestMessage); + if (!(request.selection() instanceof InitialConfigured) + || !request + .targetNamespace() + .equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !request.ownerAttemptId().equals(ownerAttemptId) + || request.ownerFence() != ownerFence + || !Arrays.equals(request.canonicalPostAuthorizationTuple(), tuple.canonicalBytes()) + || !Arrays.equals( + StartSessionTemplateAssociationReadGrpcCodec.toRequest(request).toByteArray(), + requestWire)) { + throw new IllegalStateException("Original association request pin is not canonical"); + } + ReadStartSessionTemplateAssociationResponse responseMessage = + ReadStartSessionTemplateAssociationResponse.parseFrom(responseWire); + Result result = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse(request, responseMessage); + if (!Arrays.equals( + StartSessionTemplateAssociationReadGrpcCodec.toResponse(result).toByteArray(), + responseWire) + || !row.get("pin_canonical_tenant_id", UUID.class) + .equals(result.association().canonicalTenantId()) + || row.get("pin_template_id", Long.class) != result.association().templateId() + || !row.get("pin_canonical_version_id", UUID.class) + .equals(result.association().canonicalVersionId()) + || !row.get("pin_selected_commit_id", UUID.class) + .equals(result.association().selectedCommitId()) + || !row.get("pin_publish_workflow_id", String.class) + .equals(result.association().publishWorkflowId()) + || !row.get("pin_publication_selection_digest", String.class) + .equals(result.association().publicationSelectionDigest()) + || !row.get("pin_association_digest", String.class) + .equals(result.association().associationDigest()) + || !row.get("pin_world_intake_request_id", UUID.class) + .equals(result.association().intakeRequestId()) + || !row.get("pin_world_operation_id", UUID.class) + .equals(result.association().worldOperationId()) + || !row.get("pin_source_operation_id", UUID.class) + .equals(result.association().sourceOperationId()) + || !row.get("pin_source_evidence_digest", String.class) + .equals(result.association().sourceEvidenceDigest())) { + throw new IllegalStateException("Retained association pin columns or wire changed"); + } + return result; + } catch (InvalidProtocolBufferException | IllegalArgumentException malformed) { + throw new IllegalStateException("Retained association pin wire is malformed", malformed); + } + } + + private static Resolved decodeDescriptorPin( + Result associationPin, byte[] requestWire, byte[] responseWire) { + try { + Request first = associationPin.request(); + var pinned = associationPin.association(); + Request expected = + new Request( + first.schemaVersion(), + first.targetNamespace(), + first.readRequestId(), + first.canonicalPostAuthorizationTuple(), + first.ownerAttemptId(), + first.ownerFence(), + new ExactReplay( + pinned.canonicalVersionId(), + pinned.selectedCommitId(), + pinned.publishWorkflowId(), + pinned.associationDigest())); + ReadStartSessionTemplateAssociationRequest requestMessage = + ReadStartSessionTemplateAssociationRequest.parseFrom(requestWire); + Request request = StartSessionLaunchDescriptorGrpcCodec.fromRequest(requestMessage); + if (!expected.equals(request) + || !Arrays.equals( + StartSessionLaunchDescriptorGrpcCodec.toRequest(request).toByteArray(), + requestWire)) { + throw new IllegalStateException( + "Retained descriptor request is not the exact association replay"); + } + ResolveStartSessionLaunchDescriptorResponse responseMessage = + ResolveStartSessionLaunchDescriptorResponse.parseFrom(responseWire); + Resolved result = + StartSessionLaunchDescriptorGrpcCodec.fromResponse(expected, responseMessage); + if (!(result.outcome() instanceof DescriptorOutcome) + || !Arrays.equals( + StartSessionLaunchDescriptorGrpcCodec.toResponse( + expected, result.associationRead(), result.outcome()) + .toByteArray(), + responseWire)) { + throw new IllegalStateException( + "Retained descriptor response is not canonical exact evidence"); + } + return result; + } catch (InvalidProtocolBufferException | IllegalArgumentException malformed) { + throw new IllegalStateException("Retained descriptor pin wire is malformed", malformed); + } + } + + private CanonicalGameInstanceLaunchAssociation toOriginalAssociation(Record row) { + try { + CompleteLaunchBindingEvidence evidence = + JSON.readValue( + row.get("complete_launch_binding_evidence", JSONB.class).data(), + CompleteLaunchBindingEvidence.class); + ValidatedBinding binding = validateBinding(evidence); + UUID canonicalTenantId = row.get("canonical_tenant_id", UUID.class); + UUID associationOperationId = row.get("tenant_association_operation_id", UUID.class); + UUID gameInstanceUuid = row.get("game_instance_uuid", UUID.class); + UUID namespaceId = row.get("playable_state_namespace_id", UUID.class); + RuntimeTenantIdentityEvidence source = sourceFromRow(row); + requireFreshSourceIdentity( + new FreshGameSessionTenantAssociation( + associationOperationId, row.get("game_session_tenant_id", Long.class), source), + source); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (!workloadNamespace.equals(row.get("tenant_source_target_namespace", String.class)) + || source.schemaVersion() != row.get("tenant_source_schema_version", Integer.class) + || !source.requestId().equals(row.get("tenant_association_request_id", UUID.class)) + || !source.requestId().equals(row.get("tenant_source_request_id", UUID.class)) + || !canonicalTenantId.equals(row.get("tenant_source_canonical_tenant_id", UUID.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("tenant_association_kind", String.class))) { + throw new IllegalStateException( + "Persisted fresh tenant source fields differ from their retained owner identity"); + } + GameInstanceRow current = + new GameInstanceRow( + row.get("game_instance_id", Long.class), + row.get("game_session_tenant_id", Long.class), + row.get("current_game_instance_uuid", UUID.class), + row.get("current_status", String.class), + row.get("current_row_version", Long.class), + row.get("current_game_template_id", Long.class), + row.get("current_launch_descriptor_id", String.class), + row.get("current_version_id", Long.class), + row.get("current_release_bundle_id", Long.class), + row.get("current_generation_config_revision", String.class), + row.get("current_version_state_epoch", Long.class), + row.get("current_run_owned_start_request_id", String.class), + row.get("current_run_owned_start_published_release_bundle_ref", String.class)); + requireRuntimeBinding(current, evidence); + if (!workloadNamespace.equals(row.get("target_namespace", String.class)) + || !canonicalTenantId.equals(source.canonicalTenantId()) + || !"FRESH_SOURCE_BOUND".equals(row.get("tenant_association_kind", String.class)) + || !binding.descriptor().targetNamespace().equals(workloadNamespace) + || !binding + .descriptor() + .controlPlaneRequestId() + .equals(row.get("control_plane_request_id", String.class)) + || !canonicalTenantId.equals(binding.descriptor().canonicalTenantId()) + || !row.get("world_slug", String.class).equals(binding.descriptor().worldSlug()) + || !Boolean.TRUE.equals(row.get("public_production", Boolean.class)) + || !row.get("launch_descriptor_id", String.class) + .equals(binding.descriptor().launchDescriptorId()) + || row.get("game_template_id", Long.class) != binding.descriptor().gameTemplateId() + || row.get("version_id", Long.class) != binding.descriptor().versionId() + || row.get("release_bundle_id", Long.class) != binding.descriptor().releaseBundleId() + || !row.get("generation_config_revision", String.class) + .equals(binding.descriptor().generationConfigRevision()) + || row.get("version_state_epoch", Long.class) != binding.descriptor().versionStateEpoch() + || !gameInstanceUuid.equals(current.gameInstanceUuid()) + || !"STARTING".equals(current.status()) + || current.rowVersion() < row.get("captured_starting_row_version", Long.class) + || !RealmEntryPolicy.StateScope.SHARED + .name() + .equals(row.get("playable_state_scope", String.class)) + || !Boolean.TRUE.equals(row.get("public_production", Boolean.class))) { + throw new IllegalStateException( + "Persisted STARTING association contradicts its exact runtime binding"); + } + return new CanonicalGameInstanceLaunchAssociation( + workloadNamespace, + row.get("game_session_tenant_id", Long.class), + associationOperationId, + canonicalTenantId, + gameInstanceUuid, + row.get("world_slug", String.class), + namespaceId, + RealmEntryPolicy.StateScope.SHARED, + true, + binding.descriptor().controlPlaneRequestId(), + binding.descriptor().launchDescriptorId(), + row.get("captured_starting_row_version", Long.class), + evidence, + CurrentGameInstanceStatus.STARTING, + current.rowVersion()); + } catch (RuntimeException exception) { + if (exception instanceof IllegalStateException illegalState) { + throw illegalState; + } + throw new IllegalStateException( + "Persisted original STARTING association is malformed", exception); + } + } + + private static void requireExactOriginalStartSessionSelector( + net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence + .Request + selector, + CanonicalGameInstanceLaunchAssociation association) { + var descriptor = association.launchBindingEvidence().descriptor(); + if (!selector.targetNamespace().equals(association.targetNamespace()) + || !selector.canonicalTenantId().equals(association.canonicalTenantId()) + || !selector.worldSlug().equals(association.worldSlug()) + || !selector.gameInstanceUuid().equals(association.gameInstanceUuid()) + || !selector.controlPlaneRequestId().equals(association.controlPlaneRequestId()) + || !selector.launchDescriptorId().equals(association.launchDescriptorId()) + || !selector.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !selector.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !selector + .expectedReleaseAttestationEvidenceDigest() + .equals(association.launchBindingEvidence().releaseAttestation().evidenceDigest())) { + throw new LaunchAssociationOwnerReadMismatchException( + "Canonical launch association differs from its exact original StartSession selector"); + } + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row == null ? null : row.get(field, byte[].class); + if (value == null) { + throw new IllegalStateException("Persisted owner association is missing " + field); + } + return value.clone(); + } + + private static String sha256(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + /** Locks the exact canonical launch association and its current Game Session row. */ + public CanonicalInitialAdmissionLaunchTarget lockForInitialAdmission( + String targetNamespace, UUID canonicalTenantId, UUID realmId, UUID canonicalGameInstanceId) { + return lockForInitialAdmission( + targetNamespace, canonicalTenantId, realmId, canonicalGameInstanceId, true); + } + + /** Locks the immutable launch owner and current row for an owner-local admission transaction. */ + public CanonicalInitialAdmissionLaunchTarget lockForInitialAdmission( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID canonicalGameInstanceId, + boolean requireRunning) { + requireWritableReadCommittedOwnerTransaction(); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Initial admission targetNamespace does not match this Game Session owner"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + Record row = + findForInitialAdmission( + targetNamespace, canonicalTenantId, realmId, canonicalGameInstanceId, true); + if (row == null) { + throw new IllegalStateException( + "Exact canonical launch association and current runtime row are unavailable"); + } + CanonicalGameInstanceLaunchAssociation association = toAssociation(row); + if ((requireRunning + && association.currentGameInstanceStatus() != CurrentGameInstanceStatus.RUNNING) + || !association.targetNamespace().equals(targetNamespace) + || !association.canonicalTenantId().equals(canonicalTenantId) + || !association.gameInstanceUuid().equals(canonicalGameInstanceId)) { + throw new IllegalStateException( + "Initial admission requires the exact canonical launch target in RUNNING state"); + } + return new CanonicalInitialAdmissionLaunchTarget( + association, + row.get("canonical_realm_id", UUID.class), + row.get("current_game_instance_id", Long.class), + row.get("current_version_id", Long.class)); + } + + /** Reads the exact launch association and current runtime row after owner commit. */ + public Optional readForInitialAdmission( + String targetNamespace, UUID canonicalTenantId, UUID realmId, UUID canonicalGameInstanceId) { + requireOutsideTransaction(); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Initial admission targetNamespace does not match this Game Session owner"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + Record row = + findForInitialAdmission( + targetNamespace, canonicalTenantId, realmId, canonicalGameInstanceId, false); + if (row == null) { + return Optional.empty(); + } + CanonicalGameInstanceLaunchAssociation association = toAssociation(row); + return Optional.of( + new CanonicalInitialAdmissionLaunchTarget( + association, + row.get("canonical_realm_id", UUID.class), + row.get("current_game_instance_id", Long.class), + row.get("current_version_id", Long.class))); + } + + private Record findForInitialAdmission( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID canonicalGameInstanceId, + boolean forUpdate) { + return dsl.fetchOne( + "SELECT association.*, current.id AS current_game_instance_id, " + + "current.status AS current_status, current.row_version AS current_row_version, " + + "current.game_instance_uuid AS current_game_instance_uuid, " + + "current.game_template_id AS current_game_template_id, " + + "current.launch_descriptor_id AS current_launch_descriptor_id, " + + "current.version_id AS current_version_id, " + + "current.release_bundle_id AS current_release_bundle_id, " + + "current.generation_config_revision AS current_generation_config_revision, " + + "current.version_state_epoch AS current_version_state_epoch, " + + "current.run_owned_start_request_id AS current_run_owned_start_request_id, " + + "current.run_owned_start_published_release_bundle_ref " + + "AS current_run_owned_start_published_release_bundle_ref " + + "FROM " + + ASSOCIATION_TABLE + + " association JOIN game_instances current " + + "ON current.id = association.game_instance_id " + + "AND current.tenant_id = association.game_session_tenant_id " + + "JOIN game_session_canonical_realm_catalog realm " + + "ON realm.target_namespace = association.target_namespace " + + "AND realm.realm_id = association.canonical_realm_id " + + "AND realm.canonical_tenant_id = association.canonical_tenant_id " + + "AND realm.world_slug = association.world_slug " + + "AND realm.playable_state_namespace_id = association.playable_state_namespace_id " + + "AND realm.visible = TRUE AND realm.public_production = TRUE " + + "AND realm.state_scope = 'SHARED' " + + "WHERE association.target_namespace = ? " + + "AND association.canonical_tenant_id = ? " + + "AND association.canonical_realm_id = ? " + + "AND association.game_instance_uuid = ?" + + (forUpdate ? " FOR UPDATE OF association, current" : ""), + targetNamespace, + canonicalTenantId, + realmId, + canonicalGameInstanceId); + } + + private void lockRequest(String controlPlaneRequestId) { + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ?, 0))", + workloadNamespace, + controlPlaneRequestId); + } + + private GameInstanceRow requireLockedRuntime(long tenantId, long gameInstanceId) { + Record row = + dsl.fetchOne( + "SELECT id, tenant_id, game_instance_uuid, status, row_version, game_template_id, " + + "launch_descriptor_id, version_id, release_bundle_id, generation_config_revision, " + + "version_state_epoch, run_owned_start_request_id, " + + "run_owned_start_published_release_bundle_ref FROM game_instances " + + "WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + gameInstanceId); + if (row == null) { + throw new IllegalStateException("Game Session owner instance row is missing in tenant scope"); + } + return toRuntime(row, "status", "row_version"); + } + + private RealmOwnerProjection requirePublicSharedRealm( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) { + Record row = + dsl.fetchOne( + "SELECT realm_id, playable_state_namespace_id, state_scope, public_production, visible " + + "FROM game_session_canonical_realm_catalog WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND world_slug = ? AND public_production = TRUE " + + "AND visible = TRUE", + workloadNamespace, + descriptor.canonicalTenantId(), + descriptor.worldSlug()); + if (row == null + || !Boolean.TRUE.equals(row.get("public_production", Boolean.class)) + || !Boolean.TRUE.equals(row.get("visible", Boolean.class)) + || !RealmEntryPolicy.StateScope.SHARED + .name() + .equals(row.get("state_scope", String.class))) { + throw new IllegalStateException( + "Canonical launch association requires the owner's visible public SHARED realm"); + } + UUID namespaceId = row.get("playable_state_namespace_id", UUID.class); + UUID realmId = row.get("realm_id", UUID.class); + requireNonNil(namespaceId, "playableStateNamespaceId"); + requireNonNil(realmId, "canonicalRealmId"); + return new RealmOwnerProjection(realmId, namespaceId); + } + + private FreshTenantOwnerMapping requireFreshTenantMapping( + FreshGameSessionTenantAssociation expected) { + RuntimeTenantIdentityEvidence source = expected.sourceEvidence(); + Record row = + dsl.fetchOne( + "SELECT association.association_operation_id, association.association_request_id, " + + "association.source_schema_version, association.source_target_namespace, " + + "association.source_request_id, association.source_canonical_tenant_id, " + + "association.canonical_tenant_id, association.legacy_game_session_tenant_id, " + + "association.source_game_row_id, association.source_game_tenant_key, " + + "association.provenance_kind, association.association_kind, " + + "claim.association_operation_id AS claim_operation_id, " + + "claim.association_request_id AS claim_request_id, " + + "claim.association_kind AS claim_kind, claim.reservation_kind AS claim_reservation_kind, " + + "reservation.reservation_kind " + + "FROM game_session_fresh_tenant_association association " + + "JOIN game_session_tenant_canonical_claim claim ON " + + "claim.target_namespace = association.target_namespace " + + "AND claim.canonical_tenant_id = association.canonical_tenant_id " + + "AND claim.legacy_game_session_tenant_id = association.legacy_game_session_tenant_id " + + "AND claim.association_operation_id = association.association_operation_id " + + "AND claim.association_kind = association.association_kind " + + "JOIN game_session_tenant_scope_reservation reservation ON " + + "reservation.game_session_tenant_id = association.legacy_game_session_tenant_id " + + "WHERE association.target_namespace = ? AND association.association_operation_id = ?", + workloadNamespace, + expected.associationOperationId()); + if (row == null) { + throw new IllegalStateException( + "Persisted fresh Game Session tenant association is unavailable"); + } + UUID operationId = row.get("association_operation_id", UUID.class); + long localTenantId = row.get("legacy_game_session_tenant_id", Long.class); + if (!expected.associationOperationId().equals(operationId) + || localTenantId != expected.legacyGameSessionTenantId() + || !source.requestId().equals(row.get("association_request_id", UUID.class)) + || !source.requestId().equals(row.get("source_request_id", UUID.class)) + || source.schemaVersion() != row.get("source_schema_version", Integer.class) + || !source.targetNamespace().equals(row.get("source_target_namespace", String.class)) + || !source.canonicalTenantId().equals(row.get("source_canonical_tenant_id", UUID.class)) + || !source.canonicalTenantId().equals(row.get("canonical_tenant_id", UUID.class)) + || source.sourceGameRowId() != row.get("source_game_row_id", Long.class) + || !source.sourceGameTenantKey().equals(row.get("source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(row.get("provenance_kind", String.class)) + || !operationId.equals(row.get("claim_operation_id", UUID.class)) + || !source.requestId().equals(row.get("claim_request_id", UUID.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("association_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("claim_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("reservation_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("claim_reservation_kind", String.class))) { + throw new IllegalStateException( + "Persisted fresh tenant source identity does not match its owner"); + } + return new FreshTenantOwnerMapping(operationId); + } + + private Optional findByRequest(String controlPlaneRequestId, boolean forUpdate) { + String sql = + "SELECT association.*, current.status AS current_status, " + + "current.row_version AS current_row_version, current.game_instance_uuid AS " + + "current_game_instance_uuid, current.game_template_id AS current_game_template_id, " + + "current.launch_descriptor_id AS current_launch_descriptor_id, " + + "current.version_id AS current_version_id, current.release_bundle_id AS " + + "current_release_bundle_id, current.generation_config_revision AS " + + "current_generation_config_revision, current.version_state_epoch AS " + + "current_version_state_epoch, current.run_owned_start_request_id AS " + + "current_run_owned_start_request_id, current.run_owned_start_published_release_bundle_ref " + + "AS current_run_owned_start_published_release_bundle_ref " + + "FROM " + + ASSOCIATION_TABLE + + " association JOIN game_instances current " + + "ON current.id = association.game_instance_id " + + "AND current.tenant_id = association.game_session_tenant_id " + + "JOIN game_session_canonical_realm_catalog realm " + + "ON realm.target_namespace = association.target_namespace " + + "AND realm.realm_id = association.canonical_realm_id " + + "AND realm.canonical_tenant_id = association.canonical_tenant_id " + + "AND realm.world_slug = association.world_slug " + + "AND realm.playable_state_namespace_id = association.playable_state_namespace_id " + + "AND realm.visible = TRUE AND realm.public_production = TRUE " + + "AND realm.state_scope = 'SHARED' " + + "WHERE association.target_namespace = ? AND association.control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE OF association, current" : ""); + return Optional.ofNullable(dsl.fetchOne(sql, workloadNamespace, controlPlaneRequestId)); + } + + private CanonicalGameInstanceLaunchAssociation toAssociation(Record row) { + try { + CompleteLaunchBindingEvidence evidence = + JSON.readValue( + row.get("complete_launch_binding_evidence", JSONB.class).data(), + CompleteLaunchBindingEvidence.class); + ValidatedBinding binding = validateBinding(evidence); + UUID canonicalTenantId = row.get("canonical_tenant_id", UUID.class); + UUID associationOperationId = row.get("tenant_association_operation_id", UUID.class); + UUID gameInstanceUuid = row.get("game_instance_uuid", UUID.class); + UUID namespaceId = row.get("playable_state_namespace_id", UUID.class); + Boolean publicProduction = row.get("public_production", Boolean.class); + if (!workloadNamespace.equals(row.get("target_namespace", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("tenant_association_kind", String.class)) + || !binding.descriptor().targetNamespace().equals(workloadNamespace) + || !binding + .descriptor() + .controlPlaneRequestId() + .equals(row.get("control_plane_request_id", String.class)) + || !canonicalTenantId.equals(binding.descriptor().canonicalTenantId()) + || !row.get("world_slug", String.class).equals(binding.descriptor().worldSlug()) + || !row.get("launch_descriptor_id", String.class) + .equals(binding.descriptor().launchDescriptorId()) + || row.get("game_template_id", Long.class) != binding.descriptor().gameTemplateId() + || row.get("version_id", Long.class) != binding.descriptor().versionId() + || row.get("release_bundle_id", Long.class) != binding.descriptor().releaseBundleId() + || !row.get("generation_config_revision", String.class) + .equals(binding.descriptor().generationConfigRevision()) + || row.get("version_state_epoch", Long.class) != binding.descriptor().versionStateEpoch() + || !Boolean.TRUE.equals(publicProduction)) { + throw new IllegalStateException( + "Persisted launch association contradicts its typed binding"); + } + RuntimeTenantIdentityEvidence source = sourceFromRow(row); + FreshGameSessionTenantAssociation mapping = + new FreshGameSessionTenantAssociation( + associationOperationId, row.get("game_session_tenant_id", Long.class), source); + requireFreshTenantMapping(mapping); + GameInstanceRow current = + new GameInstanceRow( + row.get("game_instance_id", Long.class), + row.get("game_session_tenant_id", Long.class), + row.get("current_game_instance_uuid", UUID.class), + row.get("current_status", String.class), + row.get("current_row_version", Long.class), + row.get("current_game_template_id", Long.class), + row.get("current_launch_descriptor_id", String.class), + row.get("current_version_id", Long.class), + row.get("current_release_bundle_id", Long.class), + row.get("current_generation_config_revision", String.class), + row.get("current_version_state_epoch", Long.class), + row.get("current_run_owned_start_request_id", String.class), + row.get("current_run_owned_start_published_release_bundle_ref", String.class)); + requireRuntimeBinding(current, evidence); + if (!gameInstanceUuid.equals(current.gameInstanceUuid()) + || current.rowVersion() < row.get("captured_starting_row_version", Long.class) + || !RealmEntryPolicy.StateScope.SHARED + .name() + .equals(row.get("playable_state_scope", String.class))) { + throw new IllegalStateException( + "Current Game Session row contradicts its launch association"); + } + return new CanonicalGameInstanceLaunchAssociation( + workloadNamespace, + row.get("game_session_tenant_id", Long.class), + associationOperationId, + canonicalTenantId, + gameInstanceUuid, + row.get("world_slug", String.class), + namespaceId, + RealmEntryPolicy.StateScope.SHARED, + true, + binding.descriptor().controlPlaneRequestId(), + binding.descriptor().launchDescriptorId(), + row.get("captured_starting_row_version", Long.class), + evidence, + CurrentGameInstanceStatus.valueOf(current.status()), + current.rowVersion()); + } catch (RuntimeException exception) { + if (exception instanceof IllegalStateException illegalState) { + throw illegalState; + } + throw new IllegalStateException( + "Persisted canonical launch association is malformed", exception); + } + } + + private static RuntimeTenantIdentityEvidence sourceFromRow(Record row) { + return new RuntimeTenantIdentityEvidence( + row.get("tenant_source_schema_version", Integer.class), + row.get("tenant_source_target_namespace", String.class), + row.get("tenant_source_request_id", UUID.class), + row.get("tenant_source_canonical_tenant_id", UUID.class), + row.get("tenant_source_game_row_id", Long.class), + row.get("tenant_source_game_tenant_key", String.class), + row.get("tenant_source_provenance_kind", String.class)); + } + + private void requireExactRetry( + CanonicalGameInstanceLaunchAssociation stored, + FreshGameSessionTenantAssociation expectedTenant, + long expectedGameInstanceId, + GameInstanceRow current, + CompleteLaunchBindingEvidence expectedEvidence, + FreshTenantOwnerMapping mapping, + RealmOwnerProjection realm) { + if (stored.gameSessionTenantId() != expectedTenant.legacyGameSessionTenantId() + || !stored.tenantAssociationOperationId().equals(mapping.operationId()) + || !stored.canonicalTenantId().equals(expectedTenant.sourceEvidence().canonicalTenantId()) + || !stored.playableStateNamespaceId().equals(realm.playableStateNamespaceId()) + || !stored.launchBindingEvidence().equals(expectedEvidence) + || !stored.gameInstanceUuid().equals(current.gameInstanceUuid()) + || stored.currentRowVersion() > current.rowVersion() + || stored.capturedStartingRowVersion() > current.rowVersion()) { + throw new CanonicalGameInstanceLaunchAssociationConflictException( + "Launch association request was reused with a changed tenant, instance, or source binding"); + } + Record row = + dsl.fetchOne( + "SELECT game_instance_id FROM " + + ASSOCIATION_TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ?", + workloadNamespace, + stored.controlPlaneRequestId()); + if (row == null || row.get("game_instance_id", Long.class) != expectedGameInstanceId) { + throw new CanonicalGameInstanceLaunchAssociationConflictException( + "Launch association request was reused for another Game Session instance"); + } + requireRuntimeBinding(current, expectedEvidence); + } + + private static void requireStartingRuntime( + GameInstanceRow runtime, CompleteLaunchBindingEvidence evidence) { + requireRuntimeBinding(runtime, evidence); + if (!"STARTING".equals(runtime.status()) + || !evidence.descriptor().controlPlaneRequestId().equals(runtime.runOwnedStartRequestId()) + || !evidence + .descriptor() + .publishedReleaseBundleRef() + .equals(runtime.runOwnedStartPublishedReleaseBundleRef())) { + throw new IllegalStateException( + "Launch association capture requires the exact persisted run-owned STARTING instance"); + } + } + + private static void requireRuntimeBinding( + GameInstanceRow runtime, CompleteLaunchBindingEvidence evidence) { + var descriptor = evidence.descriptor(); + if (runtime.id() <= 0 + || runtime.tenantId() <= 0 + || runtime.gameInstanceUuid() == null + || NIL_UUID.equals(runtime.gameInstanceUuid()) + || runtime.rowVersion() < 0 + || runtime.gameTemplateId() == null + || runtime.gameTemplateId() != descriptor.gameTemplateId() + || !Objects.equals(runtime.launchDescriptorId(), descriptor.launchDescriptorId()) + || runtime.versionId() == null + || runtime.versionId() != descriptor.versionId() + || runtime.releaseBundleId() == null + || runtime.releaseBundleId() != descriptor.releaseBundleId() + || runtime.versionStateEpoch() == null + || runtime.versionStateEpoch() != descriptor.versionStateEpoch() + || !Objects.equals( + runtime.generationConfigRevision(), descriptor.generationConfigRevision()) + || !Objects.equals(runtime.runOwnedStartRequestId(), descriptor.controlPlaneRequestId()) + || !Objects.equals( + runtime.runOwnedStartPublishedReleaseBundleRef(), + descriptor.publishedReleaseBundleRef())) { + throw new IllegalStateException( + "Game Session instance does not match the complete launch binding"); + } + try { + CurrentGameInstanceStatus.valueOf(runtime.status()); + } catch (RuntimeException invalidStatus) { + throw new IllegalStateException("Game Session instance status is unavailable", invalidStatus); + } + } + + private static GameInstanceRow toRuntime( + Record row, String statusColumn, String rowVersionColumn) { + return toRuntime( + row, + statusColumn, + rowVersionColumn, + "game_instance_uuid", + "game_template_id", + "launch_descriptor_id", + "version_id", + "release_bundle_id", + "generation_config_revision", + "version_state_epoch", + "run_owned_start_request_id", + "run_owned_start_published_release_bundle_ref"); + } + + private static GameInstanceRow toRuntime( + Record row, + String statusColumn, + String rowVersionColumn, + String uuidColumn, + String templateColumn, + String descriptorColumn, + String versionColumn, + String bundleColumn, + String configColumn, + String epochColumn, + String requestColumn, + String publishedRefColumn) { + return new GameInstanceRow( + row.get("id", Long.class), + row.get("tenant_id", Long.class), + row.get(uuidColumn, UUID.class), + row.get(statusColumn, String.class), + row.get(rowVersionColumn, Long.class), + row.get(templateColumn, Long.class), + row.get(descriptorColumn, String.class), + row.get(versionColumn, Long.class), + row.get(bundleColumn, Long.class), + row.get(configColumn, String.class), + row.get(epochColumn, Long.class), + row.get(requestColumn, String.class), + row.get(publishedRefColumn, String.class)); + } + + private static ValidatedBinding validateBinding(CompleteLaunchBindingEvidence evidence) { + Objects.requireNonNull(evidence, "launchBindingEvidence"); + var descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + requireRequestId(descriptor.controlPlaneRequestId()); + return new ValidatedBinding(evidence); + } + + private void requireFreshSourceIdentity( + FreshGameSessionTenantAssociation association, RuntimeTenantIdentityEvidence evidence) { + if (evidence.schemaVersion() != 1 + || !workloadNamespace.equals(evidence.targetNamespace()) + || evidence.requestId() == null + || NIL_UUID.equals(evidence.requestId()) + || evidence.canonicalTenantId() == null + || NIL_UUID.equals(evidence.canonicalTenantId()) + || association.legacyGameSessionTenantId() <= 0 + || !"NEW_GAME_ROW".equals(evidence.provenanceKind())) { + throw new IllegalArgumentException( + "Only exact fresh NEW_GAME_ROW owner identity is supported"); + } + } + + private static String serializeEvidence(CompleteLaunchBindingEvidence evidence) { + try { + return JSON.writeValueAsString(evidence); + } catch (JacksonException exception) { + throw new IllegalStateException( + "Failed to persist complete launch binding evidence", exception); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical launch association capture requires a writable owner transaction"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equals(settings.get("transaction_isolation", String.class)) + || !"off".equals(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "Canonical launch association capture requires writable READ COMMITTED isolation"); + } + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical launch association read requires a committed owner read"); + } + } + + private static void requireRequestId(String value) { + Objects.requireNonNull(value, "controlPlaneRequestId"); + if (value.isBlank() || value.length() > 128) { + throw new IllegalArgumentException("controlPlaneRequestId must contain 1 to 128 characters"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private record ValidatedBinding(CompleteLaunchBindingEvidence evidence) { + private net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence + descriptor() { + return evidence.descriptor(); + } + } + + private record FreshTenantOwnerMapping(UUID operationId) {} + + private record RealmOwnerProjection(UUID realmId, UUID playableStateNamespaceId) {} + + private record GameInstanceRow( + long id, + long tenantId, + UUID gameInstanceUuid, + String status, + long rowVersion, + Long gameTemplateId, + String launchDescriptorId, + Long versionId, + Long releaseBundleId, + String generationConfigRevision, + Long versionStateEpoch, + String runOwnedStartRequestId, + String runOwnedStartPublishedReleaseBundleRef) {} + + /** Owner-derived association readback; deliberately not an AttemptClaim or continuation token. */ + public record OriginalStartSessionAssociation( + CanonicalGameInstanceLaunchAssociation association, UUID ownerAttemptId, long ownerFence) { + public OriginalStartSessionAssociation { + Objects.requireNonNull(association, "association"); + requireNonNil(ownerAttemptId, "ownerAttemptId"); + requirePositive(ownerFence, "ownerFence"); + } + } + + public static final class LaunchAssociationOwnerReadMismatchException extends RuntimeException { + public LaunchAssociationOwnerReadMismatchException(String message) { + super(message); + } + } + + public static final class CanonicalGameInstanceLaunchAssociationConflictException + extends RuntimeException { + public CanonicalGameInstanceLaunchAssociationConflictException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java new file mode 100644 index 0000000000..9e62010a0a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; + +/** Versioned local source-intake digests; neither digest authenticates Game Design. */ +public final class GameSessionAuthoredWorldIntakeDigest { + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + private GameSessionAuthoredWorldIntakeDigest() {} + + public static String requestDigest(UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireIdentity(intakeRequestId, "intakeRequestId"); + Objects.requireNonNull(source, "source"); + return digest( + "game-session-authored-world-intake-request/v1", + intakeRequestId.toString(), + source.evidenceDigest()); + } + + public static String receiptDigest( + UUID localOperationId, String requestDigest, String evidenceDigest) { + requireIdentity(localOperationId, "localOperationId"); + requireDigest(requestDigest); + requireDigest(evidenceDigest); + return digest( + "game-session-authored-world-intake-receipt/v1", + localOperationId.toString(), + requestDigest, + evidenceDigest); + } + + private static String digest(String... values) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String value : values) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void requireIdentity(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException("A canonical SHA-256 digest is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java new file mode 100644 index 0000000000..e411647eaa --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java @@ -0,0 +1,515 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Game Session's immutable, owner-local copy of authenticated Game Design authored-world source. + */ +public class GameSessionAuthoredWorldSourceRepository { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private static final Table TENANT_BINDING = + DSL.table(DSL.name("game_session_authored_world_tenant_source_binding")); + private static final Field BINDING_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field BINDING_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field BINDING_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field BINDING_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field BINDING_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field BINDING_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + + private static final Table INTAKE = + DSL.table(DSL.name("game_session_authored_world_source_intake")); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field OPERATION_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final Field OPERATION_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Integer.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("source_registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("source_request_digest"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_SLUG = DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_provenance_kind"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted Spring collaborator is validated before use; no resources or finalizer are acquired." + + " The repository remains non-final for transaction proxying.") + public GameSessionAuthoredWorldSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Persists one complete source receipt under the caller's owner transaction. + * + *

The authenticated source client is responsible for obtaining the evidence from Game Design. + * This repository validates its closed evidence and digests, then atomically stores that exact + * copy with the stable tenant and world selector claims. + */ + @Transactional(propagation = Propagation.MANDATORY) + public IntakeReceipt register(UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireActiveOwnerTransaction(); + requireNonNil(intakeRequestId, "intakeRequestId"); + AuthoredWorldSourceEvidence validatedSource = validateSource(source); + String requestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, validatedSource); + + Record existingRequest = + findByIntakeRequest(validatedSource.targetNamespace(), intakeRequestId); + if (existingRequest != null) { + return requireExactReplay(existingRequest, intakeRequestId, requestDigest, validatedSource); + } + + ensureTenantBinding(validatedSource); + UUID operationId = UUID.randomUUID(); + String receiptDigest = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, validatedSource.evidenceDigest()); + + int inserted = + dsl.insertInto(INTAKE) + .set(OPERATION_ID, operationId) + .set(OPERATION_SCHEMA_VERSION, SCHEMA_VERSION) + .set(OPERATION_NAMESPACE, validatedSource.targetNamespace()) + .set(INTAKE_REQUEST_ID, intakeRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(SOURCE_SCHEMA_VERSION, validatedSource.schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, validatedSource.registrationRequestId()) + .set(SOURCE_OPERATION_ID, validatedSource.operationId()) + .set(SOURCE_REQUEST_DIGEST, validatedSource.requestDigest()) + .set(CANONICAL_TENANT_ID, validatedSource.canonicalTenantId()) + .set(TENANT_SLUG, validatedSource.tenantSlug()) + .set(WORLD_SLUG, validatedSource.worldSlug()) + .set(WORLD_DISPLAY_NAME, validatedSource.worldDisplayName()) + .set(SOURCE_GAME_ROW_ID, validatedSource.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, validatedSource.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, validatedSource.provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, validatedSource.evidenceDigest()) + .set(RECEIPT_DIGEST, receiptDigest) + .onConflictDoNothing() + .execute(); + if (inserted == 0) { + Record racedRequest = findByIntakeRequest(validatedSource.targetNamespace(), intakeRequestId); + if (racedRequest != null) { + return requireExactReplay(racedRequest, intakeRequestId, requestDigest, validatedSource); + } + if (findBySourceOperation(validatedSource.targetNamespace(), validatedSource.operationId()) + != null) { + throw new RegistrationConflictException( + "Game Design source operation is already consumed by another intake request"); + } + if (findBySourceRegistrationRequest( + validatedSource.targetNamespace(), validatedSource.registrationRequestId()) + != null) { + throw new RegistrationConflictException( + "Game Design source registration request is already consumed by another intake"); + } + if (findByWorldSelector( + validatedSource.targetNamespace(), + validatedSource.canonicalTenantId(), + validatedSource.worldSlug()) + != null) { + throw new RegistrationConflictException( + "Authored-world selector is already bound to another consumed source"); + } + throw new RegistrationConflictException( + "Authored-world source intake conflicts with an existing owner claim"); + } + + Record persisted = findByIntakeRequest(validatedSource.targetNamespace(), intakeRequestId); + if (persisted == null) { + throw new IllegalStateException("Committed authored-world source intake is missing"); + } + IntakeReceipt receipt = toReceipt(persisted); + requireExactSource(receipt.source(), validatedSource); + requireTenantBinding(receipt.source()); + return receipt; + } + + /** Reads the exact committed local operation without allocating or repairing selector state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + UUID localOperationId, UUID canonicalTenantId, String worldSlug, String namespace) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake read requires a committed-outcome owner read"); + } + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + requireNonNil(localOperationId, "localOperationId"); + + Record record = + dsl.selectFrom(INTAKE) + .where( + OPERATION_ID + .eq(localOperationId) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(OPERATION_NAMESPACE.eq(namespace))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + IntakeReceipt receipt = toReceipt(record); + requireTenantBinding(receipt.source()); + return Optional.of(receipt); + } + + /** + * Resolves the one committed source for an exact canonical world selector. + * + *

This owner-local read does not infer source operation IDs or digests from retained numeric + * keys. The returned original receipt still requires exact comparison with the selected catalog + * and separately proved retained association before any launch use. + */ + @Transactional(propagation = Propagation.NEVER, readOnly = true) + public Optional readByWorldSelector( + String namespace, UUID canonicalTenantId, String worldSlug) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake read requires a committed-outcome owner read"); + } + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + Record record = findByWorldSelector(namespace, canonicalTenantId, worldSlug); + if (record == null) { + return Optional.empty(); + } + IntakeReceipt receipt = toReceipt(record); + requireTenantBinding(receipt.source()); + return Optional.of(receipt); + } + + /** Reads an exact committed retry by its stable intake request without allocating owner state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByIntakeRequest(String namespace, UUID intakeRequestId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake read requires a committed-outcome owner read"); + } + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + + Record record = + dsl.selectFrom(INTAKE) + .where(OPERATION_NAMESPACE.eq(namespace).and(INTAKE_REQUEST_ID.eq(intakeRequestId))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + IntakeReceipt receipt = toReceipt(record); + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.source().targetNamespace().equals(namespace)) { + throw new InvalidIntakeEvidenceException( + "Persisted authored-world source intake request binding is invalid"); + } + requireTenantBinding(receipt.source()); + return Optional.of(receipt); + } + + private void ensureTenantBinding(AuthoredWorldSourceEvidence source) { + Record existing = findTenantBinding(source.targetNamespace(), source.canonicalTenantId()); + if (existing != null) { + requireMatchingBinding(existing, source); + return; + } + + int inserted = + dsl.insertInto(TENANT_BINDING) + .set(BINDING_NAMESPACE, source.targetNamespace()) + .set(BINDING_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(BINDING_TENANT_SLUG, source.tenantSlug()) + .set(BINDING_SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(BINDING_SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(BINDING_PROVENANCE_KIND, source.provenanceKind()) + .onConflictDoNothing() + .execute(); + if (inserted == 1) { + return; + } + + Record tenantBinding = findTenantBinding(source.targetNamespace(), source.canonicalTenantId()); + if (tenantBinding != null) { + requireMatchingBinding(tenantBinding, source); + return; + } + if (findTenantSlugBinding(source.targetNamespace(), source.tenantSlug()) != null) { + throw new RegistrationConflictException( + "Tenant selector is already owned by another canonical tenant"); + } + if (findSourceRowBinding(source.targetNamespace(), source.sourceGameRowId()) != null) { + throw new RegistrationConflictException( + "Game Design source row is already bound to another canonical tenant"); + } + throw new RegistrationConflictException("Tenant source binding conflicts with an owner claim"); + } + + private void requireTenantBinding(AuthoredWorldSourceEvidence source) { + Record binding = findTenantBinding(source.targetNamespace(), source.canonicalTenantId()); + if (binding == null) { + throw new InvalidIntakeEvidenceException("Tenant source selector binding is missing"); + } + requireMatchingBinding(binding, source); + } + + private void requireMatchingBinding(Record binding, AuthoredWorldSourceEvidence source) { + if (!Objects.equals(binding.get(BINDING_NAMESPACE), source.targetNamespace()) + || !Objects.equals(binding.get(BINDING_CANONICAL_TENANT_ID), source.canonicalTenantId()) + || !Objects.equals(binding.get(BINDING_TENANT_SLUG), source.tenantSlug()) + || !Objects.equals(binding.get(BINDING_SOURCE_GAME_ROW_ID), source.sourceGameRowId()) + || !Objects.equals( + binding.get(BINDING_SOURCE_GAME_TENANT_KEY), source.sourceGameTenantKey()) + || !Objects.equals(binding.get(BINDING_PROVENANCE_KIND), source.provenanceKind())) { + throw new RegistrationConflictException( + "Canonical tenant source or stable tenant selector conflicts with its prior claim"); + } + } + + private IntakeReceipt requireExactReplay( + Record record, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source) { + IntakeReceipt receipt = toReceipt(record); + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.requestDigest().equals(requestDigest) + || !receipt.source().equals(source)) { + throw new RegistrationConflictException( + "Authored-world intake identity was reused with changed source evidence"); + } + requireTenantBinding(receipt.source()); + return receipt; + } + + private void requireExactSource( + AuthoredWorldSourceEvidence actual, AuthoredWorldSourceEvidence expected) { + if (!actual.equals(expected)) { + throw new InvalidIntakeEvidenceException( + "Persisted authored-world source differs from its authenticated input"); + } + } + + private AuthoredWorldSourceEvidence validateSource(AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(source, "source"); + try { + return new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + } catch (IllegalArgumentException exception) { + throw new InvalidIntakeEvidenceException( + "Game Design authored-world source evidence is invalid", exception); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake registration requires an active owner transaction"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private Record findByIntakeRequest(String namespace, UUID intakeRequestId) { + return dsl.selectFrom(INTAKE) + .where(OPERATION_NAMESPACE.eq(namespace).and(INTAKE_REQUEST_ID.eq(intakeRequestId))) + .fetchOne(); + } + + private Record findBySourceOperation(String namespace, UUID sourceOperationId) { + return dsl.selectFrom(INTAKE) + .where(OPERATION_NAMESPACE.eq(namespace).and(SOURCE_OPERATION_ID.eq(sourceOperationId))) + .fetchOne(); + } + + private Record findBySourceRegistrationRequest(String namespace, UUID sourceRequestId) { + return dsl.selectFrom(INTAKE) + .where( + OPERATION_NAMESPACE + .eq(namespace) + .and(SOURCE_REGISTRATION_REQUEST_ID.eq(sourceRequestId))) + .fetchOne(); + } + + private Record findByWorldSelector(String namespace, UUID canonicalTenantId, String worldSlug) { + return dsl.selectFrom(INTAKE) + .where( + OPERATION_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug))) + .fetchOne(); + } + + private Record findTenantBinding(String namespace, UUID canonicalTenantId) { + return dsl.selectFrom(TENANT_BINDING) + .where( + BINDING_NAMESPACE.eq(namespace).and(BINDING_CANONICAL_TENANT_ID.eq(canonicalTenantId))) + .fetchOne(); + } + + private Record findTenantSlugBinding(String namespace, String tenantSlug) { + return dsl.selectFrom(TENANT_BINDING) + .where(BINDING_NAMESPACE.eq(namespace).and(BINDING_TENANT_SLUG.eq(tenantSlug))) + .fetchOne(); + } + + private Record findSourceRowBinding(String namespace, long sourceGameRowId) { + return dsl.selectFrom(TENANT_BINDING) + .where(BINDING_NAMESPACE.eq(namespace).and(BINDING_SOURCE_GAME_ROW_ID.eq(sourceGameRowId))) + .fetchOne(); + } + + private IntakeReceipt toReceipt(Record record) { + try { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + Objects.requireNonNull(record.get(SOURCE_SCHEMA_VERSION)), + Objects.requireNonNull(record.get(OPERATION_NAMESPACE)), + Objects.requireNonNull(record.get(SOURCE_REGISTRATION_REQUEST_ID)), + Objects.requireNonNull(record.get(SOURCE_OPERATION_ID)), + Objects.requireNonNull(record.get(SOURCE_REQUEST_DIGEST)), + Objects.requireNonNull(record.get(CANONICAL_TENANT_ID)), + Objects.requireNonNull(record.get(TENANT_SLUG)), + Objects.requireNonNull(record.get(WORLD_SLUG)), + Objects.requireNonNull(record.get(WORLD_DISPLAY_NAME)), + Objects.requireNonNull(record.get(SOURCE_GAME_ROW_ID)), + Objects.requireNonNull(record.get(SOURCE_GAME_TENANT_KEY)), + Objects.requireNonNull(record.get(SOURCE_PROVENANCE_KIND)), + Objects.requireNonNull(record.get(SOURCE_EVIDENCE_DIGEST))); + if (!Integer.valueOf(SCHEMA_VERSION).equals(record.get(OPERATION_SCHEMA_VERSION))) { + throw new IllegalArgumentException("Unsupported local intake schema version"); + } + return new IntakeReceipt( + Objects.requireNonNull(record.get(OPERATION_ID)), + Objects.requireNonNull(record.get(INTAKE_REQUEST_ID)), + Objects.requireNonNull(record.get(REQUEST_DIGEST)), + source, + Objects.requireNonNull(record.get(RECEIPT_DIGEST))); + } catch (RuntimeException exception) { + if (exception instanceof InvalidIntakeEvidenceException) { + throw exception; + } + throw new InvalidIntakeEvidenceException( + "Persisted authored-world source intake evidence is invalid", exception); + } + } + + /** Immutable local receipt retaining the exact authenticated Game Design source record. */ + public record IntakeReceipt( + UUID operationId, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source, + String receiptDigest) { + public IntakeReceipt { + requireNonNil(operationId, "operationId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + AuthoredWorldSourceEvidence validated = + new AuthoredWorldSourceEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + if (!validated.equals(source) + || !requestDigest.equals( + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, source)) + || !receiptDigest.equals( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, source.evidenceDigest()))) { + throw new IllegalArgumentException( + "Game Session authored-world receipt digests do not match"); + } + } + } + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidIntakeEvidenceException extends IllegalStateException { + public InvalidIntakeEvidenceException(String message) { + super(message); + } + + public InvalidIntakeEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java new file mode 100644 index 0000000000..b82f5c4a4b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java @@ -0,0 +1,1146 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Game Session-owned immutable initial realm catalog creation and exact readback. + * + *

This is an unwired catalog source. It never creates or opens an admission pointer and does not + * establish World lifecycle, membership, entitlement, or creator authorization. + */ +public class GameSessionCanonicalRealmCatalogRepository { + private static final int SCHEMA_VERSION = 1; + private static final long INITIAL_CATALOG_REVISION = 1L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String REQUEST_DOMAIN = "game-session-canonical-realm-catalog-request/v1"; + private static final String RECEIPT_DOMAIN = "game-session-canonical-realm-catalog-receipt/v1"; + + private static final Table CATALOG = + DSL.table(DSL.name("game_session_canonical_realm_catalog")); + private static final Table SHARED_NAMESPACES = + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")); + + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_SLUG = DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field REALM_ID = DSL.field(DSL.name("realm_id"), UUID.class); + private static final Field REALM_SLUG = DSL.field(DSL.name("realm_slug"), String.class); + private static final Field REALM_DISPLAY_NAME = + DSL.field(DSL.name("realm_display_name"), String.class); + private static final Field VISIBLE = DSL.field(DSL.name("visible"), Boolean.class); + private static final Field PUBLIC_PRODUCTION = + DSL.field(DSL.name("public_production"), Boolean.class); + private static final Field STATE_SCOPE = DSL.field(DSL.name("state_scope"), String.class); + private static final Field PLAYABLE_STATE_NAMESPACE_ID = + DSL.field(DSL.name("playable_state_namespace_id"), UUID.class); + private static final Field CHARACTER_CREATION_POLICY = + DSL.field(DSL.name("character_creation_policy"), String.class); + private static final Field CATALOG_REVISION = + DSL.field(DSL.name("catalog_revision"), Long.class); + private static final Field CREATION_REQUEST_ID = + DSL.field(DSL.name("creation_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + private static final Field SOURCE_INTAKE_OPERATION_ID = + DSL.field(DSL.name("source_intake_operation_id"), UUID.class); + private static final Field SOURCE_INTAKE_SCHEMA_VERSION = + DSL.field(DSL.name("source_intake_schema_version"), Integer.class); + private static final Field SOURCE_INTAKE_REQUEST_ID = + DSL.field(DSL.name("source_intake_request_id"), UUID.class); + private static final Field SOURCE_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("source_intake_request_digest"), String.class); + private static final Field SOURCE_INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("source_intake_receipt_digest"), String.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Integer.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("source_registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("source_request_digest"), String.class); + private static final Field SOURCE_WORLD_DISPLAY_NAME = + DSL.field(DSL.name("source_world_display_name"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_provenance_kind"), String.class); + private static final Field BINDING_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + + private static final Field LEGACY_TENANT_ID = DSL.field(DSL.name("tenant_id"), Long.class); + private static final Field SHARED_NAMESPACE_ID = + DSL.field(DSL.name("playable_state_namespace_id"), UUID.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Fail-fast validation is local; no overridable callback or partially initialized object escapes.") + public GameSessionCanonicalRealmCatalogRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Resolves exact committed authored-world evidence before the catalog write transaction begins. + * The returned opaque prepared value can only be constructed by this repository and is verified + * again against the locked immutable owner rows during creation. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedInitialPublicProduction prepareInitialPublicProduction( + CreateCanonicalRealmCatalogRequest request) { + Objects.requireNonNull(request, "request"); + requireCommittedRead(); + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + request.targetNamespace(), + request.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException( + "Canonical tenant source binding is missing from committed Game Session owner storage"); + } + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + request.targetNamespace(), + request.sourceIntakeOperationId()); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Exact committed authored-world source intake is missing"); + } + IntakeReceipt committedSource = toIntakeReceipt(intake); + requireTenantBindingMatches(binding, committedSource.source()); + requireRequestMatchesSource(request, committedSource); + requireFreshSource(committedSource.source()); + requireNoRetainedTenantAssociation(request.targetNamespace(), request.canonicalTenantId()); + return new PreparedInitialPublicProduction(request, committedSource); + } + + /** + * Creates one public-production catalog snapshot under the caller's read-write owner transaction. + * Exact retries read back the original immutable result; changed intent conflicts. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalRealmCatalogSnapshot createInitialPublicProduction( + PreparedInitialPublicProduction prepared) { + Objects.requireNonNull(prepared, "prepared"); + CreateCanonicalRealmCatalogRequest request = prepared.request(); + requireWritableOwnerTransaction(); + + IntakeReceipt sourceReceipt = lockAndReadFreshSource(request); + if (!prepared.committedSource().equals(sourceReceipt)) { + throw new InvalidCatalogEvidenceException( + "Committed authored-world evidence changed before canonical catalog creation"); + } + // Retained association capture locks the V6 namespace family before committing an association. + // Taking the same relation lock before this check serializes both SHARED and ISOLATED creation + // against that owner transaction without deriving a link to any retained numeric tenant. + dsl.execute("LOCK TABLE gameplay_tenant_shared_playable_state_namespace IN ROW EXCLUSIVE MODE"); + requireNoRetainedTenantAssociation(request.targetNamespace(), request.canonicalTenantId()); + + String requestDigest = requestDigest(request, sourceReceipt); + Record existing = findByRequest(request.targetNamespace(), request.requestId()); + if (existing != null) { + return requireExactRetry(existing, request, sourceReceipt, requestDigest); + } + if (findPublicForTenant(request.targetNamespace(), request.canonicalTenantId()) != null) { + throw new CatalogConflictException( + "Canonical tenant already has a public-production realm catalog result"); + } + if (findByRealmSlug(request.targetNamespace(), request.canonicalTenantId(), request.realmSlug()) + != null) { + throw new CatalogConflictException("Realm selector is already owned by this tenant"); + } + + UUID realmId = UUID.randomUUID(); + requireNonNil(realmId, "allocated realmId"); + UUID namespaceId = + "SHARED".equals(request.stateScope()) + ? getOrCreateSharedNamespace(request.targetNamespace(), sourceReceipt) + : allocateIsolatedNamespace(); + UUID namespace = namespaceId; + String receiptDigest = + receiptDigest( + request, sourceReceipt, realmId, namespace, INITIAL_CATALOG_REVISION, requestDigest); + + int inserted = + dsl.insertInto(CATALOG) + .set(TARGET_NAMESPACE, request.targetNamespace()) + .set(CANONICAL_TENANT_ID, request.canonicalTenantId()) + .set(TENANT_SLUG, sourceReceipt.source().tenantSlug()) + .set(WORLD_SLUG, sourceReceipt.source().worldSlug()) + .set(REALM_ID, realmId) + .set(REALM_SLUG, request.realmSlug()) + .set(REALM_DISPLAY_NAME, request.realmDisplayName()) + .set(VISIBLE, request.visible()) + .set(PUBLIC_PRODUCTION, request.publicProduction()) + .set(STATE_SCOPE, request.stateScope()) + .set(PLAYABLE_STATE_NAMESPACE_ID, namespace) + .set(CHARACTER_CREATION_POLICY, request.characterCreationPolicy()) + .set(CATALOG_REVISION, INITIAL_CATALOG_REVISION) + .set(CREATION_REQUEST_ID, request.requestId()) + .set(REQUEST_DIGEST, requestDigest) + .set(RECEIPT_DIGEST, receiptDigest) + .set(SOURCE_INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(SOURCE_INTAKE_SCHEMA_VERSION, SCHEMA_VERSION) + .set(SOURCE_INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, sourceReceipt.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(SOURCE_SCHEMA_VERSION, sourceReceipt.source().schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, sourceReceipt.source().registrationRequestId()) + .set(SOURCE_OPERATION_ID, sourceReceipt.source().operationId()) + .set(SOURCE_REQUEST_DIGEST, sourceReceipt.source().requestDigest()) + .set(SOURCE_WORLD_DISPLAY_NAME, sourceReceipt.source().worldDisplayName()) + .set(SOURCE_GAME_ROW_ID, sourceReceipt.source().sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, sourceReceipt.source().sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, sourceReceipt.source().provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, sourceReceipt.source().evidenceDigest()) + .onConflictDoNothing() + .execute(); + + Record persisted = findByRequest(request.targetNamespace(), request.requestId()); + if (persisted == null) { + if (inserted == 0) { + throw new CatalogConflictException( + "Canonical realm selector or public-production claim conflicts with existing authority"); + } + throw new InvalidCatalogEvidenceException( + "Canonical realm catalog creation did not read back its persisted request"); + } + return requireExactRetry(persisted, request, sourceReceipt, requestDigest); + } + + /** Reads one exact immutable result by its stable creation request identity. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByRequest( + String targetNamespace, UUID requestId) { + requireReadSelector(targetNamespace, requestId); + requireCommittedRead(); + Record record = findByRequest(targetNamespace, requestId); + return record == null ? Optional.empty() : Optional.of(toSnapshot(record)); + } + + /** Reads one exact canonical realm catalog row by its full owner identity. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByRealm( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + requireReadSelector(targetNamespace, canonicalTenantId); + requireNonNil(realmId, "realmId"); + requireCommittedRead(); + Record record = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(REALM_ID.eq(realmId))) + .fetchOne(); + return record == null ? Optional.empty() : Optional.of(toSnapshot(record)); + } + + /** + * Locks and fully verifies one exact initial public-production catalog row in the caller's owner + * transaction. The returned snapshot is produced by the same validation used for committed + * catalog reads; callers must compare it with their committed preflight snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalRealmCatalogSnapshot lockExactInitialPublicProduction( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID creationRequestId, + long catalogRevision) { + requireWritableOwnerTransaction(); + requireReadSelector(targetNamespace, canonicalTenantId); + requireNonNil(realmId, "realmId"); + requireNonNil(creationRequestId, "creationRequestId"); + if (catalogRevision != INITIAL_CATALOG_REVISION) { + throw new CatalogConflictException( + "Initial public-production catalog revision must be exactly one"); + } + Record record = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(REALM_ID.eq(realmId)) + .and(CREATION_REQUEST_ID.eq(creationRequestId)) + .and(CATALOG_REVISION.eq(catalogRevision))) + .forUpdate() + .fetchOne(); + if (record == null) { + throw new InvalidCatalogEvidenceException( + "Exact initial public-production catalog row is missing from Game Session owner storage"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(record); + if (!snapshot.visible() + || !snapshot.publicProduction() + || snapshot.catalogRevision() != INITIAL_CATALOG_REVISION + || !snapshot.targetNamespace().equals(targetNamespace) + || !snapshot.tenantId().equals(canonicalTenantId) + || !snapshot.realmId().equals(realmId) + || !snapshot.creationRequestId().equals(creationRequestId)) { + throw new InvalidCatalogEvidenceException( + "Locked catalog row is not the exact initial public-production authority"); + } + return snapshot; + } + + /** Locks one exact catalog target by its canonical identity in the caller's owner transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalRealmCatalogSnapshot lockInitialAdmissionTarget( + String targetNamespace, UUID canonicalTenantId, UUID realmId, long catalogRevision) { + requireWritableOwnerTransaction(); + requireReadSelector(targetNamespace, canonicalTenantId); + requireNonNil(realmId, "realmId"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + Record record = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(REALM_ID.eq(realmId)) + .and(CATALOG_REVISION.eq(catalogRevision))) + .forUpdate() + .fetchOne(); + if (record == null) { + throw new InvalidCatalogEvidenceException( + "Exact canonical initial-admission catalog row is missing or stale"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(record); + if (!snapshot.visible() + || !snapshot.publicProduction() + || !snapshot.targetNamespace().equals(targetNamespace) + || !snapshot.tenantId().equals(canonicalTenantId) + || !snapshot.realmId().equals(realmId) + || snapshot.catalogRevision() != catalogRevision) { + throw new InvalidCatalogEvidenceException( + "Locked catalog row is not the exact visible public-production realm target"); + } + return snapshot; + } + + /** + * Returns the unique visible public-production catalog snapshot, or no authority when absent. + * Multiple or internally conflicting results fail closed rather than selecting by order. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readUniqueVisiblePublicProduction( + String targetNamespace, UUID canonicalTenantId) { + requireReadSelector(targetNamespace, canonicalTenantId); + requireCommittedRead(); + var rows = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(PUBLIC_PRODUCTION.isTrue())) + .orderBy(CREATION_REQUEST_ID.asc()) + .limit(2) + .fetch(); + if (rows.isEmpty()) { + return Optional.empty(); + } + if (rows.size() != 1) { + throw new CatalogConflictException( + "Public-production catalog authority is ambiguous for this canonical tenant"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(rows.getFirst()); + if (!snapshot.visible() || !snapshot.publicProduction()) { + throw new InvalidCatalogEvidenceException( + "Public-production catalog readback is not visible player-addressable authority"); + } + return Optional.of(snapshot); + } + + /** + * Reads every persisted public-production catalog candidate for player discovery. The caller + * composes each row with the current canonical OPEN pointer and its exact terminal proof; this + * method is only the catalog half of that read and never manufactures routing authority. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public List readVisiblePublicProductionSnapshots( + String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireCommittedRead(); + return dsl.selectFrom(CATALOG) + .where(TARGET_NAMESPACE.eq(targetNamespace).and(PUBLIC_PRODUCTION.isTrue())) + .orderBy(CANONICAL_TENANT_ID.asc(), REALM_ID.asc()) + .fetch() + .map(this::toSnapshot); + } + + private IntakeReceipt lockAndReadFreshSource(CreateCanonicalRealmCatalogRequest request) { + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? FOR UPDATE", + request.targetNamespace(), + request.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException( + "Canonical tenant source binding is missing from Game Session owner storage"); + } + + // Lock order is stable: tenant source-binding row, then exact authored-world intake row, + // followed by the shared-namespace family serialization lock in createInitialPublicProduction. + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ? FOR UPDATE", + request.targetNamespace(), + request.sourceIntakeOperationId()); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Exact committed authored-world source intake is missing"); + } + IntakeReceipt receipt = toIntakeReceipt(intake); + requireTenantBindingMatches(binding, receipt.source()); + requireRequestMatchesSource(request, receipt); + requireFreshSource(receipt.source()); + return receipt; + } + + private void requireRequestMatchesSource( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt receipt) { + if (!request.targetNamespace().equals(receipt.source().targetNamespace()) + || !request.canonicalTenantId().equals(receipt.source().canonicalTenantId()) + || !request.sourceIntakeOperationId().equals(receipt.operationId())) { + throw new InvalidCatalogEvidenceException( + "Authored-world source intake does not match the exact requested tenant scope"); + } + } + + private UUID getOrCreateSharedNamespace(String targetNamespace, IntakeReceipt sourceReceipt) { + UUID tenantId = sourceReceipt.source().canonicalTenantId(); + Record current = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ? FOR UPDATE", + tenantId); + if (current != null) { + UUID currentId = required(current, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + validateSharedNamespaceSource(current); + if (!targetNamespace.equals(required(current, TARGET_NAMESPACE, "shared namespace target"))) { + throw new CatalogConflictException( + "Canonical tenant shared namespace belongs to a different Game Session namespace"); + } + if (current.get(LEGACY_TENANT_ID) != null) { + throw new InvalidCatalogEvidenceException( + "Canonical shared namespace conflicts with an existing numeric namespace row"); + } + return currentId; + } + + UUID namespaceId = UUID.randomUUID(); + requireNonNil(namespaceId, "allocated shared namespace"); + AuthoredWorldSourceEvidence source = sourceReceipt.source(); + int inserted = + dsl.insertInto(SHARED_NAMESPACES) + .set(LEGACY_TENANT_ID, (Long) null) + .set(SHARED_NAMESPACE_ID, namespaceId) + .set(CANONICAL_TENANT_ID, tenantId) + .set(TARGET_NAMESPACE, targetNamespace) + .set(SOURCE_INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(SOURCE_INTAKE_SCHEMA_VERSION, SCHEMA_VERSION) + .set(SOURCE_INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, sourceReceipt.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(SOURCE_SCHEMA_VERSION, source.schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, source.registrationRequestId()) + .set(SOURCE_OPERATION_ID, source.operationId()) + .set(SOURCE_REQUEST_DIGEST, source.requestDigest()) + .set(SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, source.provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, source.evidenceDigest()) + .onConflictDoNothing() + .execute(); + if (inserted == 0) { + Record raced = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ? FOR UPDATE", + tenantId); + if (raced != null) { + validateSharedNamespaceSource(raced); + if (raced.get(LEGACY_TENANT_ID) == null + && targetNamespace.equals( + required(raced, TARGET_NAMESPACE, "shared namespace target"))) { + return required(raced, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + } + } + throw new CatalogConflictException("Canonical shared namespace allocation conflicts"); + } + Record persisted = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenantId); + if (persisted == null) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace allocation did not read back from Game Session storage"); + } + validateSharedNamespaceSource(persisted); + return required(persisted, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + } + + private UUID allocateIsolatedNamespace() { + UUID namespaceId = UUID.randomUUID(); + requireNonNil(namespaceId, "allocated isolated namespace"); + if (dsl.fetchOne( + "SELECT playable_state_namespace_id " + + "FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE playable_state_namespace_id = ?", + namespaceId) + != null) { + throw new CatalogConflictException( + "Allocated isolated namespace collides with shared identity"); + } + return namespaceId; + } + + private void validateSharedNamespaceSource(Record namespace) { + UUID tenantId = required(namespace, CANONICAL_TENANT_ID, "canonical shared tenant id"); + String targetNamespace = required(namespace, TARGET_NAMESPACE, "shared namespace target"); + UUID intakeOperation = + required(namespace, SOURCE_INTAKE_OPERATION_ID, "shared namespace source operation"); + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + targetNamespace, + intakeOperation); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace source intake readback is missing"); + } + IntakeReceipt receipt = toIntakeReceipt(intake); + AuthoredWorldSourceEvidence source = receipt.source(); + if (!tenantId.equals(source.canonicalTenantId()) + || !targetNamespace.equals(source.targetNamespace()) + || !receipt + .intakeRequestId() + .equals( + required(namespace, SOURCE_INTAKE_REQUEST_ID, "shared namespace intake request")) + || !receipt + .requestDigest() + .equals( + required(namespace, SOURCE_INTAKE_REQUEST_DIGEST, "shared namespace intake digest")) + || !receipt + .receiptDigest() + .equals( + required( + namespace, SOURCE_INTAKE_RECEIPT_DIGEST, "shared namespace receipt digest")) + || !source + .registrationRequestId() + .equals( + required( + namespace, SOURCE_REGISTRATION_REQUEST_ID, "shared namespace registration")) + || !source + .operationId() + .equals(required(namespace, SOURCE_OPERATION_ID, "shared namespace source operation")) + || !source + .requestDigest() + .equals( + required( + namespace, SOURCE_REQUEST_DIGEST, "shared namespace source request digest")) + || !Long.valueOf(source.sourceGameRowId()) + .equals(required(namespace, SOURCE_GAME_ROW_ID, "shared namespace source row")) + || !source + .sourceGameTenantKey() + .equals( + required(namespace, SOURCE_GAME_TENANT_KEY, "shared namespace source tenant key")) + || !source + .provenanceKind() + .equals(required(namespace, SOURCE_PROVENANCE_KIND, "shared namespace provenance")) + || !source + .evidenceDigest() + .equals( + required(namespace, SOURCE_EVIDENCE_DIGEST, "shared namespace evidence digest"))) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace differs from its immutable authored-world source receipt"); + } + requireFreshSource(source); + requireNoRetainedTenantAssociation(targetNamespace, tenantId); + } + + private CanonicalRealmCatalogSnapshot requireExactRetry( + Record existing, + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt sourceReceipt, + String expectedRequestDigest) { + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(existing); + if (!request.requestId().equals(snapshot.creationRequestId()) + || !expectedRequestDigest.equals(snapshot.requestDigest()) + || !sourceReceipt.equals(snapshot.sourceIntakeReceipt())) { + throw new CatalogConflictException( + "Canonical realm creation request identity was reused with changed input or source evidence"); + } + return snapshot; + } + + private CanonicalRealmCatalogSnapshot toSnapshot(Record record) { + try { + IntakeReceipt sourceReceipt = toCatalogSourceReceipt(record); + UUID requestId = required(record, CREATION_REQUEST_ID, "catalog request id"); + String targetNamespace = required(record, TARGET_NAMESPACE, "catalog target namespace"); + UUID canonicalTenantId = required(record, CANONICAL_TENANT_ID, "catalog tenant id"); + UUID sourceIntakeOperationId = + required(record, SOURCE_INTAKE_OPERATION_ID, "catalog source intake operation"); + String realmSlug = required(record, REALM_SLUG, "catalog realm slug"); + String realmDisplayName = required(record, REALM_DISPLAY_NAME, "catalog realm display name"); + boolean visible = Boolean.TRUE.equals(record.get(VISIBLE)); + boolean publicProduction = Boolean.TRUE.equals(record.get(PUBLIC_PRODUCTION)); + String stateScope = required(record, STATE_SCOPE, "catalog state scope"); + String characterCreationPolicy = + required(record, CHARACTER_CREATION_POLICY, "catalog character-creation policy"); + String expectedRequestDigest = + requestDigest( + requestId, + targetNamespace, + canonicalTenantId, + sourceIntakeOperationId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + characterCreationPolicy, + sourceReceipt); + String persistedRequestDigest = required(record, REQUEST_DIGEST, "catalog request digest"); + UUID realmId = required(record, REALM_ID, "catalog realm id"); + UUID namespaceId = + required(record, PLAYABLE_STATE_NAMESPACE_ID, "catalog playable-state namespace"); + long revision = required(record, CATALOG_REVISION, "catalog revision"); + String expectedReceiptDigest = + receiptDigest( + targetNamespace, + canonicalTenantId, + requestId, + sourceReceipt, + realmId, + namespaceId, + revision, + persistedRequestDigest); + if (!expectedRequestDigest.equals(persistedRequestDigest) + || !expectedReceiptDigest.equals( + required(record, RECEIPT_DIGEST, "catalog receipt digest"))) { + throw new InvalidCatalogEvidenceException( + "Persisted canonical realm catalog request or receipt digest does not match its contents"); + } + + verifyPersistedSourceReceipt(sourceReceipt); + verifyNamespaceSelection( + targetNamespace, canonicalTenantId, stateScope, realmId, namespaceId); + return new CanonicalRealmCatalogSnapshot( + targetNamespace, + canonicalTenantId, + required(record, TENANT_SLUG, "catalog tenant slug"), + required(record, WORLD_SLUG, "catalog world slug"), + realmId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + namespaceId, + characterCreationPolicy, + revision, + requestId, + persistedRequestDigest, + required(record, RECEIPT_DIGEST, "catalog receipt digest"), + sourceReceipt); + } catch (InvalidCatalogEvidenceException | CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCatalogEvidenceException( + "Persisted canonical realm catalog evidence is invalid", exception); + } + } + + private void verifyNamespaceSelection( + String targetNamespace, + UUID canonicalTenantId, + String stateScope, + UUID realmId, + UUID namespaceId) { + if ("SHARED".equals(stateScope)) { + Record shared = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + canonicalTenantId); + if (shared == null + || shared.get(LEGACY_TENANT_ID) != null + || !namespaceId.equals(required(shared, SHARED_NAMESPACE_ID, "shared namespace id"))) { + throw new InvalidCatalogEvidenceException( + "SHARED realm catalog does not resolve to its canonical tenant namespace row"); + } + validateSharedNamespaceSource(shared); + } else { + if (dsl.fetchOne( + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE playable_state_namespace_id = ?", + namespaceId) + != null) { + throw new InvalidCatalogEvidenceException( + "ISOLATED realm namespace conflicts with the canonical tenant SHARED namespace"); + } + List sameNamespace = + dsl.select(REALM_ID) + .from(CATALOG) + .where(PLAYABLE_STATE_NAMESPACE_ID.eq(namespaceId).and(STATE_SCOPE.eq("ISOLATED"))) + .limit(2) + .fetch(); + if (sameNamespace.size() > 1 + || (sameNamespace.size() == 1 + && !realmId.equals(sameNamespace.getFirst().get(REALM_ID)))) { + throw new InvalidCatalogEvidenceException( + "ISOLATED playable-state namespace is already owned by another realm"); + } + } + requireNoRetainedTenantAssociation(targetNamespace, canonicalTenantId); + } + + private void verifyPersistedSourceReceipt(IntakeReceipt expected) { + AuthoredWorldSourceEvidence source = expected.source(); + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + source.targetNamespace(), + source.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException("Persisted tenant source binding is missing"); + } + requireTenantBindingMatches(binding, source); + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + source.targetNamespace(), + expected.operationId()); + if (intake == null || !expected.equals(toIntakeReceipt(intake))) { + throw new InvalidCatalogEvidenceException( + "Canonical realm catalog does not match exact immutable source-intake readback"); + } + requireFreshSource(source); + } + + private IntakeReceipt toCatalogSourceReceipt(Record record) { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required(record, SOURCE_SCHEMA_VERSION, "source schema version"), + required(record, TARGET_NAMESPACE, "source target namespace"), + required(record, SOURCE_REGISTRATION_REQUEST_ID, "source registration request"), + required(record, SOURCE_OPERATION_ID, "source operation"), + required(record, SOURCE_REQUEST_DIGEST, "source request digest"), + required(record, CANONICAL_TENANT_ID, "source canonical tenant"), + required(record, TENANT_SLUG, "source tenant slug"), + required(record, WORLD_SLUG, "source world slug"), + required(record, SOURCE_WORLD_DISPLAY_NAME, "source world display name"), + required(record, SOURCE_GAME_ROW_ID, "source game row"), + required(record, SOURCE_GAME_TENANT_KEY, "source game tenant key"), + required(record, SOURCE_PROVENANCE_KIND, "source provenance"), + required(record, SOURCE_EVIDENCE_DIGEST, "source evidence digest")); + if (!Integer.valueOf(SCHEMA_VERSION) + .equals(required(record, SOURCE_INTAKE_SCHEMA_VERSION, "source intake schema version"))) { + throw new InvalidCatalogEvidenceException( + "Unsupported persisted source-intake schema version"); + } + return new IntakeReceipt( + required(record, SOURCE_INTAKE_OPERATION_ID, "source intake operation"), + required(record, SOURCE_INTAKE_REQUEST_ID, "source intake request"), + required(record, SOURCE_INTAKE_REQUEST_DIGEST, "source intake request digest"), + source, + required(record, SOURCE_INTAKE_RECEIPT_DIGEST, "source intake receipt digest")); + } + + private IntakeReceipt toIntakeReceipt(Record record) { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required( + record, + DSL.field(DSL.name("source_schema_version"), Integer.class), + "source schema"), + required(record, TARGET_NAMESPACE, "source target namespace"), + required(record, SOURCE_REGISTRATION_REQUEST_ID, "source registration request"), + required(record, SOURCE_OPERATION_ID, "source operation"), + required(record, SOURCE_REQUEST_DIGEST, "source request digest"), + required(record, CANONICAL_TENANT_ID, "source canonical tenant"), + required(record, TENANT_SLUG, "source tenant slug"), + required(record, WORLD_SLUG, "source world slug"), + required( + record, + DSL.field(DSL.name("world_display_name"), String.class), + "source world display name"), + required(record, SOURCE_GAME_ROW_ID, "source game row"), + required(record, SOURCE_GAME_TENANT_KEY, "source game tenant key"), + required( + record, + DSL.field(DSL.name("source_provenance_kind"), String.class), + "source provenance"), + required(record, SOURCE_EVIDENCE_DIGEST, "source evidence digest")); + Integer intakeSchema = + required(record, DSL.field(DSL.name("schema_version"), Integer.class), "intake schema"); + if (!Integer.valueOf(SCHEMA_VERSION).equals(intakeSchema)) { + throw new InvalidCatalogEvidenceException( + "Unsupported persisted source-intake schema version"); + } + return new IntakeReceipt( + required(record, DSL.field(DSL.name("operation_id"), UUID.class), "intake operation"), + required(record, DSL.field(DSL.name("intake_request_id"), UUID.class), "intake request"), + required( + record, DSL.field(DSL.name("request_digest"), String.class), "intake request digest"), + source, + required( + record, DSL.field(DSL.name("receipt_digest"), String.class), "intake receipt digest")); + } + + private void requireTenantBindingMatches(Record binding, AuthoredWorldSourceEvidence source) { + if (!source + .targetNamespace() + .equals(required(binding, TARGET_NAMESPACE, "tenant binding namespace")) + || !source + .canonicalTenantId() + .equals(required(binding, CANONICAL_TENANT_ID, "tenant binding canonical id")) + || !source.tenantSlug().equals(required(binding, TENANT_SLUG, "tenant binding slug")) + || !Long.valueOf(source.sourceGameRowId()) + .equals(required(binding, SOURCE_GAME_ROW_ID, "tenant binding source row")) + || !source + .sourceGameTenantKey() + .equals(required(binding, SOURCE_GAME_TENANT_KEY, "tenant binding source key")) + || !source + .provenanceKind() + .equals(required(binding, BINDING_PROVENANCE_KIND, "tenant binding provenance"))) { + throw new InvalidCatalogEvidenceException( + "Authored-world receipt conflicts with the immutable canonical tenant source binding"); + } + } + + private void requireFreshSource(AuthoredWorldSourceEvidence source) { + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidCatalogEvidenceException( + "Initial canonical catalog creation requires fresh Game Design tenant source provenance"); + } + } + + private void requireNoRetainedTenantAssociation(String targetNamespace, UUID canonicalTenantId) { + if (dsl.fetchOne( + "SELECT operation_id FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + targetNamespace, + canonicalTenantId) + != null) { + throw new CatalogConflictException( + "Canonical tenant already has retained numeric Game Session identity evidence"); + } + } + + private Record findByRequest(String targetNamespace, UUID requestId) { + return dsl.selectFrom(CATALOG) + .where(TARGET_NAMESPACE.eq(targetNamespace).and(CREATION_REQUEST_ID.eq(requestId))) + .fetchOne(); + } + + private Record findPublicForTenant(String targetNamespace, UUID tenantId) { + return dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(tenantId)) + .and(PUBLIC_PRODUCTION.isTrue())) + .fetchOne(); + } + + private Record findByRealmSlug(String targetNamespace, UUID tenantId, String realmSlug) { + return dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(tenantId)) + .and(REALM_SLUG.eq(realmSlug))) + .fetchOne(); + } + + static String requestDigest( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt sourceReceipt) { + return requestDigest( + request.requestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.sourceIntakeOperationId(), + request.realmSlug(), + request.realmDisplayName(), + request.visible(), + request.publicProduction(), + request.stateScope(), + request.characterCreationPolicy(), + sourceReceipt); + } + + private static String requestDigest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String characterCreationPolicy, + IntakeReceipt sourceReceipt) { + AuthoredWorldSourceEvidence source = sourceReceipt.source(); + return digest( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + requestId.toString(), + targetNamespace, + canonicalTenantId.toString(), + sourceIntakeOperationId.toString(), + sourceReceipt.intakeRequestId().toString(), + sourceReceipt.requestDigest(), + sourceReceipt.receiptDigest(), + Integer.toString(source.schemaVersion()), + source.registrationRequestId().toString(), + source.operationId().toString(), + source.requestDigest(), + source.canonicalTenantId().toString(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + Long.toString(source.sourceGameRowId()), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + realmSlug, + realmDisplayName, + Boolean.toString(visible), + Boolean.toString(publicProduction), + stateScope, + characterCreationPolicy, + "ABSENT", + "ABSENT"); + } + + private static String receiptDigest( + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt sourceReceipt, + UUID realmId, + UUID namespaceId, + long revision, + String requestDigest) { + return receiptDigest( + request.targetNamespace(), + request.canonicalTenantId(), + request.requestId(), + sourceReceipt, + realmId, + namespaceId, + revision, + requestDigest); + } + + private static String receiptDigest( + String targetNamespace, + UUID canonicalTenantId, + UUID requestId, + IntakeReceipt sourceReceipt, + UUID realmId, + UUID namespaceId, + long revision, + String requestDigest) { + return digest( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + targetNamespace, + canonicalTenantId.toString(), + requestId.toString(), + requestDigest, + realmId.toString(), + namespaceId.toString(), + Long.toString(revision), + sourceReceipt.operationId().toString(), + sourceReceipt.receiptDigest()); + } + + private static String digest(String... values) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String value : values) { + byte[] bytes = strictUtf8(value); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must be well-formed UTF-8 text", exception); + } + } + + private void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical realm catalog creation requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical realm catalog creation requires a read-write transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical realm catalog DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical realm catalog creation requires READ COMMITTED isolation"); + } + return null; + }); + Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); + if (isolationRow == null + || !"read committed".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical realm catalog creation requires READ COMMITTED isolation"); + } + Record readOnlyRow = dsl.fetchOne("SHOW transaction_read_only"); + if (readOnlyRow == null || !"off".equalsIgnoreCase(readOnlyRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical realm catalog creation requires a read-write transaction"); + } + } + + private void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical realm catalog read requires a committed-outcome owner read"); + } + } + + private static void requireReadSelector(String targetNamespace, UUID identity) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(identity, "identity"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static T required(Record record, Field field, String label) { + T value = record.get(field); + if (value == null) { + throw new InvalidCatalogEvidenceException("Persisted " + label + " is missing"); + } + return value; + } + + /** Opaque source preflight result; callers cannot manufacture a committed owner receipt. */ + public static final class PreparedInitialPublicProduction { + private final CreateCanonicalRealmCatalogRequest request; + private final IntakeReceipt committedSource; + + private PreparedInitialPublicProduction( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt committedSource) { + this.request = Objects.requireNonNull(request, "request"); + this.committedSource = Objects.requireNonNull(committedSource, "committedSource"); + } + + private CreateCanonicalRealmCatalogRequest request() { + return request; + } + + private IntakeReceipt committedSource() { + return committedSource; + } + } + + public static final class CatalogConflictException extends IllegalStateException { + public CatalogConflictException(String message) { + super(message); + } + } + + public static final class InvalidCatalogEvidenceException extends IllegalStateException { + public InvalidCatalogEvidenceException(String message) { + super(message); + } + + public InvalidCatalogEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.java new file mode 100644 index 0000000000..ca861044ad --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.java @@ -0,0 +1,468 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, non-activating Game Session owner primitive for a fresh canonical STARTING row. + * + *

This repository is deliberately not a Spring component and is not an Account grant or + * redemption adapter. Its caller must already have independently redeemed the exact Account + * authorization and supply the resulting canonical owner UUID and immutable operator request + * identity/digest. This class has no World lifecycle, pointer, or runtime-projection dependency. + */ +public final class GameSessionCanonicalStartingInstanceRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final String STARTING = "STARTING"; + private static final String LAUNCH_ASSOCIATION_TABLE = "game_session_canonical_instance_launch"; + + private final DSLContext dsl; + private final String workloadNamespace; + private final CanonicalGameInstanceLaunchAssociationRepository launchAssociationRepository; + + public GameSessionCanonicalStartingInstanceRepository(DSLContext dsl, String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.launchAssociationRepository = + new CanonicalGameInstanceLaunchAssociationRepository(dsl, workloadNamespace); + } + + /** + * Creates or exactly replays one fresh owner row and its complete launch association. + * + *

The insert and association capture must run in one writable READ COMMITTED transaction. The + * descriptor's candidate script patch and runtime flags remain preserved in the complete binding; + * the owner row remains semantically UNPINNED until Game Session's pin owner commits an exact pin + * tuple. No numeric Game Design source ID or Account database row is used as identity. + */ + public StartingInstance createStarting( + FreshGameSessionTenantAssociation tenantAssociation, + CompleteLaunchBindingEvidence launchBinding, + UUID canonicalOwnerAccountUuid, + String controlPlaneRequestId, + String canonicalRequestDigest) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(tenantAssociation, "tenantAssociation"); + Objects.requireNonNull(launchBinding, "launchBinding"); + requireNonNil(canonicalOwnerAccountUuid, "canonicalOwnerAccountUuid"); + requireRequestId(controlPlaneRequestId); + requireRequestDigest(canonicalRequestDigest); + + var descriptor = launchBinding.descriptor(); + descriptor.requireValid(); + launchBinding.releaseAttestation().requireValid(descriptor); + if (!workloadNamespace.equals(descriptor.targetNamespace()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId())) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Operator request identity or workload namespace differs from the complete launch binding"); + } + requireFreshTenantTuple(tenantAssociation, descriptor); + + // This is the same serialization key used by association capture, before any owner lookup. + launchAssociationRepository.lockRequestForStartingGameInstance(controlPlaneRequestId); + requireExactPersistedSource(tenantAssociation.sourceEvidence(), launchBinding); + + Record existingAssociation = findLaunchAssociationForRequest(controlPlaneRequestId); + if (existingAssociation != null) { + long storedTenantId = requiredLong(existingAssociation, "game_session_tenant_id"); + long storedInstanceId = requiredLong(existingAssociation, "game_instance_id"); + UUID storedInstanceUuid = requiredUuid(existingAssociation, "game_instance_uuid"); + if (storedTenantId != tenantAssociation.legacyGameSessionTenantId()) { + throw new CanonicalStartingInstanceConflictException( + "Control-plane request is already bound to another Game Session tenant"); + } + Record existingRuntime = lockRuntime(storedTenantId, storedInstanceId); + requireRequestOwnerAndRuntime( + existingRuntime, + tenantAssociation, + launchBinding, + canonicalOwnerAccountUuid, + controlPlaneRequestId, + canonicalRequestDigest, + storedInstanceUuid); + + CanonicalGameInstanceLaunchAssociation association = + launchAssociationRepository.capture(tenantAssociation, storedInstanceId, launchBinding); + requireAssociationMatches(association, storedTenantId, storedInstanceUuid); + return new StartingInstance(storedInstanceId, storedInstanceUuid, association); + } + + Record orphan = + dsl.fetchOne( + "SELECT id FROM game_instances " + + "WHERE tenant_id = ? AND run_owned_start_request_id = ? FOR UPDATE", + tenantAssociation.legacyGameSessionTenantId(), + controlPlaneRequestId); + if (orphan != null) { + throw new CanonicalStartingInstanceConflictException( + "A Game Session request row exists without its canonical launch association"); + } + + UUID gameInstanceUuid = UUID.randomUUID(); + requireNonNil(gameInstanceUuid, "allocated gameInstanceUuid"); + long gameInstanceId = + insertStartingRuntime( + tenantAssociation.legacyGameSessionTenantId(), + launchBinding, + canonicalOwnerAccountUuid, + controlPlaneRequestId, + canonicalRequestDigest, + gameInstanceUuid); + + // V26's initially deferred owner trigger requires this association before transaction commit. + CanonicalGameInstanceLaunchAssociation association = + launchAssociationRepository.capture(tenantAssociation, gameInstanceId, launchBinding); + Record persistedRuntime = + lockRuntime(tenantAssociation.legacyGameSessionTenantId(), gameInstanceId); + requireRequestOwnerAndRuntime( + persistedRuntime, + tenantAssociation, + launchBinding, + canonicalOwnerAccountUuid, + controlPlaneRequestId, + canonicalRequestDigest, + gameInstanceUuid); + if (!STARTING.equals(requiredText(persistedRuntime, "status")) + || requiredLong(persistedRuntime, "row_version") != 0L) { + throw new IllegalStateException( + "New canonical Game Session owner row did not remain at its initial STARTING fence"); + } + requireAssociationMatches( + association, tenantAssociation.legacyGameSessionTenantId(), gameInstanceUuid); + return new StartingInstance(gameInstanceId, gameInstanceUuid, association); + } + + private long insertStartingRuntime( + long privateGameSessionTenantId, + CompleteLaunchBindingEvidence launchBinding, + UUID canonicalOwnerAccountUuid, + String controlPlaneRequestId, + String canonicalRequestDigest, + UUID gameInstanceUuid) { + var descriptor = launchBinding.descriptor(); + requireColumnText(descriptor.launchDescriptorId(), 64, "launchDescriptorId"); + if (descriptor.remapSetIdPresent()) { + requireColumnText(descriptor.remapSetId(), 64, "remapSetId"); + } + + // The canonical typed binding, including runtimeFlagsJson and candidate script data, is + // persisted by capture below. Mutable feature_flag rows are not instance launch evidence. + // A candidate patch is not an admitted pin; all current pin fields therefore start absent. + Record row = + dsl.fetchOne( + "INSERT INTO game_instances " + + "(tenant_id, runtime_version, script_patch_version, " + + "script_patch_base_version_id, owner_account_id, owner_account_uuid, status, " + + "row_version, game_template_id, launch_descriptor_id, version_id, " + + "release_bundle_id, version_state_epoch, generation_config_revision, remap_set_id, " + + "script_patch_pinned_at, script_patch_pinned_by, script_patch_pinned_reason, " + + "script_patch_pinned_control_plane_request_id, script_pin_epoch, " + + "run_owned_start_request_id, run_owned_start_request_digest, " + + "run_owned_start_published_release_bundle_ref, run_owned_start_preparing_epoch, " + + "run_owned_start_active_epoch, game_instance_uuid) " + + "VALUES (?, ?, NULL, NULL, NULL, ?, 'STARTING', 0, ?, ?, ?, ?, ?, ?, ?, " + + "NULL, NULL, NULL, NULL, NULL, ?, ?, ?, NULL, NULL, ?) RETURNING id", + privateGameSessionTenantId, + Long.toString(descriptor.versionId()), + canonicalOwnerAccountUuid, + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.versionStateEpoch(), + descriptor.generationConfigRevision(), + descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null, + controlPlaneRequestId, + canonicalRequestDigest, + descriptor.publishedReleaseBundleRef(), + gameInstanceUuid); + if (row == null) { + throw new IllegalStateException( + "Game Session STARTING owner row insert returned no identity"); + } + return requiredLong(row, "id"); + } + + private Record findLaunchAssociationForRequest(String controlPlaneRequestId) { + return dsl.fetchOne( + "SELECT game_session_tenant_id, game_instance_id, game_instance_uuid FROM " + + LAUNCH_ASSOCIATION_TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ? FOR UPDATE", + workloadNamespace, + controlPlaneRequestId); + } + + private Record lockRuntime(long tenantId, long gameInstanceId) { + Record row = + dsl.fetchOne( + "SELECT id, tenant_id, game_instance_uuid, owner_account_id, owner_account_uuid, " + + "runtime_version, status, row_version, game_template_id, launch_descriptor_id, " + + "version_id, release_bundle_id, version_state_epoch, generation_config_revision, " + + "remap_set_id, run_owned_start_request_id, run_owned_start_request_digest, " + + "run_owned_start_published_release_bundle_ref " + + "FROM game_instances WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + gameInstanceId); + if (row == null) { + throw new CanonicalStartingInstanceConflictException( + "Canonical launch association refers to a missing Game Session owner row"); + } + return row; + } + + private void requireRequestOwnerAndRuntime( + Record row, + FreshGameSessionTenantAssociation tenantAssociation, + CompleteLaunchBindingEvidence launchBinding, + UUID canonicalOwnerAccountUuid, + String controlPlaneRequestId, + String canonicalRequestDigest, + UUID expectedGameInstanceUuid) { + var descriptor = launchBinding.descriptor(); + if (requiredLong(row, "tenant_id") != tenantAssociation.legacyGameSessionTenantId() + || !requiredUuid(row, "game_instance_uuid").equals(expectedGameInstanceUuid) + || !canonicalOwnerAccountUuid.equals(row.get("owner_account_uuid", UUID.class)) + || row.get("owner_account_id", Long.class) != null + || !controlPlaneRequestId.equals(requiredText(row, "run_owned_start_request_id")) + || !canonicalRequestDigest.equals(requiredText(row, "run_owned_start_request_digest")) + || !Long.toString(descriptor.versionId()).equals(requiredText(row, "runtime_version")) + || requiredLong(row, "game_template_id") != descriptor.gameTemplateId() + || !requiredText(row, "launch_descriptor_id").equals(descriptor.launchDescriptorId()) + || requiredLong(row, "version_id") != descriptor.versionId() + || requiredLong(row, "release_bundle_id") != descriptor.releaseBundleId() + || requiredLong(row, "version_state_epoch") != descriptor.versionStateEpoch() + || !requiredText(row, "generation_config_revision") + .equals(descriptor.generationConfigRevision()) + || !Objects.equals( + row.get("remap_set_id", String.class), + descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null) + || !requiredText(row, "run_owned_start_published_release_bundle_ref") + .equals(descriptor.publishedReleaseBundleRef())) { + throw new CanonicalStartingInstanceConflictException( + "Canonical launch retry changed owner, request digest, or exact descriptor tuple"); + } + } + + private void requireExactPersistedSource( + RuntimeTenantIdentityEvidence expected, CompleteLaunchBindingEvidence launchBinding) { + var descriptor = launchBinding.descriptor(); + Record row = + dsl.fetchOne( + "SELECT intake.source_schema_version AS schema_version, intake.target_namespace, " + + "intake.source_registration_request_id AS registration_request_id, " + + "intake.source_operation_id AS operation_id, " + + "intake.source_request_digest AS request_digest, " + + "intake.canonical_tenant_id, intake.tenant_slug, intake.world_slug, " + + "intake.world_display_name, intake.source_game_row_id, " + + "intake.source_game_tenant_key, " + + "intake.source_provenance_kind AS provenance_kind, " + + "intake.source_evidence_digest AS evidence_digest " + + "FROM game_session_authored_world_source_intake intake " + + "JOIN game_session_authored_world_tenant_source_binding binding " + + "ON binding.target_namespace = intake.target_namespace " + + "AND binding.canonical_tenant_id = intake.canonical_tenant_id " + + "AND binding.tenant_slug = intake.tenant_slug " + + "AND binding.source_game_row_id = intake.source_game_row_id " + + "AND binding.source_game_tenant_key = intake.source_game_tenant_key " + + "AND binding.provenance_kind = intake.source_provenance_kind " + + "WHERE intake.target_namespace = ? " + + "AND intake.source_registration_request_id = ? " + + "AND intake.source_operation_id = ? FOR KEY SHARE OF intake, binding", + workloadNamespace, + expected.requestId(), + descriptor.authoredWorldSourceOperationId()); + if (row == null) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Complete launch binding has no exact persisted authored-world source receipt"); + } + + AuthoredWorldSourceEvidence persisted; + try { + persisted = + new AuthoredWorldSourceEvidence( + requiredInt(row, "schema_version"), + requiredText(row, "target_namespace"), + requiredUuid(row, "registration_request_id"), + requiredUuid(row, "operation_id"), + requiredText(row, "request_digest"), + requiredUuid(row, "canonical_tenant_id"), + requiredText(row, "tenant_slug"), + requiredText(row, "world_slug"), + requiredText(row, "world_display_name"), + requiredLong(row, "source_game_row_id"), + requiredText(row, "source_game_tenant_key"), + requiredText(row, "provenance_kind"), + requiredText(row, "evidence_digest")); + } catch (RuntimeException malformed) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Persisted authored-world source evidence is malformed", malformed); + } + + if (!"NEW_GAME_ROW".equals(persisted.provenanceKind()) + || !expected.targetNamespace().equals(persisted.targetNamespace()) + || !expected.requestId().equals(persisted.registrationRequestId()) + || !expected.canonicalTenantId().equals(persisted.canonicalTenantId()) + || expected.sourceGameRowId() != persisted.sourceGameRowId() + || !expected.sourceGameTenantKey().equals(persisted.sourceGameTenantKey()) + || !expected.provenanceKind().equals(persisted.provenanceKind()) + || !descriptor.canonicalTenantId().equals(persisted.canonicalTenantId()) + || !descriptor.worldSlug().equals(persisted.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(persisted.operationId()) + || !descriptor.authoredWorldSourceEvidenceDigest().equals(persisted.evidenceDigest())) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Complete launch binding differs from its exact fresh authored-world source"); + } + } + + private static void requireFreshTenantTuple( + FreshGameSessionTenantAssociation tenantAssociation, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) { + RuntimeTenantIdentityEvidence source = tenantAssociation.sourceEvidence(); + if (source.schemaVersion() != 1 + || !"NEW_GAME_ROW".equals(source.provenanceKind()) + || !descriptor.canonicalTenantId().equals(source.canonicalTenantId()) + || !descriptor.targetNamespace().equals(source.targetNamespace())) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Fresh Game Session tenant association differs from the complete launch binding"); + } + } + + private static void requireAssociationMatches( + CanonicalGameInstanceLaunchAssociation association, + long expectedTenantId, + UUID expectedGameInstanceUuid) { + if (association.gameSessionTenantId() != expectedTenantId + || !association.gameInstanceUuid().equals(expectedGameInstanceUuid)) { + throw new CanonicalStartingInstanceConflictException( + "Canonical launch association readback differs from its Game Session owner row"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical STARTING instance creation requires a writable owner transaction"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equals(settings.get("transaction_isolation", String.class)) + || !"off".equals(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "Canonical STARTING instance creation requires writable READ COMMITTED isolation"); + } + } + + private static void requireColumnText(String value, int maximum, String label) { + if (value == null || value.isBlank() || value.length() > maximum) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + label + " does not fit the retained Game Session owner column"); + } + } + + private static void requireRequestId(String requestId) { + if (requestId == null || requestId.isBlank() || requestId.length() > 128) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "controlPlaneRequestId must contain 1 to 128 nonblank characters"); + } + } + + private static void requireRequestDigest(String requestDigest) { + if (requestDigest == null || !REQUEST_DIGEST.matcher(requestDigest).matches()) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "canonicalRequestDigest must be the exact lowercase SHA-256 value accepted by V10"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new InvalidCanonicalStartingInstanceEvidenceException(label + " must be non-nil"); + } + } + + private static String requiredText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner row is missing " + field); + } + return value; + } + + private static long requiredLong(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner row is missing " + field); + } + return value; + } + + private static int requiredInt(Record row, String field) { + Integer value = row.get(field, Integer.class); + if (value == null) { + throw new IllegalStateException("Persisted authored-world source is missing " + field); + } + return value; + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalStateException("Persisted Game Session owner row has invalid " + field); + } + return value; + } + + /** Original private numeric row, immutable canonical UUID, and the complete captured binding. */ + public record StartingInstance( + long gameInstanceId, + UUID gameInstanceUuid, + CanonicalGameInstanceLaunchAssociation launchAssociation) { + public StartingInstance { + if (gameInstanceId <= 0) { + throw new IllegalArgumentException("gameInstanceId must be positive"); + } + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + Objects.requireNonNull(launchAssociation, "launchAssociation"); + if (!gameInstanceUuid.equals(launchAssociation.gameInstanceUuid())) { + throw new IllegalArgumentException( + "Starting instance UUID differs from its launch association"); + } + } + } + + public static final class CanonicalStartingInstanceConflictException + extends IllegalStateException { + public CanonicalStartingInstanceConflictException(String message) { + super(message); + } + } + + public static final class InvalidCanonicalStartingInstanceEvidenceException + extends IllegalArgumentException { + public InvalidCanonicalStartingInstanceEvidenceException(String message) { + super(message); + } + + public InvalidCanonicalStartingInstanceEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java new file mode 100644 index 0000000000..5a63133283 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java @@ -0,0 +1,437 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Game Session's owner for immutable fresh canonical-tenant to private tenant-key association. + * + *

This producer consumes only a committed Game Session source-intake receipt. It does not create + * a runtime instance, admission pointer, grant, or external authority. + */ +public class GameSessionFreshTenantAssociationRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String FRESH_KIND = "FRESH_SOURCE_BOUND"; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Fail-fast validation is local; no resources or finalizer are acquired. The repository" + + " remains non-final for transaction proxying.") + public GameSessionFreshTenantAssociationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Persists the fresh source-bound tenant mapping or returns its exact durable replay. + * + *

The association operation ID is the caller's stable mutation identity. The expected receipt + * is re-read, digest-validated, and compared with its immutable tenant-source binding under this + * same writable READ COMMITTED transaction before any private tenant ID is allocated. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public FreshGameSessionTenantAssociation associateFresh( + UUID associationOperationId, String targetNamespace, IntakeReceipt expectedSourceReceipt) { + requireWritableReadCommittedOwnerTransaction(); + requireNonNil(associationOperationId, "associationOperationId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + Objects.requireNonNull(expectedSourceReceipt, "expectedSourceReceipt"); + if (!targetNamespace.equals(expectedSourceReceipt.source().targetNamespace())) { + throw new FreshTenantAssociationConflictException( + "Source receipt namespace differs from the requested association namespace"); + } + + lockAssociationOperation(associationOperationId); + IntakeReceipt persistedSource = + readPersistedSourceReceipt(targetNamespace, expectedSourceReceipt.operationId()); + if (!persistedSource.equals(expectedSourceReceipt)) { + throw new InvalidFreshTenantSourceException( + "Persisted authored-world source receipt differs from the requested exact receipt"); + } + RuntimeTenantIdentityEvidence runtimeSource = + requireFreshSource(targetNamespace, persistedSource.source()); + + Record existingAssociation = findAssociationByOperation(associationOperationId); + if (existingAssociation != null) { + return requireExactAssociation( + existingAssociation, associationOperationId, targetNamespace, runtimeSource); + } + + if (findClaimByOperation(associationOperationId) != null) { + throw new FreshTenantAssociationConflictException( + "Association operation ID is already owned by another tenant claim"); + } + if (findClaimByCanonicalTenant(targetNamespace, runtimeSource.canonicalTenantId()) != null) { + throw new FreshTenantAssociationConflictException( + "Canonical tenant already has a Game Session tenant association"); + } + if (findClaimByAssociationRequest( + targetNamespace, persistedSource.source().registrationRequestId()) + != null) { + throw new FreshTenantAssociationConflictException( + "Source registration request is already owned by another tenant association"); + } + + long privateTenantId = allocateFreshPrivateTenantId(); + insertCanonicalClaim( + targetNamespace, + runtimeSource.canonicalTenantId(), + privateTenantId, + associationOperationId, + persistedSource.source().registrationRequestId()); + insertFreshAssociation( + associationOperationId, targetNamespace, privateTenantId, persistedSource.source()); + + Record committedAssociation = findAssociationByOperation(associationOperationId); + if (committedAssociation == null) { + throw new IllegalStateException("Committed fresh tenant association is missing"); + } + return requireExactAssociation( + committedAssociation, associationOperationId, targetNamespace, runtimeSource); + } + + private void lockAssociationOperation(UUID associationOperationId) { + // Hash collisions only serialize unrelated operations; they cannot merge their owner records. + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(?)", associationOperationId.getMostSignificantBits()); + } + + private IntakeReceipt readPersistedSourceReceipt(String namespace, UUID intakeOperationId) { + Record row = + dsl.fetchOne( + "SELECT intake.operation_id AS operation_id, " + + "intake.schema_version AS schema_version, " + + "intake.target_namespace AS target_namespace, " + + "intake.intake_request_id AS intake_request_id, " + + "intake.request_digest AS request_digest, " + + "intake.source_schema_version AS source_schema_version, " + + "intake.source_registration_request_id AS source_registration_request_id, " + + "intake.source_operation_id AS source_operation_id, " + + "intake.source_request_digest AS source_request_digest, " + + "intake.canonical_tenant_id AS canonical_tenant_id, " + + "intake.tenant_slug AS tenant_slug, intake.world_slug AS world_slug, " + + "intake.world_display_name AS world_display_name, " + + "intake.source_game_row_id AS source_game_row_id, " + + "intake.source_game_tenant_key AS source_game_tenant_key, " + + "intake.source_provenance_kind AS source_provenance_kind, " + + "intake.source_evidence_digest AS source_evidence_digest, " + + "intake.receipt_digest AS receipt_digest, " + + "binding.target_namespace AS binding_target_namespace, " + + "binding.canonical_tenant_id AS binding_canonical_tenant_id, " + + "binding.tenant_slug AS binding_tenant_slug, " + + "binding.source_game_row_id AS binding_source_game_row_id, " + + "binding.source_game_tenant_key AS binding_source_game_tenant_key, " + + "binding.provenance_kind AS binding_provenance_kind " + + "FROM game_session_authored_world_source_intake intake " + + "JOIN game_session_authored_world_tenant_source_binding binding " + + "ON binding.target_namespace = intake.target_namespace " + + "AND binding.canonical_tenant_id = intake.canonical_tenant_id " + + "AND binding.tenant_slug = intake.tenant_slug " + + "AND binding.source_game_row_id = intake.source_game_row_id " + + "AND binding.source_game_tenant_key = intake.source_game_tenant_key " + + "AND binding.provenance_kind = intake.source_provenance_kind " + + "WHERE intake.target_namespace = ? AND intake.operation_id = ? " + + "FOR UPDATE OF intake, binding", + namespace, + intakeOperationId); + if (row == null) { + Record otherNamespace = + dsl.fetchOne( + "SELECT target_namespace FROM game_session_authored_world_source_intake " + + "WHERE operation_id = ?", + intakeOperationId); + if (otherNamespace != null) { + throw new FreshTenantAssociationConflictException( + "Source intake operation belongs to a different target namespace"); + } + throw new InvalidFreshTenantSourceException( + "Exact committed Game Session source intake receipt is missing"); + } + + String provenanceKind = required(row.get("source_provenance_kind", String.class)); + if (!"NEW_GAME_ROW".equals(provenanceKind)) { + throw new InvalidFreshTenantSourceException( + "Fresh tenant association requires NEW_GAME_ROW source provenance"); + } + if (!Integer.valueOf(1).equals(row.get("schema_version", Integer.class))) { + throw new InvalidFreshTenantSourceException( + "Unsupported Game Session source-intake receipt schema version"); + } + + try { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required(row.get("source_schema_version", Integer.class)), + required(row.get("target_namespace", String.class)), + required(row.get("source_registration_request_id", UUID.class)), + required(row.get("source_operation_id", UUID.class)), + required(row.get("source_request_digest", String.class)), + required(row.get("canonical_tenant_id", UUID.class)), + required(row.get("tenant_slug", String.class)), + required(row.get("world_slug", String.class)), + required(row.get("world_display_name", String.class)), + required(row.get("source_game_row_id", Long.class)), + required(row.get("source_game_tenant_key", String.class)), + provenanceKind, + required(row.get("source_evidence_digest", String.class))); + requireExactTenantSourceBinding(row, source); + return new IntakeReceipt( + required(row.get("operation_id", UUID.class)), + required(row.get("intake_request_id", UUID.class)), + required(row.get("request_digest", String.class)), + source, + required(row.get("receipt_digest", String.class))); + } catch (RuntimeException exception) { + if (exception instanceof InvalidFreshTenantSourceException) { + throw exception; + } + throw new InvalidFreshTenantSourceException( + "Persisted authored-world intake receipt failed exact evidence validation", exception); + } + } + + private void requireExactTenantSourceBinding(Record row, AuthoredWorldSourceEvidence source) { + if (!Objects.equals(row.get("binding_target_namespace", String.class), source.targetNamespace()) + || !Objects.equals( + row.get("binding_canonical_tenant_id", UUID.class), source.canonicalTenantId()) + || !Objects.equals(row.get("binding_tenant_slug", String.class), source.tenantSlug()) + || !Objects.equals( + row.get("binding_source_game_row_id", Long.class), source.sourceGameRowId()) + || !Objects.equals( + row.get("binding_source_game_tenant_key", String.class), source.sourceGameTenantKey()) + || !Objects.equals( + row.get("binding_provenance_kind", String.class), source.provenanceKind())) { + throw new InvalidFreshTenantSourceException( + "Authored-world source intake differs from its locked tenant-source binding"); + } + } + + private RuntimeTenantIdentityEvidence requireFreshSource( + String targetNamespace, AuthoredWorldSourceEvidence source) { + if (!targetNamespace.equals(source.targetNamespace())) { + throw new InvalidFreshTenantSourceException( + "Authored-world source namespace differs from the association namespace"); + } + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidFreshTenantSourceException( + "Fresh tenant association requires NEW_GAME_ROW source provenance"); + } + try { + return new RuntimeTenantIdentityEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + } catch (IllegalArgumentException exception) { + throw new InvalidFreshTenantSourceException( + "Authored-world source cannot establish a fresh runtime tenant identity", exception); + } + } + + private Record findAssociationByOperation(UUID associationOperationId) { + return dsl.fetchOne( + "SELECT * FROM game_session_fresh_tenant_association " + + "WHERE association_operation_id = ? FOR KEY SHARE", + associationOperationId); + } + + private Record findClaimByOperation(UUID associationOperationId) { + return dsl.fetchOne( + "SELECT * FROM game_session_tenant_canonical_claim " + + "WHERE association_operation_id = ? FOR KEY SHARE", + associationOperationId); + } + + private Record findClaimByCanonicalTenant(String namespace, UUID canonicalTenantId) { + return dsl.fetchOne( + "SELECT * FROM game_session_tenant_canonical_claim " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? FOR UPDATE", + namespace, + canonicalTenantId); + } + + private Record findClaimByAssociationRequest(String namespace, UUID associationRequestId) { + return dsl.fetchOne( + "SELECT * FROM game_session_tenant_canonical_claim " + + "WHERE target_namespace = ? AND association_request_id = ? FOR UPDATE", + namespace, + associationRequestId); + } + + private long allocateFreshPrivateTenantId() { + Record reservation = + dsl.fetchOne( + "INSERT INTO game_session_tenant_scope_reservation (reservation_kind) " + + "VALUES ('FRESH_SOURCE_BOUND') RETURNING game_session_tenant_id"); + if (reservation == null || reservation.get("game_session_tenant_id", Long.class) == null) { + throw new IllegalStateException("Game Session tenant ID reservation returned no identity"); + } + long privateTenantId = reservation.get("game_session_tenant_id", Long.class); + if (privateTenantId <= 0) { + throw new IllegalStateException("Game Session tenant ID reservation was not positive"); + } + return privateTenantId; + } + + private void insertCanonicalClaim( + String namespace, + UUID canonicalTenantId, + long privateTenantId, + UUID associationOperationId, + UUID associationRequestId) { + int inserted = + dsl.execute( + "INSERT INTO game_session_tenant_canonical_claim " + + "(target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, " + + "association_kind, reservation_kind, association_operation_id, " + + "association_request_id) " + + "VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", + namespace, + canonicalTenantId, + privateTenantId, + associationOperationId, + associationRequestId); + if (inserted != 1) { + throw new IllegalStateException("Game Session canonical tenant claim was not persisted"); + } + } + + private void insertFreshAssociation( + UUID associationOperationId, + String namespace, + long privateTenantId, + AuthoredWorldSourceEvidence source) { + int inserted = + dsl.execute( + "INSERT INTO game_session_fresh_tenant_association " + + "(association_operation_id, target_namespace, association_request_id, " + + "source_schema_version, source_target_namespace, source_request_id, " + + "source_canonical_tenant_id, canonical_tenant_id, " + + "legacy_game_session_tenant_id, source_game_row_id, source_game_tenant_key, " + + "provenance_kind, association_kind) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', " + + "'FRESH_SOURCE_BOUND')", + associationOperationId, + namespace, + source.registrationRequestId(), + source.schemaVersion(), + namespace, + source.registrationRequestId(), + source.canonicalTenantId(), + source.canonicalTenantId(), + privateTenantId, + source.sourceGameRowId(), + source.sourceGameTenantKey()); + if (inserted != 1) { + throw new IllegalStateException("Game Session fresh tenant association was not persisted"); + } + } + + private FreshGameSessionTenantAssociation requireExactAssociation( + Record association, + UUID expectedOperationId, + String expectedNamespace, + RuntimeTenantIdentityEvidence expectedSource) { + UUID associationOperationId = required(association.get("association_operation_id", UUID.class)); + long privateTenantId = required(association.get("legacy_game_session_tenant_id", Long.class)); + if (!expectedOperationId.equals(associationOperationId) + || !expectedNamespace.equals(association.get("target_namespace", String.class)) + || !expectedSource.requestId().equals(association.get("association_request_id", UUID.class)) + || !Integer.valueOf(expectedSource.schemaVersion()) + .equals(association.get("source_schema_version", Integer.class)) + || !expectedNamespace.equals(association.get("source_target_namespace", String.class)) + || !expectedSource.requestId().equals(association.get("source_request_id", UUID.class)) + || !expectedSource + .canonicalTenantId() + .equals(association.get("source_canonical_tenant_id", UUID.class)) + || !expectedSource + .canonicalTenantId() + .equals(association.get("canonical_tenant_id", UUID.class)) + || !Objects.equals( + expectedSource.sourceGameRowId(), association.get("source_game_row_id", Long.class)) + || !expectedSource + .sourceGameTenantKey() + .equals(association.get("source_game_tenant_key", String.class)) + || !expectedSource.provenanceKind().equals(association.get("provenance_kind", String.class)) + || !FRESH_KIND.equals(association.get("association_kind", String.class))) { + throw new FreshTenantAssociationConflictException( + "Association operation ID is already bound to different source or namespace evidence"); + } + return new FreshGameSessionTenantAssociation( + associationOperationId, privateTenantId, expectedSource); + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Fresh tenant association requires a writable owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Fresh tenant association requires writable READ COMMITTED isolation"); + } + return null; + }); + Record transaction = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + if (transaction == null + || !"read committed".equals(transaction.get("isolation", String.class)) + || !"off".equals(transaction.get("read_only", String.class))) { + throw new IllegalStateException( + "Fresh tenant association requires a writable READ COMMITTED owner transaction"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static T required(T value) { + return Objects.requireNonNull(value, "Persisted Game Session owner evidence is incomplete"); + } + + public static final class InvalidFreshTenantSourceException extends IllegalStateException { + public InvalidFreshTenantSourceException(String message) { + super(message); + } + + public InvalidFreshTenantSourceException(String message, Throwable cause) { + super(message, cause); + } + } + + public static final class FreshTenantAssociationConflictException extends IllegalStateException { + public FreshTenantAssociationConflictException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepository.java new file mode 100644 index 0000000000..914deec390 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepository.java @@ -0,0 +1,595 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec.Resolved; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Unregistered immutable descriptor outcome pin tied to the original StartSession association. It + * creates no instance, pointer, hold, admission, or activation authority. + */ +public final class GameSessionStartSessionLaunchDescriptorRepository { + // Local fail-closed storage budgets; these do not imply a gRPC transport message limit. + private static final int MAX_REQUEST_WIRE_BYTES = + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + 1024; + private static final int MAX_RESPONSE_WIRE_BYTES = 8 * 1024 * 1024; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String TABLE = "game_session_start_session_launch_descriptor_pin"; + + private final DSLContext dsl; + private final GameSessionStartSessionTemplateAssociationRepository associationRepository; + + public GameSessionStartSessionLaunchDescriptorRepository( + DSLContext dsl, GameSessionStartSessionTemplateAssociationRepository associationRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl is required"); + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository is required"); + } + + /** Reads only a descriptor outcome pinned to the exact currently valid original owner claim. */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public Optional findPinned( + GameSessionStartSessionOperatorAttemptRepository.AttemptClaim claim) { + Objects.requireNonNull(claim, "claim is required"); + Optional + association = associationRepository.findPinned(claim); + Record row = selectPin(claim.targetNamespace(), claim.controlPlaneRequestId(), true); + if (row == null) { + return Optional.empty(); + } + if (association.isEmpty()) { + throw new IllegalStateException( + "Persisted StartSession descriptor pin has no original association pin"); + } + return Optional.of( + decodeStored( + row, + claim.targetNamespace(), + claim.controlPlaneRequestId(), + claim.ownerAttemptId(), + claim.ownerFence(), + association.orElseThrow())); + } + + /** Reads a retained descriptor only after the opaque continuation revalidates its owner row. */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public Optional findPinned( + GameSessionStartSessionOperatorAttemptRepository.EvidenceContinuation continuation) { + Objects.requireNonNull(continuation, "evidence continuation is required"); + Optional + association = associationRepository.findPinned(continuation); + Record row = selectPin(continuation, true); + if (row == null) { + return Optional.empty(); + } + if (association.isEmpty()) { + throw new IllegalStateException( + "Persisted StartSession descriptor pin has no original association pin"); + } + return Optional.of( + decodeStored( + row, + continuation.targetNamespace(), + continuation.controlPlaneRequestId(), + continuation.ownerAttemptId(), + continuation.ownerFence(), + association.orElseThrow())); + } + + /** + * Pins one exact-replay descriptor outcome under the current original claim. The exact replay + * request is derived only from the already retained association; this method never selects. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public PinnedLaunchDescriptorSnapshot pin( + GameSessionStartSessionOperatorAttemptRepository.AttemptClaim claim, Resolved candidate) { + Objects.requireNonNull(claim, "claim is required"); + Objects.requireNonNull(candidate, "candidate is required"); + GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot association = + associationRepository + .findPinned(claim) + .orElseThrow( + () -> + new StartSessionLaunchDescriptorConflictException( + "An original template association pin is required before descriptor pinning")); + PreparedCandidate prepared = prepareCandidate(association, candidate); + Record existing = selectPin(claim.targetNamespace(), claim.controlPlaneRequestId(), true); + if (existing != null) { + PinnedLaunchDescriptorSnapshot retained = + decodeStored( + existing, + claim.targetNamespace(), + claim.controlPlaneRequestId(), + claim.ownerAttemptId(), + claim.ownerFence(), + association); + // The owner phase epoch is a fresh same-owner snapshot value, not part of the immutable + // selection. prepareCandidate already rejects every changed association/release/World field. + if (Arrays.equals(retained.requestWire(), prepared.requestWire()) + && (Arrays.equals(retained.responseWire(), prepared.responseWire()) + || candidate.outcome().equals(retained.resolved().outcome()))) { + return retained; + } + throw new StartSessionLaunchDescriptorConflictException( + "Descriptor outcome differs from the original immutable StartSession pin"); + } + + Record inserted = + dsl.fetchOne( + "INSERT INTO " + + TABLE + + " (target_namespace, control_plane_request_id, canonical_tenant_id, " + + "owner_attempt_id, owner_fence, association_request_digest, " + + "association_response_digest, descriptor_request_wire, descriptor_response_wire, " + + "descriptor_request_digest, descriptor_response_digest) " + + "SELECT attempt.target_namespace, attempt.control_plane_request_id, " + + "attempt.canonical_tenant_id, attempt.owner_attempt_id, attempt.owner_fence, " + + "association.association_request_digest, association.association_response_digest, " + + "?, ?, ?, ? " + + "FROM game_session_start_session_operator_attempt attempt " + + "JOIN game_session_start_session_template_association_pin association " + + "ON association.target_namespace = attempt.target_namespace " + + "AND association.control_plane_request_id = attempt.control_plane_request_id " + + "AND association.canonical_tenant_id = attempt.canonical_tenant_id " + + "AND association.owner_attempt_id = attempt.owner_attempt_id " + + "AND association.owner_fence = attempt.owner_fence " + + "AND association.post_authorization_execution_tuple " + + "= attempt.post_authorization_execution_tuple " + + "WHERE attempt.target_namespace = ? " + + "AND attempt.control_plane_request_id = ? " + + "AND attempt.owner_attempt_id = ? AND attempt.owner_mutation_id = ? " + + "AND attempt.claim_owner_id = ? AND attempt.owner_fence = ? " + + "AND attempt.phase_state = 'OWNER_EXECUTION_PENDING' " + + "AND attempt.account_redemption_projection IS NOT NULL " + + "AND attempt.lease_expires_at > clock_timestamp() " + + "RETURNING *", + prepared.requestWire(), + prepared.responseWire(), + sha256(prepared.requestWire()), + sha256(prepared.responseWire()), + claim.targetNamespace(), + claim.controlPlaneRequestId(), + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.claimOwnerId(), + claim.ownerFence()); + if (inserted == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Game Session owner claim is stale or its attached association changed " + + "before descriptor pinning"); + } + return decodeStored( + inserted, + claim.targetNamespace(), + claim.controlPlaneRequestId(), + claim.ownerAttemptId(), + claim.ownerFence(), + association); + } + + /** + * Pins an exact descriptor through the restricted continuation. The SQL statement repeats the + * stored owner identity, canonical tuple, exact attached projection, and database-clock lease + * predicate at the write boundary. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public PinnedLaunchDescriptorSnapshot pin( + GameSessionStartSessionOperatorAttemptRepository.EvidenceContinuation continuation, + Resolved candidate) { + Objects.requireNonNull(continuation, "evidence continuation is required"); + Objects.requireNonNull(candidate, "candidate is required"); + GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot association = + associationRepository + .findPinned(continuation) + .orElseThrow( + () -> + new StartSessionLaunchDescriptorConflictException( + "An existing template association pin is required before descriptor continuation")); + PreparedCandidate prepared = prepareCandidate(association, candidate); + Record existing = selectPin(continuation, true); + if (existing != null) { + PinnedLaunchDescriptorSnapshot retained = + decodeStored( + existing, + continuation.targetNamespace(), + continuation.controlPlaneRequestId(), + continuation.ownerAttemptId(), + continuation.ownerFence(), + association); + if (Arrays.equals(retained.requestWire(), prepared.requestWire()) + && (Arrays.equals(retained.responseWire(), prepared.responseWire()) + || candidate.outcome().equals(retained.resolved().outcome()))) { + return retained; + } + throw new StartSessionLaunchDescriptorConflictException( + "Descriptor outcome differs from the original immutable StartSession pin"); + } + + Record inserted = + dsl.fetchOne( + "INSERT INTO " + + TABLE + + " (target_namespace, control_plane_request_id, canonical_tenant_id, " + + "owner_attempt_id, owner_fence, association_request_digest, " + + "association_response_digest, descriptor_request_wire, descriptor_response_wire, " + + "descriptor_request_digest, descriptor_response_digest) " + + "SELECT attempt.target_namespace, attempt.control_plane_request_id, " + + "attempt.canonical_tenant_id, attempt.owner_attempt_id, attempt.owner_fence, " + + "association.association_request_digest, association.association_response_digest, " + + "?, ?, ?, ? " + + "FROM game_session_start_session_operator_attempt attempt " + + "JOIN game_session_start_session_template_association_pin association " + + "ON association.target_namespace = attempt.target_namespace " + + "AND association.control_plane_request_id = attempt.control_plane_request_id " + + "AND association.canonical_tenant_id = attempt.canonical_tenant_id " + + "AND association.owner_attempt_id = attempt.owner_attempt_id " + + "AND association.owner_fence = attempt.owner_fence " + + "AND association.post_authorization_execution_tuple " + + "= attempt.post_authorization_execution_tuple " + + "AND association.association_request_digest = ? " + + "AND association.association_response_digest = ? " + + "WHERE attempt.target_namespace = ? " + + "AND attempt.control_plane_request_id = ? " + + "AND attempt.owner_attempt_id = ? AND attempt.owner_mutation_id = ? " + + "AND attempt.claim_owner_id = ? AND attempt.owner_fence = ? " + + "AND attempt.phase_state = 'OWNER_EXECUTION_PENDING' " + + "AND attempt.post_authorization_execution_tuple = ? " + + "AND attempt.account_redemption_projection = ? " + + "AND ?::timestamptz > clock_timestamp() " + + "AND attempt.lease_expires_at > clock_timestamp() " + + "RETURNING *", + prepared.requestWire(), + prepared.responseWire(), + sha256(prepared.requestWire()), + sha256(prepared.responseWire()), + association.requestDigest(), + association.responseDigest(), + continuation.targetNamespace(), + continuation.controlPlaneRequestId(), + continuation.ownerAttemptId(), + continuation.ownerMutationId(), + continuation.claimOwnerId(), + continuation.ownerFence(), + continuation.postAuthorizationExecutionTuple(), + continuation.accountRedemptionProjection(), + originalAuthorizationExpiresAt(continuation)); + if (inserted == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Evidence continuation expired or changed before the descriptor pin statement"); + } + return decodeStored( + inserted, + continuation.targetNamespace(), + continuation.controlPlaneRequestId(), + continuation.ownerAttemptId(), + continuation.ownerFence(), + association); + } + + private static PreparedCandidate prepareCandidate( + GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot pinned, + Resolved candidate) { + Result original = pinned.result(); + Association association = original.association(); + Request expectedRequest = exactReplayRequest(original); + Result expectedAssociation = + new Result( + expectedRequest, + association, + original.releaseBundle(), + original.worldPublishedStartLocationEvidence(), + candidate.associationRead().phaseEpoch()); + byte[] expectedAssociationWire = + StartSessionTemplateAssociationReadGrpcCodec.toResponse(expectedAssociation).toByteArray(); + byte[] candidateAssociationWire = + StartSessionTemplateAssociationReadGrpcCodec.toResponse(candidate.associationRead()) + .toByteArray(); + if (!expectedRequest.equals(candidate.associationRead().request()) + || !Arrays.equals(expectedAssociationWire, candidateAssociationWire)) { + throw new StartSessionLaunchDescriptorConflictException( + "Descriptor response association differs from the retained exact " + + "StartSession selection"); + } + + ReadStartSessionTemplateAssociationRequest requestMessage = + StartSessionLaunchDescriptorGrpcCodec.toRequest(expectedRequest); + ResolveStartSessionLaunchDescriptorResponse responseMessage = + StartSessionLaunchDescriptorGrpcCodec.toResponse( + expectedRequest, candidate.associationRead(), candidate.outcome()); + Resolved decoded = + StartSessionLaunchDescriptorGrpcCodec.fromResponse(expectedRequest, responseMessage); + if (!decoded.equals(candidate) + || !Arrays.equals( + StartSessionLaunchDescriptorGrpcCodec.toResponse( + expectedRequest, decoded.associationRead(), decoded.outcome()) + .toByteArray(), + responseMessage.toByteArray())) { + throw new StartSessionLaunchDescriptorConflictException( + "Descriptor outcome is not the canonical closed StartSession response"); + } + byte[] requestWire = requestMessage.toByteArray(); + byte[] responseWire = responseMessage.toByteArray(); + requireWireBound(requestWire, responseWire); + return new PreparedCandidate(requestWire, responseWire); + } + + private PinnedLaunchDescriptorSnapshot decodeStored( + Record row, + String expectedNamespace, + String expectedRequestId, + UUID expectedOwnerAttemptId, + long expectedOwnerFence, + GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot pinned) { + Request expectedRequest = exactReplayRequest(pinned.result()); + StartSessionPostAuthorizationExecutionTuple tuple = expectedRequest.decodedTuple(); + byte[] requestWire = requiredBytes(row, "descriptor_request_wire"); + byte[] responseWire = requiredBytes(row, "descriptor_response_wire"); + if (!requiredText(row, "target_namespace").equals(expectedNamespace) + || !requiredText(row, "control_plane_request_id").equals(expectedRequestId) + || !requiredUuid(row, "canonical_tenant_id") + .equals(pinned.result().association().canonicalTenantId()) + || !requiredUuid(row, "owner_attempt_id").equals(expectedOwnerAttemptId) + || requiredLong(row, "owner_fence") != expectedOwnerFence + || !requiredText(row, "association_request_digest").equals(pinned.requestDigest()) + || !requiredText(row, "association_response_digest").equals(pinned.responseDigest()) + || !requiredText(row, "descriptor_request_digest").equals(sha256(requestWire)) + || !requiredText(row, "descriptor_response_digest").equals(sha256(responseWire))) { + throw new IllegalStateException( + "Persisted StartSession descriptor pin differs from its original association " + + "or owner claim"); + } + if (!tuple.controlPlaneRequestId().equals(expectedRequestId) + || !expectedRequest.targetNamespace().equals(expectedNamespace) + || !expectedRequest.ownerAttemptId().equals(expectedOwnerAttemptId) + || expectedRequest.ownerFence() != expectedOwnerFence) { + throw new IllegalStateException( + "Persisted StartSession descriptor pin request differs from its current owner claim"); + } + requireWireBound(requestWire, responseWire); + + try { + ReadStartSessionTemplateAssociationRequest requestMessage = + ReadStartSessionTemplateAssociationRequest.parseFrom(requestWire); + Request request = StartSessionLaunchDescriptorGrpcCodec.fromRequest(requestMessage); + if (!request.equals(expectedRequest) + || !Arrays.equals( + StartSessionLaunchDescriptorGrpcCodec.toRequest(request).toByteArray(), + requestWire)) { + throw new IllegalStateException( + "Persisted StartSession descriptor request differs from the retained exact selection"); + } + ResolveStartSessionLaunchDescriptorResponse responseMessage = + ResolveStartSessionLaunchDescriptorResponse.parseFrom(responseWire); + Resolved resolved = + StartSessionLaunchDescriptorGrpcCodec.fromResponse(expectedRequest, responseMessage); + byte[] expectedAssociationWire = + StartSessionTemplateAssociationReadGrpcCodec.toResponse( + exactReplayAssociation( + pinned.result(), expectedRequest, resolved.associationRead().phaseEpoch())) + .toByteArray(); + byte[] retainedAssociationWire = + StartSessionTemplateAssociationReadGrpcCodec.toResponse(resolved.associationRead()) + .toByteArray(); + if (!Arrays.equals(expectedAssociationWire, retainedAssociationWire) + || !Arrays.equals( + StartSessionLaunchDescriptorGrpcCodec.toResponse( + expectedRequest, resolved.associationRead(), resolved.outcome()) + .toByteArray(), + responseWire)) { + throw new IllegalStateException( + "Persisted StartSession descriptor response differs from its retained association"); + } + return new PinnedLaunchDescriptorSnapshot( + resolved, + requestWire, + responseWire, + requiredText(row, "descriptor_request_digest"), + requiredText(row, "descriptor_response_digest"), + requiredInstant(row, "created_at")); + } catch (InvalidProtocolBufferException | IllegalArgumentException malformed) { + throw new IllegalStateException( + "Persisted StartSession launch descriptor evidence is malformed", malformed); + } + } + + private static Result exactReplayAssociation(Result original, Request request, long phaseEpoch) { + return new Result( + request, + original.association(), + original.releaseBundle(), + original.worldPublishedStartLocationEvidence(), + phaseEpoch); + } + + private static Request exactReplayRequest(Result original) { + Association association = original.association(); + Request firstRequest = original.request(); + return new Request( + firstRequest.schemaVersion(), + firstRequest.targetNamespace(), + firstRequest.readRequestId(), + firstRequest.canonicalPostAuthorizationTuple(), + firstRequest.ownerAttemptId(), + firstRequest.ownerFence(), + new ExactReplay( + association.canonicalVersionId(), + association.selectedCommitId(), + association.publishWorkflowId(), + association.associationDigest())); + } + + private Record selectPin(String namespace, String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + namespace, + requestId); + } + + private Record selectPin( + GameSessionStartSessionOperatorAttemptRepository.EvidenceContinuation continuation, + boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ? " + + "AND ?::timestamptz > clock_timestamp()" + + (forUpdate ? " FOR UPDATE" : ""), + continuation.targetNamespace(), + continuation.controlPlaneRequestId(), + originalAuthorizationExpiresAt(continuation)); + } + + private static String originalAuthorizationExpiresAt( + GameSessionStartSessionOperatorAttemptRepository.EvidenceContinuation continuation) { + byte[] exactTuple = continuation.postAuthorizationExecutionTuple(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(exactTuple); + if (!Arrays.equals(tuple.canonicalBytes(), exactTuple)) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Evidence continuation tuple is not canonical"); + } + return StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .authorizationExpiresAt(); + } + + private static void requireWireBound(byte[] requestWire, byte[] responseWire) { + if (requestWire.length == 0 + || responseWire.length == 0 + || requestWire.length > MAX_REQUEST_WIRE_BYTES + || responseWire.length > MAX_RESPONSE_WIRE_BYTES) { + throw new StartSessionLaunchDescriptorConflictException( + "Launch descriptor carrier exceeds the local fail-closed storage budget"); + } + } + + private static String sha256(byte[] value) { + Objects.requireNonNull(value, "digest input is required"); + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static String requiredText(Record row, String field) { + String value = row == null ? null : row.get(field, String.class); + if (value == null) { + throw new IllegalStateException("Persisted descriptor pin is missing " + field); + } + return value; + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row == null ? null : row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalStateException("Persisted descriptor pin is missing " + field); + } + return value; + } + + private static long requiredLong(Record row, String field) { + Long value = row == null ? null : row.get(field, Long.class); + if (value == null) { + throw new IllegalStateException("Persisted descriptor pin is missing " + field); + } + return value; + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row == null ? null : row.get(field, byte[].class); + if (value == null) { + throw new IllegalStateException("Persisted descriptor pin is missing " + field); + } + return value.clone(); + } + + private static Instant requiredInstant(Record row, String field) { + java.time.OffsetDateTime value = + row == null ? null : row.get(field, java.time.OffsetDateTime.class); + if (value == null) { + throw new IllegalStateException("Persisted descriptor pin is missing created_at"); + } + return value.toInstant(); + } + + private record PreparedCandidate(byte[] requestWire, byte[] responseWire) { + private PreparedCandidate { + requestWire = requestWire.clone(); + responseWire = responseWire.clone(); + } + + @Override + public byte[] requestWire() { + return requestWire.clone(); + } + + @Override + public byte[] responseWire() { + return responseWire.clone(); + } + } + + /** Retained typed outcome plus exact canonical wire evidence and local storage digests. */ + public record PinnedLaunchDescriptorSnapshot( + Resolved resolved, + byte[] requestWire, + byte[] responseWire, + String requestDigest, + String responseDigest, + Instant createdAt) { + public PinnedLaunchDescriptorSnapshot { + Objects.requireNonNull(resolved, "resolved is required"); + requestWire = Objects.requireNonNull(requestWire, "requestWire is required").clone(); + responseWire = Objects.requireNonNull(responseWire, "responseWire is required").clone(); + Objects.requireNonNull(requestDigest, "requestDigest is required"); + Objects.requireNonNull(responseDigest, "responseDigest is required"); + Objects.requireNonNull(createdAt, "createdAt is required"); + } + + @Override + public byte[] requestWire() { + return requestWire.clone(); + } + + @Override + public byte[] responseWire() { + return responseWire.clone(); + } + } + + public static final class StartSessionLaunchDescriptorConflictException + extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public StartSessionLaunchDescriptorConflictException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java new file mode 100644 index 0000000000..5501dd7c6d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java @@ -0,0 +1,789 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.sql.Connection; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unregistered, non-activating durable reservation for one canonical StartSession owner attempt. + * + *

This repository records immutable intent before the Account redemption call. It does not + * perform redemption, infer authority, dispatch a Game Session mutation, or write a business + * result. An expired claim remains pending and cannot be transferred or re-armed here. + */ +public final class GameSessionStartSessionOperatorAttemptRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String TABLE = "game_session_start_session_operator_attempt"; + private static final String OWNER_FENCE_SEQUENCE = + "game_session_start_session_operator_owner_fence_seq"; + private static final Pattern AUTHORIZATION_REFERENCE_FINGERPRINT = + Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Duration MAX_OWNER_CLAIM_LEASE = Duration.ofMinutes(5); + + private final DSLContext dsl; + private final long ownerClaimLeaseMillis; + + public GameSessionStartSessionOperatorAttemptRepository( + DSLContext dsl, Duration ownerClaimLease) { + this.dsl = Objects.requireNonNull(dsl, "dsl is required"); + Objects.requireNonNull(ownerClaimLease, "owner claim lease is required"); + long millis = ownerClaimLease.toMillis(); + if (millis <= 0L || ownerClaimLease.compareTo(MAX_OWNER_CLAIM_LEASE) > 0) { + throw new IllegalArgumentException( + "owner claim lease must be positive and at most five minutes"); + } + this.ownerClaimLeaseMillis = millis; + } + + /** + * Creates one claim or returns the exact existing attempt without granting a second claim. + * Requires a caller-owned, writable READ COMMITTED transaction. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public ReservationResult reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(tuple, "post-authorization tuple is required"); + String namespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + String requestId = tuple.controlPlaneRequestId(); + lockRequestKey(namespace, requestId); + + Record existing = selectAttempt(namespace, requestId, true); + if (existing != null) { + byte[] storedTuple = requiredBytes(existing, "post_authorization_execution_tuple"); + if (!Arrays.equals(storedTuple, tuple.canonicalBytes())) { + throw new StartSessionOperatorAttemptConflictException( + "controlPlaneRequestId is already bound to a different complete post-authorization tuple"); + } + requireStoredProjectionColumnsMatch(existing, tuple); + return new ReservationResult( + ReservationDisposition.EXACT_REPLAY, snapshot(existing), Optional.empty()); + } + + UUID attemptId = newNonNilUuid("ownerAttemptId"); + UUID ownerMutationId = newNonNilUuid("ownerMutationId"); + UUID claimOwnerId = newNonNilUuid("claimOwnerId"); + Record fenceRecord = dsl.fetchOne("SELECT nextval('" + OWNER_FENCE_SEQUENCE + "') AS fence"); + long ownerFence = requiredLong(fenceRecord, "fence"); + if (ownerFence <= 0L) { + throw new IllegalStateException( + "Game Session owner fence sequence did not produce a positive value"); + } + + Record inserted = + dsl.fetchOne( + "INSERT INTO " + + TABLE + + " (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() + (?::double precision / 1000.0) * interval '1 second') " + + "RETURNING *", + namespace, + requestId, + tuple.preAuthorizationTuple().action().scope().tenantId(), + attemptId, + ownerMutationId, + claimOwnerId, + ownerFence, + tuple.canonicalBytes(), + tuple.mutationDigest(), + tuple.authorizationReferenceFingerprint(), + ownerClaimLeaseMillis); + if (inserted == null) { + throw new IllegalStateException("Game Session owner attempt insert returned no row"); + } + AttemptClaim claim = + new AttemptClaim( + namespace, requestId, attemptId, ownerMutationId, claimOwnerId, ownerFence); + return new ReservationResult( + ReservationDisposition.CLAIM_CREATED, snapshot(inserted), Optional.of(claim)); + } + + /** + * Validates the exact original claim and returns its durable snapshot. Expired claims are stale; + * they are deliberately not advanced or reallocated. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public AttemptSnapshot validateCurrentClaim(AttemptClaim claim) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(claim, "owner attempt claim is required"); + Record row = selectAttempt(claim.targetNamespace(), claim.controlPlaneRequestId(), true); + requireClaimMatch(row, claim); + requireUnexpired(row); + return snapshot(row); + } + + /** + * Creates a narrow continuation capability for the exact existing pending attempt. This does not + * reconstruct or expose an {@link AttemptClaim}; every use revalidates the stored claim identity. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public EvidenceContinuation beginEvidenceContinuation( + StartSessionPostAuthorizationExecutionTuple tuple) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); + String namespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + Record row = selectAttempt(namespace, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Original StartSession owner attempt is missing and remains reconciliation-only"); + } + byte[] exactTuple = tuple.canonicalBytes(); + if (!Arrays.equals(requiredBytes(row, "post_authorization_execution_tuple"), exactTuple)) { + throw new StartSessionOperatorAttemptConflictException( + "Evidence continuation tuple differs from the original complete StartSession attempt"); + } + if (!"OWNER_EXECUTION_PENDING".equals(requiredText(row, "phase_state"))) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Only the original pending StartSession attempt supports evidence continuation"); + } + requireStoredProjectionColumnsMatch(row, tuple); + requireUnexpired(row); + requireOriginalAuthorityUnexpired(tuple); + byte[] storedProjection = optionalBytes(row, "account_redemption_projection"); + if (storedProjection == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "StartSession attempt has no attached Account projection and remains reconciliation-only"); + } + AccountRedemptionProjection expectedProjection = projectionFromTuple(tuple); + byte[] canonicalProjection = expectedProjection.canonicalBytes(); + if (!Arrays.equals(storedProjection, canonicalProjection)) { + throw new IllegalStateException( + "Persisted Account redemption projection differs from its complete canonical tuple"); + } + requireProjectionMatches(tuple, expectedProjection); + + return new EvidenceContinuation( + requiredText(row, "target_namespace"), + requiredText(row, "control_plane_request_id"), + requiredUuid(row, "owner_attempt_id"), + requiredUuid(row, "owner_mutation_id"), + requiredUuid(row, "claim_owner_id"), + requiredLong(row, "owner_fence"), + exactTuple, + storedProjection); + } + + /** + * Repo-internal capability check. Callers receive only the immutable attempt snapshot, never an + * AttemptClaim that could be reused for redemption or a general mutation. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + AttemptSnapshot validateEvidenceContinuation(EvidenceContinuation continuation) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(continuation, "evidence continuation is required"); + Record row = + selectAttempt(continuation.targetNamespace(), continuation.controlPlaneRequestId(), true); + if (row == null + || !continuation.ownerAttemptId().equals(optionalUuid(row, "owner_attempt_id")) + || !continuation.ownerMutationId().equals(optionalUuid(row, "owner_mutation_id")) + || !continuation.claimOwnerId().equals(optionalUuid(row, "claim_owner_id")) + || continuation.ownerFence() != optionalLong(row, "owner_fence")) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Evidence continuation no longer identifies the original stored owner claim"); + } + if (!"OWNER_EXECUTION_PENDING".equals(requiredText(row, "phase_state"))) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Evidence continuation requires the same pending owner attempt"); + } + requireUnexpired(row); + byte[] currentTuple = requiredBytes(row, "post_authorization_execution_tuple"); + if (!Arrays.equals(currentTuple, continuation.postAuthorizationExecutionTuple())) { + throw new StartSessionOperatorAttemptConflictException( + "Evidence continuation tuple or Account projection differs from the retained attempt"); + } + StartSessionPostAuthorizationExecutionTuple decodedTuple = + StartSessionPostAuthorizationExecutionTuple.decode(currentTuple); + requireOriginalAuthorityUnexpired(decodedTuple); + byte[] currentProjection = optionalBytes(row, "account_redemption_projection"); + if (currentProjection == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Evidence continuation Account projection is no longer attached"); + } + if (!Arrays.equals(currentProjection, continuation.accountRedemptionProjection())) { + throw new StartSessionOperatorAttemptConflictException( + "Evidence continuation tuple or Account projection differs from the retained attempt"); + } + StartSessionPostAuthorizationExecutionTuple tuple = decodedTuple; + if (!Arrays.equals(tuple.canonicalBytes(), currentTuple) + || !tuple.controlPlaneRequestId().equals(continuation.controlPlaneRequestId()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(continuation.targetNamespace())) { + throw new IllegalStateException( + "Evidence continuation tuple is not the canonical original owner identity"); + } + requireStoredProjectionColumnsMatch(row, tuple); + AccountRedemptionProjection expectedProjection = projectionFromTuple(tuple); + if (!Arrays.equals(currentProjection, expectedProjection.canonicalBytes())) { + throw new IllegalStateException( + "Evidence continuation Account projection is not canonical for its tuple"); + } + requireProjectionMatches(tuple, expectedProjection); + return snapshot(row); + } + + /** + * Atomically attaches the exact Account redemption projection to its still-current claim. Replays + * of the same projection return the original snapshot; any substitution conflicts. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public AttemptSnapshot attachAccountRedemptionProjection( + AttemptClaim claim, AccountRedemptionProjection projection) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(claim, "owner attempt claim is required"); + Objects.requireNonNull(projection, "Account redemption projection is required"); + Record row = selectAttempt(claim.targetNamespace(), claim.controlPlaneRequestId(), true); + requireClaimMatch(row, claim); + requireUnexpired(row); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + requiredBytes(row, "post_authorization_execution_tuple")); + requireProjectionMatches(tuple, projection); + + byte[] existingProjection = optionalBytes(row, "account_redemption_projection"); + byte[] exactProjection = projection.canonicalBytes(); + if (existingProjection != null) { + if (!Arrays.equals(existingProjection, exactProjection)) { + throw new StartSessionOperatorAttemptConflictException( + "Account redemption projection differs from the original exact projection"); + } + return snapshot(row); + } + + Record updated = + dsl.fetchOne( + "UPDATE " + + TABLE + + " SET account_redemption_projection = ? " + + "WHERE target_namespace = ? AND control_plane_request_id = ? " + + "AND owner_attempt_id = ? AND owner_mutation_id = ? " + + "AND claim_owner_id = ? AND owner_fence = ? " + + "AND lease_expires_at > clock_timestamp() " + + "AND account_redemption_projection IS NULL RETURNING *", + exactProjection, + claim.targetNamespace(), + claim.controlPlaneRequestId(), + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.claimOwnerId(), + claim.ownerFence()); + if (updated == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Game Session owner attempt claim changed before Account projection attachment"); + } + return snapshot(updated); + } + + private void lockRequestKey(String namespace, String requestId) { + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ?, 0))", namespace, requestId); + } + + private Record selectAttempt(String namespace, String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + namespace, + requestId); + } + + private static void requireStoredProjectionColumnsMatch( + Record row, StartSessionPostAuthorizationExecutionTuple tuple) { + if (!tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .equals(requiredUuid(row, "canonical_tenant_id")) + || !tuple.mutationDigest().equals(requiredText(row, "mutation_digest")) + || !tuple + .authorizationReferenceFingerprint() + .equals(requiredText(row, "authorization_reference_fingerprint"))) { + throw new IllegalStateException( + "Persisted Game Session owner attempt columns differ from its exact canonical tuple"); + } + } + + private static void requireProjectionMatches( + StartSessionPostAuthorizationExecutionTuple tuple, AccountRedemptionProjection projection) { + if (!tuple + .authorizationReferenceFingerprint() + .equals(projection.authorizationReferenceFingerprint()) + || !Arrays.equals( + tuple.authorityEvidenceBundleBytes(), projection.authorityEvidenceBundleBytes()) + || !StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .issuanceOperationId() + .equals(projection.issuanceOperationId()) + || parsePositiveFence(tuple.issuanceFence()) != projection.issuanceFence()) { + throw new StartSessionOperatorAttemptConflictException( + "Account redemption projection is not bound to the exact post-authorization tuple"); + } + } + + private static AccountRedemptionProjection projectionFromTuple( + StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle authority = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + parsePositiveFence(tuple.issuanceFence())); + } + + private static void requireClaimMatch(Record row, AttemptClaim claim) { + if (row == null + || !claim.ownerAttemptId().equals(optionalUuid(row, "owner_attempt_id")) + || !claim.ownerMutationId().equals(optionalUuid(row, "owner_mutation_id")) + || !claim.claimOwnerId().equals(optionalUuid(row, "claim_owner_id")) + || claim.ownerFence() != optionalLong(row, "owner_fence")) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Game Session owner attempt claim is missing or no longer exact"); + } + } + + private void requireUnexpired(Record row) { + Record validity = + dsl.fetchOne( + "SELECT lease_expires_at > clock_timestamp() AS unexpired " + + "FROM " + + TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ?", + requiredText(row, "target_namespace"), + requiredText(row, "control_plane_request_id")); + if (validity == null || !Boolean.TRUE.equals(validity.get("unexpired", Boolean.class))) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Game Session owner attempt claim lease is expired and remains non-replayable"); + } + } + + private void requireOriginalAuthorityUnexpired( + StartSessionPostAuthorizationExecutionTuple tuple) { + String referenceExpiresAt = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .authorizationExpiresAt(); + Record validity = + dsl.fetchOne("SELECT ?::timestamptz > clock_timestamp() AS unexpired", referenceExpiresAt); + if (validity == null || !Boolean.TRUE.equals(validity.get("unexpired", Boolean.class))) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Original Account authorization reference expired during evidence continuation"); + } + } + + private static AttemptSnapshot snapshot(Record row) { + return new AttemptSnapshot( + requiredText(row, "target_namespace"), + requiredText(row, "control_plane_request_id"), + requiredUuid(row, "canonical_tenant_id"), + requiredUuid(row, "owner_attempt_id"), + requiredUuid(row, "owner_mutation_id"), + requiredLong(row, "owner_fence"), + requiredText(row, "phase_state"), + requiredBytes(row, "post_authorization_execution_tuple"), + optionalBytes(row, "account_redemption_projection"), + requiredInstant(row, "created_at"), + requiredInstant(row, "lease_expires_at")); + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "StartSession owner attempt requires a writable READ COMMITTED owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "StartSession owner attempt requires a writable READ COMMITTED owner transaction"); + } + return null; + }); + Record transaction = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + if (transaction == null + || !"read committed".equals(transaction.get("isolation", String.class)) + || !"off".equals(transaction.get("read_only", String.class))) { + throw new IllegalStateException( + "StartSession owner attempt requires a writable READ COMMITTED owner transaction"); + } + } + + private static long parsePositiveFence(String value) { + try { + long fence = Long.parseLong(value); + if (fence <= 0L || !Long.toString(fence).equals(value)) { + throw new NumberFormatException(); + } + return fence; + } catch (NumberFormatException malformed) { + throw new IllegalArgumentException( + "Account issuance fence is outside the signed owner range"); + } + } + + private static UUID newNonNilUuid(String field) { + UUID value = UUID.randomUUID(); + if (NIL_UUID.equals(value)) { + throw new IllegalStateException("Random UUID source returned nil " + field); + } + return value; + } + + private static String requiredText(Record row, String field) { + String value = row == null ? null : row.get(field, String.class); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner attempt is missing " + field); + } + return value; + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = optionalUuid(row, field); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner attempt is missing " + field); + } + return value; + } + + private static UUID optionalUuid(Record row, String field) { + return row == null ? null : row.get(field, UUID.class); + } + + private static long requiredLong(Record row, String field) { + Long value = optionalLong(row, field); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner attempt is missing " + field); + } + return value; + } + + private static Long optionalLong(Record row, String field) { + return row == null ? null : row.get(field, Long.class); + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = optionalBytes(row, field); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner attempt is missing " + field); + } + return value; + } + + private static byte[] optionalBytes(Record row, String field) { + byte[] value = row == null ? null : row.get(field, byte[].class); + return value == null ? null : value.clone(); + } + + private static Instant requiredInstant(Record row, String field) { + java.time.OffsetDateTime value = + row == null ? null : row.get(field, java.time.OffsetDateTime.class); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner attempt is missing " + field); + } + return value.toInstant(); + } + + public enum ReservationDisposition { + CLAIM_CREATED, + EXACT_REPLAY + } + + /** Result distinguishes the unique newly minted claim from a replay snapshot. */ + public record ReservationResult( + ReservationDisposition disposition, AttemptSnapshot snapshot, Optional claim) { + public ReservationResult { + Objects.requireNonNull(disposition, "disposition is required"); + Objects.requireNonNull(snapshot, "snapshot is required"); + Objects.requireNonNull(claim, "claim wrapper is required"); + if ((disposition == ReservationDisposition.CLAIM_CREATED) != claim.isPresent()) { + throw new IllegalArgumentException( + "only a newly created owner attempt may return its claim"); + } + } + } + + /** One opaque-in-process capability returned only to the transaction that created the claim. */ + public record AttemptClaim( + String targetNamespace, + String controlPlaneRequestId, + UUID ownerAttemptId, + UUID ownerMutationId, + UUID claimOwnerId, + long ownerFence) { + public AttemptClaim { + Objects.requireNonNull(targetNamespace, "targetNamespace is required"); + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId is required"); + requireNonNil(ownerAttemptId, "ownerAttemptId"); + requireNonNil(ownerMutationId, "ownerMutationId"); + requireNonNil(claimOwnerId, "claimOwnerId"); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + } + } + + /** + * Narrow owner-internal continuation token. Its constructor and all claim-binding accessors are + * private to this repository package; it exposes no claimant credential or redemption API. + */ + public static final class EvidenceContinuation { + private final String targetNamespace; + private final String controlPlaneRequestId; + private final UUID ownerAttemptId; + private final UUID ownerMutationId; + private final UUID claimOwnerId; + private final long ownerFence; + private final byte[] postAuthorizationExecutionTuple; + private final byte[] accountRedemptionProjection; + + private EvidenceContinuation( + String targetNamespace, + String controlPlaneRequestId, + UUID ownerAttemptId, + UUID ownerMutationId, + UUID claimOwnerId, + long ownerFence, + byte[] postAuthorizationExecutionTuple, + byte[] accountRedemptionProjection) { + this.targetNamespace = Objects.requireNonNull(targetNamespace); + this.controlPlaneRequestId = Objects.requireNonNull(controlPlaneRequestId); + this.ownerAttemptId = Objects.requireNonNull(ownerAttemptId); + this.ownerMutationId = Objects.requireNonNull(ownerMutationId); + this.claimOwnerId = Objects.requireNonNull(claimOwnerId); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + this.ownerFence = ownerFence; + this.postAuthorizationExecutionTuple = postAuthorizationExecutionTuple.clone(); + this.accountRedemptionProjection = accountRedemptionProjection.clone(); + } + + String targetNamespace() { + return targetNamespace; + } + + String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + UUID ownerAttemptId() { + return ownerAttemptId; + } + + UUID ownerMutationId() { + return ownerMutationId; + } + + UUID claimOwnerId() { + return claimOwnerId; + } + + long ownerFence() { + return ownerFence; + } + + byte[] postAuthorizationExecutionTuple() { + return postAuthorizationExecutionTuple.clone(); + } + + byte[] accountRedemptionProjection() { + return accountRedemptionProjection.clone(); + } + } + + /** Immutable readback; byte-array accessors never expose the stored record buffer. */ + public static final class AttemptSnapshot { + private final String targetNamespace; + private final String controlPlaneRequestId; + private final UUID canonicalTenantId; + private final UUID ownerAttemptId; + private final UUID ownerMutationId; + private final long ownerFence; + private final String phaseState; + private final byte[] postAuthorizationExecutionTuple; + private final byte[] accountRedemptionProjection; + private final Instant createdAt; + private final Instant leaseExpiresAt; + + private AttemptSnapshot( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + UUID ownerAttemptId, + UUID ownerMutationId, + long ownerFence, + String phaseState, + byte[] postAuthorizationExecutionTuple, + byte[] accountRedemptionProjection, + Instant createdAt, + Instant leaseExpiresAt) { + this.targetNamespace = targetNamespace; + this.controlPlaneRequestId = controlPlaneRequestId; + this.canonicalTenantId = canonicalTenantId; + this.ownerAttemptId = ownerAttemptId; + this.ownerMutationId = ownerMutationId; + this.ownerFence = ownerFence; + this.phaseState = phaseState; + this.postAuthorizationExecutionTuple = postAuthorizationExecutionTuple.clone(); + this.accountRedemptionProjection = + accountRedemptionProjection == null ? null : accountRedemptionProjection.clone(); + this.createdAt = createdAt; + this.leaseExpiresAt = leaseExpiresAt; + } + + public String targetNamespace() { + return targetNamespace; + } + + public String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public UUID ownerAttemptId() { + return ownerAttemptId; + } + + public UUID ownerMutationId() { + return ownerMutationId; + } + + public long ownerFence() { + return ownerFence; + } + + public String phaseState() { + return phaseState; + } + + public byte[] postAuthorizationExecutionTuple() { + return postAuthorizationExecutionTuple.clone(); + } + + public byte[] accountRedemptionProjection() { + return accountRedemptionProjection == null ? null : accountRedemptionProjection.clone(); + } + + public Instant createdAt() { + return createdAt; + } + + public Instant leaseExpiresAt() { + return leaseExpiresAt; + } + } + + /** Typed, no-secret Account redemption output persisted only after exact tuple comparison. */ + public record AccountRedemptionProjection( + String authorizationReferenceFingerprint, + byte[] authorityEvidenceBundleBytes, + UUID issuanceOperationId, + long issuanceFence) { + public AccountRedemptionProjection { + if (authorizationReferenceFingerprint == null + || !AUTHORIZATION_REFERENCE_FINGERPRINT + .matcher(authorizationReferenceFingerprint) + .matches()) { + throw new IllegalArgumentException("Account redemption fingerprint is malformed"); + } + authorityEvidenceBundleBytes = + Objects.requireNonNull( + authorityEvidenceBundleBytes, "authority evidence bundle is required") + .clone(); + Objects.requireNonNull(issuanceOperationId, "issuanceOperationId is required"); + if (issuanceOperationId.equals(NIL_UUID) || issuanceFence <= 0L) { + throw new IllegalArgumentException( + "Account redemption identity and fence must be positive"); + } + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundleBytes); + if (!bundle.issuanceOperationId().equals(issuanceOperationId) + || parsePositiveFence(bundle.issuanceFence()) != issuanceFence) { + throw new IllegalArgumentException( + "Account redemption response differs from its exact authority evidence bundle"); + } + } + + @Override + public byte[] authorityEvidenceBundleBytes() { + return authorityEvidenceBundleBytes.clone(); + } + + public byte[] canonicalBytes() { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundleBytes); + Map projection = new LinkedHashMap<>(); + projection.put("projectionSchemaId", "accountStartSessionRedemptionProjection"); + projection.put("projectionSchemaVersion", "1"); + projection.put("authorizationReferenceFingerprint", authorizationReferenceFingerprint); + projection.put("authorityEvidenceBundle", bundle.jsonValue()); + projection.put("issuanceOperationId", issuanceOperationId.toString()); + projection.put("issuanceFence", issuanceFence); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + if (bytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException( + "Account redemption projection exceeds its byte limit"); + } + return bytes; + } catch (java.io.IOException exception) { + throw new IllegalStateException( + "could not encode Account redemption projection", exception); + } + } + } + + public static final class StartSessionOperatorAttemptConflictException + extends IllegalStateException { + public StartSessionOperatorAttemptConflictException(String message) { + super(message); + } + } + + public static final class StaleStartSessionOperatorAttemptClaimException + extends IllegalStateException { + public StaleStartSessionOperatorAttemptClaimException(String message) { + super(message); + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must not be nil"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java new file mode 100644 index 0000000000..8e56aa6b3a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java @@ -0,0 +1,441 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Unregistered immutable pin for the first normalized Game Design association selected by a + * canonical StartSession owner attempt. It creates no instance, pointer, hold, admission, or grant. + */ +public final class GameSessionStartSessionTemplateAssociationRepository { + // Local fail-closed storage budgets only; these do not imply a gRPC transport message limit. + private static final int MAX_REQUEST_WIRE_BYTES = + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + 1024; + private static final int MAX_RESPONSE_WIRE_BYTES = 4 * 1024 * 1024; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String TABLE = "game_session_start_session_template_association_pin"; + + private final DSLContext dsl; + private final GameSessionStartSessionOperatorAttemptRepository attemptRepository; + + public GameSessionStartSessionTemplateAssociationRepository( + DSLContext dsl, GameSessionStartSessionOperatorAttemptRepository attemptRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl is required"); + this.attemptRepository = + Objects.requireNonNull(attemptRepository, "attemptRepository is required"); + } + + /** + * Returns only the first retained selection after locking and revalidating the live owner claim. + * A caller must use this before asking Game Design to resolve a selection again. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public Optional findPinned( + GameSessionStartSessionOperatorAttemptRepository.AttemptClaim claim) { + Objects.requireNonNull(claim, "claim is required"); + GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot attempt = + validateCurrentAttempt(claim); + Record row = selectPin(claim.targetNamespace(), claim.controlPlaneRequestId(), true); + return row == null + ? Optional.empty() + : Optional.of( + decodeStored(row, claim.targetNamespace(), claim.controlPlaneRequestId(), attempt)); + } + + /** + * Returns only an existing association pin through the restricted continuation capability. This + * overload cannot create an initial selection or reconstruct an owner claim. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public Optional findPinned( + GameSessionStartSessionOperatorAttemptRepository.EvidenceContinuation continuation) { + Objects.requireNonNull(continuation, "evidence continuation is required"); + GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot attempt = + attemptRepository.validateEvidenceContinuation(continuation); + Record row = + selectPin(continuation.targetNamespace(), continuation.controlPlaneRequestId(), true); + return row == null + ? Optional.empty() + : Optional.of( + decodeStored( + row, + continuation.targetNamespace(), + continuation.controlPlaneRequestId(), + attempt)); + } + + /** + * Pins the first configured selection or validates a later exact replay against the retained + * selection. Only the byte-identical original response may replay INITIAL_CONFIGURED; a new + * initial read cannot reselect after a pin exists. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public PinnedAssociationSnapshot pinInitialOrValidateExactReplay( + GameSessionStartSessionOperatorAttemptRepository.AttemptClaim claim, Result candidate) { + Objects.requireNonNull(claim, "claim is required"); + Objects.requireNonNull(candidate, "candidate is required"); + byte[] requestWire = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(candidate.request()).toByteArray(); + byte[] responseWire = + StartSessionTemplateAssociationReadGrpcCodec.toResponse(candidate).toByteArray(); + requireWireBound(requestWire, responseWire); + GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot attempt = + validateCurrentAttempt(claim); + requireCandidateBoundToAttempt(claim, attempt, candidate); + Record existing = selectPin(claim.targetNamespace(), claim.controlPlaneRequestId(), true); + if (existing != null) { + byte[] originalRequestWire = requiredBytes(existing, "association_request_wire"); + byte[] originalResponseWire = requiredBytes(existing, "association_response_wire"); + if (Arrays.equals(originalRequestWire, requestWire) + && Arrays.equals(originalResponseWire, responseWire)) { + return decodeStored( + existing, claim.targetNamespace(), claim.controlPlaneRequestId(), attempt); + } + PinnedAssociationSnapshot original = + decodeStored(existing, claim.targetNamespace(), claim.controlPlaneRequestId(), attempt); + requireExactReplay(original, candidate); + return original; + } + + if (!(candidate.request().selection() instanceof InitialConfigured)) { + throw new StartSessionTemplateAssociationConflictException( + "An exact replay cannot create the original template association pin"); + } + + Association association = candidate.association(); + Record inserted = + dsl.fetchOne( + "INSERT INTO " + + TABLE + + " (target_namespace, control_plane_request_id, canonical_tenant_id, " + + "owner_attempt_id, owner_fence, post_authorization_execution_tuple, " + + "post_authorization_tuple_digest, account_redemption_projection_digest, " + + "association_request_wire, association_response_wire, association_request_digest, " + + "association_response_digest, template_id, canonical_version_id, selected_commit_id, " + + "publish_workflow_id, publication_selection_digest, association_digest, " + + "world_intake_request_id, world_operation_id, source_operation_id, " + + "source_evidence_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "RETURNING *", + attempt.targetNamespace(), + attempt.controlPlaneRequestId(), + attempt.canonicalTenantId(), + attempt.ownerAttemptId(), + attempt.ownerFence(), + attempt.postAuthorizationExecutionTuple(), + sha256(attempt.postAuthorizationExecutionTuple()), + sha256(attempt.accountRedemptionProjection()), + requestWire, + responseWire, + sha256(requestWire), + sha256(responseWire), + association.templateId(), + association.canonicalVersionId(), + association.selectedCommitId(), + association.publishWorkflowId(), + association.publicationSelectionDigest(), + association.associationDigest(), + association.intakeRequestId(), + association.worldOperationId(), + association.sourceOperationId(), + association.sourceEvidenceDigest()); + if (inserted == null) { + throw new IllegalStateException("Game Session association pin insert returned no row"); + } + return decodeStored(inserted, claim.targetNamespace(), claim.controlPlaneRequestId(), attempt); + } + + private GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot validateCurrentAttempt( + GameSessionStartSessionOperatorAttemptRepository.AttemptClaim claim) { + GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot attempt = + attemptRepository.validateCurrentClaim(claim); + if (!"OWNER_EXECUTION_PENDING".equals(attempt.phaseState()) + || attempt.accountRedemptionProjection() == null + || !attempt.targetNamespace().equals(claim.targetNamespace()) + || !attempt.controlPlaneRequestId().equals(claim.controlPlaneRequestId()) + || !attempt.ownerAttemptId().equals(claim.ownerAttemptId()) + || attempt.ownerFence() != claim.ownerFence()) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Template association pin requires the exact pending, Account-attached owner attempt"); + } + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + attempt.postAuthorizationExecutionTuple()); + if (!Arrays.equals(tuple.canonicalBytes(), attempt.postAuthorizationExecutionTuple()) + || !tuple.controlPlaneRequestId().equals(attempt.controlPlaneRequestId()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(attempt.targetNamespace()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .equals(attempt.canonicalTenantId())) { + throw new IllegalStateException( + "Persisted StartSession owner attempt differs from its canonical post-authorization tuple"); + } + return attempt; + } + + private static void requireCandidateBoundToAttempt( + GameSessionStartSessionOperatorAttemptRepository.AttemptClaim claim, + GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot attempt, + Result candidate) { + Request request = candidate.request(); + if (!request.targetNamespace().equals(attempt.targetNamespace()) + || !request.ownerAttemptId().equals(attempt.ownerAttemptId()) + || request.ownerFence() != attempt.ownerFence() + || !Arrays.equals( + request.canonicalPostAuthorizationTuple(), attempt.postAuthorizationExecutionTuple()) + || !request.targetNamespace().equals(claim.targetNamespace()) + || !request.decodedTuple().controlPlaneRequestId().equals(claim.controlPlaneRequestId()) + || !candidate.association().canonicalTenantId().equals(attempt.canonicalTenantId())) { + throw new StartSessionTemplateAssociationConflictException( + "Game Design association differs from the exact current StartSession owner attempt"); + } + } + + private PinnedAssociationSnapshot decodeStored( + Record row, + String expectedNamespace, + String expectedRequestId, + GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot attempt) { + byte[] tupleBytes = requiredBytes(row, "post_authorization_execution_tuple"); + byte[] requestWire = requiredBytes(row, "association_request_wire"); + byte[] responseWire = requiredBytes(row, "association_response_wire"); + if (!requiredText(row, "target_namespace").equals(expectedNamespace) + || !requiredText(row, "control_plane_request_id").equals(expectedRequestId) + || !requiredUuid(row, "canonical_tenant_id").equals(attempt.canonicalTenantId()) + || !requiredUuid(row, "owner_attempt_id").equals(attempt.ownerAttemptId()) + || requiredLong(row, "owner_fence") != attempt.ownerFence() + || !Arrays.equals(tupleBytes, attempt.postAuthorizationExecutionTuple()) + || !requiredText(row, "post_authorization_tuple_digest").equals(sha256(tupleBytes)) + || !requiredText(row, "account_redemption_projection_digest") + .equals(sha256(attempt.accountRedemptionProjection())) + || !requiredText(row, "association_request_digest").equals(sha256(requestWire)) + || !requiredText(row, "association_response_digest").equals(sha256(responseWire))) { + throw new IllegalStateException( + "Persisted StartSession template association pin differs from its owner attempt"); + } + if (requestWire.length > MAX_REQUEST_WIRE_BYTES + || responseWire.length > MAX_RESPONSE_WIRE_BYTES) { + throw new IllegalStateException( + "Persisted template association carrier exceeds its byte limit"); + } + + try { + ReadStartSessionTemplateAssociationRequest requestMessage = + ReadStartSessionTemplateAssociationRequest.parseFrom(requestWire); + Request request = StartSessionTemplateAssociationReadGrpcCodec.fromRequest(requestMessage); + if (!(request.selection() instanceof InitialConfigured) + || !Arrays.equals( + StartSessionTemplateAssociationReadGrpcCodec.toRequest(request).toByteArray(), + requestWire)) { + throw new IllegalStateException( + "Persisted original association request is not a canonical initial selection"); + } + ReadStartSessionTemplateAssociationResponse responseMessage = + ReadStartSessionTemplateAssociationResponse.parseFrom(responseWire); + Result result = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse(request, responseMessage); + if (!Arrays.equals( + StartSessionTemplateAssociationReadGrpcCodec.toResponse(result).toByteArray(), + responseWire)) { + throw new IllegalStateException( + "Persisted association response is not canonically encoded"); + } + requireNormalizedColumnsMatch(row, result); + return new PinnedAssociationSnapshot( + result, + requiredText(row, "association_request_digest"), + requiredText(row, "association_response_digest"), + requiredInstant(row, "created_at")); + } catch (InvalidProtocolBufferException | IllegalArgumentException malformed) { + throw new IllegalStateException( + "Persisted StartSession template association evidence is malformed", malformed); + } + } + + private static void requireNormalizedColumnsMatch(Record row, Result result) { + Association association = result.association(); + if (!requiredText(row, "target_namespace").equals(association.targetNamespace()) + || !requiredUuid(row, "canonical_tenant_id").equals(association.canonicalTenantId()) + || requiredLong(row, "template_id") != association.templateId() + || !requiredUuid(row, "canonical_version_id").equals(association.canonicalVersionId()) + || !requiredUuid(row, "selected_commit_id").equals(association.selectedCommitId()) + || !requiredText(row, "publish_workflow_id").equals(association.publishWorkflowId()) + || !requiredText(row, "publication_selection_digest") + .equals(association.publicationSelectionDigest()) + || !requiredText(row, "association_digest").equals(association.associationDigest()) + || !requiredUuid(row, "world_intake_request_id").equals(association.intakeRequestId()) + || !requiredUuid(row, "world_operation_id").equals(association.worldOperationId()) + || !requiredUuid(row, "source_operation_id").equals(association.sourceOperationId()) + || !requiredText(row, "source_evidence_digest") + .equals(association.sourceEvidenceDigest())) { + throw new IllegalStateException( + "Persisted template association columns differ from the retained typed response"); + } + } + + private static void requireExactReplay(PinnedAssociationSnapshot original, Result candidate) { + Request request = candidate.request(); + Request originalRequest = original.result().request(); + Association pinned = original.result().association(); + if (!(request.selection() instanceof ExactReplay replay) + || !request.targetNamespace().equals(originalRequest.targetNamespace()) + || !Arrays.equals( + request.canonicalPostAuthorizationTuple(), + originalRequest.canonicalPostAuthorizationTuple()) + || !request.ownerAttemptId().equals(originalRequest.ownerAttemptId()) + || request.ownerFence() != originalRequest.ownerFence() + || !replay.canonicalVersionId().equals(pinned.canonicalVersionId()) + || !replay.selectedCommitId().equals(pinned.selectedCommitId()) + || !replay.publishWorkflowId().equals(pinned.publishWorkflowId()) + || !replay.associationDigest().equals(pinned.associationDigest()) + || !sameAssociation(pinned, candidate.association()) + || !original.result().releaseBundle().equals(candidate.releaseBundle()) + || !original + .result() + .worldPublishedStartLocationEvidence() + .equals(candidate.worldPublishedStartLocationEvidence())) { + throw new StartSessionTemplateAssociationConflictException( + "Exact replay differs from the original immutable template association selection"); + } + } + + private static boolean sameAssociation(Association left, Association right) { + var leftWorldRead = left.worldReadRequest(); + var rightWorldRead = right.worldReadRequest(); + return left.canonicalTenantId().equals(right.canonicalTenantId()) + && left.templateId() == right.templateId() + && left.canonicalVersionId().equals(right.canonicalVersionId()) + && left.selectedCommitId().equals(right.selectedCommitId()) + && left.publishWorkflowId().equals(right.publishWorkflowId()) + && left.publicationSelectionDigest().equals(right.publicationSelectionDigest()) + && left.associationDigest().equals(right.associationDigest()) + && left.targetNamespace().equals(right.targetNamespace()) + && left.intakeRequestId().equals(right.intakeRequestId()) + && left.worldOperationId().equals(right.worldOperationId()) + && left.sourceOperationId().equals(right.sourceOperationId()) + && left.worldSlug().equals(right.worldSlug()) + && left.sourceEvidenceDigest().equals(right.sourceEvidenceDigest()) + && leftWorldRead.schemaVersion() == rightWorldRead.schemaVersion() + && leftWorldRead.targetNamespace().equals(rightWorldRead.targetNamespace()) + && leftWorldRead.intakeRequestId().equals(rightWorldRead.intakeRequestId()) + && leftWorldRead.canonicalTenantId().equals(rightWorldRead.canonicalTenantId()) + && left.worldReceipt().equals(right.worldReceipt()); + } + + private Record selectPin(String namespace, String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + namespace, + requestId); + } + + private static void requireWireBound(byte[] requestWire, byte[] responseWire) { + if (requestWire.length == 0 + || responseWire.length == 0 + || requestWire.length > MAX_REQUEST_WIRE_BYTES + || responseWire.length > MAX_RESPONSE_WIRE_BYTES) { + throw new StartSessionTemplateAssociationConflictException( + "Template association carrier exceeds the local fail-closed storage budget"); + } + } + + private static String sha256(byte[] value) { + Objects.requireNonNull(value, "digest input is required"); + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static String requiredText(Record row, String field) { + String value = row == null ? null : row.get(field, String.class); + if (value == null) + throw new IllegalStateException("Persisted association pin is missing " + field); + return value; + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row == null ? null : row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalStateException("Persisted association pin is missing " + field); + } + return value; + } + + private static long requiredLong(Record row, String field) { + Long value = row == null ? null : row.get(field, Long.class); + if (value == null) + throw new IllegalStateException("Persisted association pin is missing " + field); + return value; + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row == null ? null : row.get(field, byte[].class); + if (value == null) + throw new IllegalStateException("Persisted association pin is missing " + field); + return value.clone(); + } + + private static Instant requiredInstant(Record row, String field) { + java.time.OffsetDateTime value = + row == null ? null : row.get(field, java.time.OffsetDateTime.class); + if (value == null) + throw new IllegalStateException("Persisted association pin is missing " + field); + return value.toInstant(); + } + + /** Original immutable typed selection and exact-wire digests; no owner credential is exposed. */ + public record PinnedAssociationSnapshot( + Result result, String requestDigest, String responseDigest, Instant createdAt) { + public PinnedAssociationSnapshot { + Objects.requireNonNull(result, "result is required"); + Objects.requireNonNull(requestDigest, "requestDigest is required"); + Objects.requireNonNull(responseDigest, "responseDigest is required"); + Objects.requireNonNull(createdAt, "createdAt is required"); + } + } + + public static final class StartSessionTemplateAssociationConflictException + extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public StartSessionTemplateAssociationConflictException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java new file mode 100644 index 0000000000..bf3aa9a4bb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; + +/** Immutable Game Session-local mapping to exact authenticated fresh Game Design identity. */ +public record FreshGameSessionTenantAssociation( + UUID associationOperationId, + long legacyGameSessionTenantId, + RuntimeTenantIdentityEvidence sourceEvidence) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public FreshGameSessionTenantAssociation { + if (associationOperationId == null || NIL_UUID.equals(associationOperationId)) { + throw new IllegalArgumentException("associationOperationId must be a non-nil UUID"); + } + if (legacyGameSessionTenantId <= 0) { + throw new IllegalArgumentException("legacyGameSessionTenantId must be positive"); + } + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + if (!"NEW_GAME_ROW".equals(sourceEvidence.provenanceKind())) { + throw new IllegalArgumentException("Fresh association requires NEW_GAME_ROW provenance"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java new file mode 100644 index 0000000000..d9f540580f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java @@ -0,0 +1,210 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorReadClient; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository.PinnedLaunchDescriptorSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.EvidenceContinuation; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered continuation of one existing StartSession association and descriptor projection. + * Account revalidates the original redeemed operation, and Game Design independently authorizes the + * descriptor read; this service creates no mutation or runtime admission authority. + */ +public final class GameSessionStartSessionLaunchDescriptorContinuationService { + private final GameSessionStartSessionOperatorAttemptRepository attemptRepository; + private final GameSessionStartSessionTemplateAssociationRepository associationRepository; + private final GameSessionStartSessionLaunchDescriptorRepository descriptorRepository; + private final StartSessionRedeemedOperationProjectionClient accountProjectionClient; + private final StartSessionLaunchDescriptorReadClient descriptorReadClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public GameSessionStartSessionLaunchDescriptorContinuationService( + GameSessionStartSessionOperatorAttemptRepository attemptRepository, + GameSessionStartSessionTemplateAssociationRepository associationRepository, + GameSessionStartSessionLaunchDescriptorRepository descriptorRepository, + StartSessionRedeemedOperationProjectionClient accountProjectionClient, + StartSessionLaunchDescriptorReadClient descriptorReadClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.attemptRepository = + Objects.requireNonNull(attemptRepository, "attemptRepository is required"); + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository is required"); + this.descriptorRepository = + Objects.requireNonNull(descriptorRepository, "descriptorRepository is required"); + this.accountProjectionClient = + Objects.requireNonNull(accountProjectionClient, "accountProjectionClient is required"); + this.descriptorReadClient = + Objects.requireNonNull(descriptorReadClient, "descriptorReadClient is required"); + Objects.requireNonNull(transactionManager, "transactionManager is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Revalidates the same live original attempt and Account projection, reads its existing + * selection, calls Account and Game Design outside SQL, and then pins only the exact returned + * descriptor outcome. + */ + public PinnedLaunchDescriptorSnapshot continueOriginalEvidence( + StartSessionPostAuthorizationExecutionTuple tuple) { + Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); + requireNoAmbientTransaction(); + if (!workloadNamespace.equals( + tuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw new EvidenceContinuationUnavailableException( + "StartSession continuation tuple is outside the configured Game Session namespace"); + } + + ContinuationPlan plan = + ownerTransaction.execute( + status -> { + EvidenceContinuation continuation = + attemptRepository.beginEvidenceContinuation(tuple); + PinnedAssociationSnapshot association = + associationRepository + .findPinned(continuation) + .orElseThrow( + () -> + new EvidenceContinuationUnavailableException( + "Original selection is missing; this attempt remains reconciliation-only")); + return new ContinuationPlan( + continuation, association, exactReplayRequest(association.result())); + }); + if (plan == null) { + throw new IllegalStateException("StartSession continuation transaction returned no plan"); + } + + Request originalRequest = plan.association().result().request(); + requireOriginalRequestBinding(tuple, originalRequest); + + requireNoAmbientTransaction(); + ReadRedeemedOperationProjectionResponse originalProjection = + accountProjectionClient.read( + tuple, originalRequest.ownerAttemptId(), originalRequest.ownerFence()); + requireNoAmbientTransaction(); + + var resolved = descriptorReadClient.resolve(plan.request()); + requireNoAmbientTransaction(); + + ReadRedeemedOperationProjectionResponse currentProjection = + accountProjectionClient.read( + tuple, originalRequest.ownerAttemptId(), originalRequest.ownerFence()); + requireNoAmbientTransaction(); + requireSameAccountProjection(originalProjection, currentProjection); + + PinnedLaunchDescriptorSnapshot pinned = + ownerTransaction.execute( + status -> { + PinnedAssociationSnapshot current = + associationRepository + .findPinned(plan.continuation()) + .orElseThrow( + () -> + new EvidenceContinuationUnavailableException( + "Original selection disappeared during descriptor resolution")); + requireSameSelection(plan.association(), current); + return descriptorRepository.pin(plan.continuation(), resolved); + }); + if (pinned == null) { + throw new IllegalStateException("StartSession descriptor pin transaction returned no result"); + } + return pinned; + } + + private static Request exactReplayRequest(Result original) { + var association = original.association(); + var request = original.request(); + return new Request( + request.schemaVersion(), + request.targetNamespace(), + request.readRequestId(), + request.canonicalPostAuthorizationTuple(), + request.ownerAttemptId(), + request.ownerFence(), + new ExactReplay( + association.canonicalVersionId(), + association.selectedCommitId(), + association.publishWorkflowId(), + association.associationDigest())); + } + + private static void requireSameSelection( + PinnedAssociationSnapshot originallyRead, PinnedAssociationSnapshot current) { + if (!originallyRead.requestDigest().equals(current.requestDigest()) + || !originallyRead.responseDigest().equals(current.responseDigest()) + || !Arrays.equals( + StartSessionTemplateAssociationReadGrpcCodec.toResponse(originallyRead.result()) + .toByteArray(), + StartSessionTemplateAssociationReadGrpcCodec.toResponse(current.result()) + .toByteArray())) { + throw new GameSessionStartSessionLaunchDescriptorRepository + .StartSessionLaunchDescriptorConflictException( + "Original immutable selection changed during descriptor continuation"); + } + } + + private void requireOriginalRequestBinding( + StartSessionPostAuthorizationExecutionTuple tuple, Request request) { + if (!workloadNamespace.equals(request.targetNamespace()) + || !Arrays.equals(tuple.canonicalBytes(), request.canonicalPostAuthorizationTuple()) + || request.ownerAttemptId() == null + || request.ownerAttemptId().equals(new java.util.UUID(0L, 0L)) + || request.ownerFence() <= 0L) { + throw new EvidenceContinuationUnavailableException( + "Original pinned selection does not bind the exact tuple and owner attempt"); + } + } + + private static void requireSameAccountProjection( + ReadRedeemedOperationProjectionResponse original, + ReadRedeemedOperationProjectionResponse current) { + if (!Arrays.equals(original.toByteArray(), current.toByteArray())) { + throw new EvidenceContinuationUnavailableException( + "Account's original redeemed operation projection changed during descriptor continuation"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Remote Account and Game Design reads must occur outside owner SQL transactions"); + } + } + + private record ContinuationPlan( + EvidenceContinuation continuation, PinnedAssociationSnapshot association, Request request) {} + + public static final class EvidenceContinuationUnavailableException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public EvidenceContinuationUnavailableException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql b/services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql new file mode 100644 index 0000000000..bd673c1876 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql @@ -0,0 +1,100 @@ +-- Game Session's non-replayable owner-side reservation for a complete authorized StartSession. +-- This table is intentionally not a runtime-activation or business-mutation switch. +-- [jooq ignore start] +CREATE SEQUENCE game_session_start_session_operator_owner_fence_seq + AS BIGINT START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE NO CYCLE; + +CREATE TABLE game_session_start_session_operator_attempt ( + target_namespace VARCHAR(63) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_tenant_id UUID NOT NULL, + owner_attempt_id UUID NOT NULL, + owner_mutation_id UUID NOT NULL, + claim_owner_id UUID NOT NULL, + owner_fence BIGINT NOT NULL, + post_authorization_execution_tuple BYTEA NOT NULL, + mutation_digest VARCHAR(64) NOT NULL, + authorization_reference_fingerprint VARCHAR(137) NOT NULL, + phase_state VARCHAR(48) NOT NULL DEFAULT 'OWNER_EXECUTION_PENDING', + account_redemption_projection BYTEA, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + lease_expires_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_gs_start_session_operator_attempt + PRIMARY KEY (target_namespace, control_plane_request_id), + CONSTRAINT uq_gs_start_session_operator_attempt_id UNIQUE (owner_attempt_id), + CONSTRAINT uq_gs_start_session_operator_mutation_id UNIQUE (owner_mutation_id), + CONSTRAINT uq_gs_start_session_operator_fence UNIQUE (owner_fence), + CONSTRAINT chk_gs_start_session_operator_attempt_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND octet_length(control_plane_request_id) BETWEEN 1 AND 128 + AND control_plane_request_id !~ '^[[:space:]]*$' + AND control_plane_request_id !~ '[[:cntrl:]]' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND claim_owner_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_fence > 0 + AND lease_expires_at > created_at), + CONSTRAINT chk_gs_start_session_operator_attempt_tuple CHECK ( + octet_length(post_authorization_execution_tuple) BETWEEN 1 AND 262144 + AND mutation_digest ~ '^[0-9a-f]{64}$' + AND authorization_reference_fingerprint + ~ '^arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}$'), + CONSTRAINT chk_gs_start_session_operator_attempt_pending CHECK ( + phase_state = 'OWNER_EXECUTION_PENDING' + AND (account_redemption_projection IS NULL + OR octet_length(account_redemption_projection) BETWEEN 1 AND 262144)) +); + +CREATE FUNCTION enforce_game_session_start_session_operator_attempt_immutable() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Session StartSession owner attempts are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.account_redemption_projection IS NOT NULL + OR NEW.account_redemption_projection IS NULL + OR NEW.target_namespace IS DISTINCT FROM OLD.target_namespace + OR NEW.control_plane_request_id IS DISTINCT FROM OLD.control_plane_request_id + OR NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.owner_attempt_id IS DISTINCT FROM OLD.owner_attempt_id + OR NEW.owner_mutation_id IS DISTINCT FROM OLD.owner_mutation_id + OR NEW.claim_owner_id IS DISTINCT FROM OLD.claim_owner_id + OR NEW.owner_fence IS DISTINCT FROM OLD.owner_fence + OR NEW.post_authorization_execution_tuple IS DISTINCT FROM OLD.post_authorization_execution_tuple + OR NEW.mutation_digest IS DISTINCT FROM OLD.mutation_digest + OR NEW.authorization_reference_fingerprint IS DISTINCT FROM OLD.authorization_reference_fingerprint + OR NEW.phase_state IS DISTINCT FROM OLD.phase_state + OR NEW.created_at IS DISTINCT FROM OLD.created_at + OR NEW.lease_expires_at IS DISTINCT FROM OLD.lease_expires_at THEN + RAISE EXCEPTION 'Game Session StartSession owner attempt evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_start_session_operator_attempt_immutable + BEFORE UPDATE OR DELETE ON game_session_start_session_operator_attempt + FOR EACH ROW EXECUTE FUNCTION enforce_game_session_start_session_operator_attempt_immutable(); + +CREATE FUNCTION reject_game_session_start_session_operator_attempt_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session StartSession owner attempts cannot be truncated' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER game_session_start_session_operator_attempt_no_truncate + BEFORE TRUNCATE ON game_session_start_session_operator_attempt + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_start_session_operator_attempt_truncate(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V37__start_session_template_association_pin.sql b/services/game-session-service/src/main/resources/db/migration/V37__start_session_template_association_pin.sql new file mode 100644 index 0000000000..5622d4b2b3 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V37__start_session_template_association_pin.sql @@ -0,0 +1,93 @@ +-- Pin one normalized Game Design template association to the original StartSession owner attempt. +-- This immutable evidence does not grant authority, select a descriptor, or activate a runtime. +-- Request storage is the 256 KiB canonical tuple plus 1 KiB closed-request overhead; response +-- storage has a local 4 MiB fail-closed budget and makes no claim about gRPC transport capacity. +-- [jooq ignore start] +CREATE UNIQUE INDEX uq_gs_start_session_operator_attempt_pin_binding + ON game_session_start_session_operator_attempt + (target_namespace, control_plane_request_id, owner_attempt_id, owner_fence, canonical_tenant_id); + +CREATE TABLE game_session_start_session_template_association_pin ( + target_namespace VARCHAR(63) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_tenant_id UUID NOT NULL, + owner_attempt_id UUID NOT NULL, + owner_fence BIGINT NOT NULL, + post_authorization_execution_tuple BYTEA NOT NULL, + post_authorization_tuple_digest VARCHAR(71) NOT NULL, + account_redemption_projection_digest VARCHAR(71) NOT NULL, + association_request_wire BYTEA NOT NULL, + association_response_wire BYTEA NOT NULL, + association_request_digest VARCHAR(71) NOT NULL, + association_response_digest VARCHAR(71) NOT NULL, + template_id BIGINT NOT NULL, + canonical_version_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + publish_workflow_id VARCHAR(256) NOT NULL, + publication_selection_digest VARCHAR(71) NOT NULL, + association_digest VARCHAR(71) NOT NULL, + world_intake_request_id UUID NOT NULL, + world_operation_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT pk_gs_start_session_template_association_pin + PRIMARY KEY (target_namespace, control_plane_request_id), + CONSTRAINT uq_gs_start_session_template_association_attempt UNIQUE (owner_attempt_id), + CONSTRAINT fk_gs_start_session_template_association_attempt + FOREIGN KEY ( + target_namespace, + control_plane_request_id, + owner_attempt_id, + owner_fence, + canonical_tenant_id) + REFERENCES game_session_start_session_operator_attempt + (target_namespace, control_plane_request_id, owner_attempt_id, owner_fence, canonical_tenant_id), + CONSTRAINT chk_gs_start_session_template_association_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND octet_length(control_plane_request_id) BETWEEN 1 AND 128 + AND control_plane_request_id !~ '^[[:space:]]*$' + AND control_plane_request_id !~ '[[:cntrl:]]' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_fence > 0 + AND template_id > 0 + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND btrim(publish_workflow_id) <> '' + AND octet_length(publish_workflow_id) <= 256 + AND world_intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_start_session_template_association_evidence CHECK ( + octet_length(post_authorization_execution_tuple) BETWEEN 1 AND 262144 + AND octet_length(association_request_wire) BETWEEN 1 AND 263168 + AND octet_length(association_response_wire) BETWEEN 1 AND 4194304 + AND post_authorization_tuple_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_redemption_projection_digest ~ '^sha256:[0-9a-f]{64}$' + AND association_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND association_response_digest ~ '^sha256:[0-9a-f]{64}$' + AND publication_selection_digest ~ '^sha256:[0-9a-f]{64}$' + AND association_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE FUNCTION reject_gs_start_session_template_association_pin_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'StartSession template association pins are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER gs_start_session_template_association_pin_immutable +BEFORE UPDATE OR DELETE ON game_session_start_session_template_association_pin +FOR EACH ROW EXECUTE FUNCTION reject_gs_start_session_template_association_pin_mutation(); + +CREATE TRIGGER gs_start_session_template_association_pin_no_truncate +BEFORE TRUNCATE ON game_session_start_session_template_association_pin +FOR EACH STATEMENT EXECUTE FUNCTION reject_gs_start_session_template_association_pin_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql b/services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql new file mode 100644 index 0000000000..b6ecb674ee --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql @@ -0,0 +1,61 @@ +-- Pin one exact-replay Game Design descriptor outcome to the already retained StartSession +-- association. This immutable evidence grants no World hold, runtime admission, or activation. +-- Request storage is the bounded canonical tuple plus 1 KiB closed-request overhead. Response +-- storage has a local 8 MiB fail-closed budget and makes no claim about gRPC transport capacity. +-- [jooq ignore start] +CREATE TABLE game_session_start_session_launch_descriptor_pin ( + target_namespace VARCHAR(63) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_tenant_id UUID NOT NULL, + owner_attempt_id UUID NOT NULL, + owner_fence BIGINT NOT NULL, + association_request_digest VARCHAR(71) NOT NULL, + association_response_digest VARCHAR(71) NOT NULL, + descriptor_request_wire BYTEA NOT NULL, + descriptor_response_wire BYTEA NOT NULL, + descriptor_request_digest VARCHAR(71) NOT NULL, + descriptor_response_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT pk_gs_start_session_launch_descriptor_pin + PRIMARY KEY (target_namespace, control_plane_request_id), + CONSTRAINT uq_gs_start_session_launch_descriptor_attempt UNIQUE (owner_attempt_id), + CONSTRAINT fk_gs_start_session_launch_descriptor_association + FOREIGN KEY (target_namespace, control_plane_request_id) + REFERENCES game_session_start_session_template_association_pin + (target_namespace, control_plane_request_id), + CONSTRAINT chk_gs_start_session_launch_descriptor_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND octet_length(control_plane_request_id) BETWEEN 1 AND 128 + AND control_plane_request_id !~ '^[[:space:]]*$' + AND control_plane_request_id !~ '[[:cntrl:]]' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_fence > 0), + CONSTRAINT chk_gs_start_session_launch_descriptor_evidence CHECK ( + octet_length(descriptor_request_wire) BETWEEN 1 AND 263168 + AND octet_length(descriptor_response_wire) BETWEEN 1 AND 8388608 + AND association_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND association_response_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_response_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE FUNCTION reject_gs_start_session_launch_descriptor_pin_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'StartSession launch descriptor pins are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER gs_start_session_launch_descriptor_pin_immutable +BEFORE UPDATE OR DELETE ON game_session_start_session_launch_descriptor_pin +FOR EACH ROW EXECUTE FUNCTION reject_gs_start_session_launch_descriptor_pin_mutation(); + +CREATE TRIGGER gs_start_session_launch_descriptor_pin_no_truncate +BEFORE TRUNCATE ON game_session_start_session_launch_descriptor_pin +FOR EACH STATEMENT EXECUTE FUNCTION reject_gs_start_session_launch_descriptor_pin_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java new file mode 100644 index 0000000000..ef984cca2e --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java @@ -0,0 +1,386 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository.LaunchAssociationOwnerReadMismatchException; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository.OriginalStartSessionAssociation; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.StartingInstance; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof that the World handoff is bound to the original retained StartSession owner. + * Uses existing typed repository fixtures; it is not Account/World producer or through-commit + * authority proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionOriginalStartSessionAssociationReadIntegrationTest { + private static final UUID CANONICAL_VERSION = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void readsOnlyTheExactRetainedAssociationAndDescriptorForTheOriginalPendingAttempt() { + StartSessionPostAuthorizationExecutionTuple tuple = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple( + "original-association-handoff-positive"); + Fixture fixture = fixture(tuple, Duration.ofSeconds(30)); + OwnerBackedStarting starting = fixture.startWithOwnerPins(tuple); + + OriginalStartSessionAssociation read = + fixture.read(selector(starting.startingInstance().launchAssociation())).orElseThrow(); + + assertThat(read.association()).isEqualTo(starting.startingInstance().launchAssociation()); + assertThat(read.ownerAttemptId()).isEqualTo(starting.claim().ownerAttemptId()); + assertThat(read.ownerFence()).isEqualTo(starting.claim().ownerFence()).isPositive(); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_session_start_session_template_association_pin")))) + .isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_session_start_session_launch_descriptor_pin")))) + .isEqualTo(1); + } + + @Test + void absentOriginalAttemptAndPinsDoNotExposeTheStartingAssociation() { + StartSessionPostAuthorizationExecutionTuple tuple = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple( + "original-association-handoff-no-owner"); + Fixture fixture = fixture(tuple, Duration.ofSeconds(30)); + StartingInstance starting = fixture.startWithoutOwnerPins(tuple); + + assertThat(fixture.read(selector(starting.launchAssociation()))).isEmpty(); + } + + @Test + void changedDescriptorSelectorFailsClosedAgainstTheRetainedOwnerRead() { + StartSessionPostAuthorizationExecutionTuple tuple = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple( + "original-association-handoff-mismatch"); + Fixture fixture = fixture(tuple, Duration.ofSeconds(30)); + OwnerBackedStarting starting = fixture.startWithOwnerPins(tuple); + var exact = selector(starting.startingInstance().launchAssociation()); + var changed = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + exact.readRequestId(), + exact.targetNamespace(), + exact.canonicalTenantId(), + exact.worldSlug(), + exact.gameInstanceUuid(), + exact.controlPlaneRequestId(), + exact.launchDescriptorId(), + exact.expectedDescriptorRequestDigest(), + "sha256:" + "c".repeat(64), + exact.expectedReleaseAttestationEvidenceDigest()); + + assertThatThrownBy(() -> fixture.read(changed)) + .isInstanceOf(LaunchAssociationOwnerReadMismatchException.class); + } + + @Test + void expiredOwnerLeaseHidesOtherwiseRetainedAssociationEvidence() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple( + "original-association-handoff-expired"); + Fixture fixture = fixture(tuple, Duration.ofSeconds(5)); + OwnerBackedStarting starting = fixture.startWithOwnerPins(tuple); + Thread.sleep(5_250L); + + assertThat(fixture.read(selector(starting.startingInstance().launchAssociation()))).isEmpty(); + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector( + net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation association) { + var binding = association.launchBindingEvidence(); + var descriptor = binding.descriptor(); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + association.targetNamespace(), + association.canonicalTenantId(), + association.worldSlug(), + association.gameInstanceUuid(), + association.controlPlaneRequestId(), + association.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + binding.releaseAttestation().evidenceDigest()); + } + + private static CompleteLaunchBindingEvidence completeBinding( + AuthoredWorldLaunchDescriptorEvidence descriptor, UUID canonicalVersionId) { + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + "original-association-commit", + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + canonicalVersionId, + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "original-association-publish", + "original-association-commit", + participants, + "sha256:" + "e".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, release); + } + + private static AuthoredWorldLaunchDescriptorEvidence unpinnedDescriptor( + StartSessionPostAuthorizationExecutionTuple tuple, AuthoredWorldSourceEvidence source) { + var action = tuple.preAuthorizationTuple().action(); + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + action.scope().targetNamespace(), + tuple.controlPlaneRequestId(), + action.scope().tenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + action.target().gameTemplateId(), + false, + null, + false, + null, + false, + null, + true, + "{}"); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "unowned-start-session-descriptor", + 19L, + false, + null, + "{}", + "generation-1", + 5L, + 91L, + "immutable-release-ref", + false, + null); + } + + private static Fixture fixture( + StartSessionPostAuthorizationExecutionTuple tuple, Duration ownerClaimLease) { + String namespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + UUID tenantId = tuple.preAuthorizationTuple().action().scope().tenantId(); + String schema = "gs_original_assoc_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var attempts = new GameSessionStartSessionOperatorAttemptRepository(dsl, ownerClaimLease); + var templateAssociations = + new GameSessionStartSessionTemplateAssociationRepository(dsl, attempts); + var descriptors = + new GameSessionStartSessionLaunchDescriptorRepository(dsl, templateAssociations); + var sourceRepository = new GameSessionAuthoredWorldSourceRepository(dsl); + var tenantRepository = new GameSessionFreshTenantAssociationRepository(dsl); + var catalogRepository = new GameSessionCanonicalRealmCatalogRepository(dsl); + var startingRepository = new GameSessionCanonicalStartingInstanceRepository(dsl, namespace); + var source = GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.source(); + if (!source.targetNamespace().equals(namespace) + || !source.canonicalTenantId().equals(tenantId)) { + throw new IllegalStateException("Shared StartSession source fixture differs from its tuple"); + } + var sourceReceipt = + Objects.requireNonNull( + transactions.execute(status -> sourceRepository.register(UUID.randomUUID(), source)), + "registered fresh source receipt"); + var createCatalog = + new CreateCanonicalRealmCatalogRequest( + UUID.randomUUID(), + namespace, + tenantId, + sourceReceipt.operationId(), + source.worldSlug(), + source.worldDisplayName(), + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var preparedCatalog = catalogRepository.prepareInitialPublicProduction(createCatalog); + transactions.executeWithoutResult( + status -> catalogRepository.createInitialPublicProduction(preparedCatalog)); + FreshGameSessionTenantAssociation tenantAssociation = + Objects.requireNonNull( + transactions.execute( + status -> + tenantRepository.associateFresh(UUID.randomUUID(), namespace, sourceReceipt)), + "fresh tenant association"); + return new Fixture( + namespace, + tenantId, + dsl, + transactions, + attempts, + templateAssociations, + descriptors, + startingRepository, + new CanonicalGameInstanceLaunchAssociationRepository(dsl, namespace), + source, + tenantAssociation); + } + + private record Fixture( + String namespace, + UUID tenantId, + DSLContext dsl, + TransactionTemplate transactions, + GameSessionStartSessionOperatorAttemptRepository attempts, + GameSessionStartSessionTemplateAssociationRepository templateAssociations, + GameSessionStartSessionLaunchDescriptorRepository descriptors, + GameSessionCanonicalStartingInstanceRepository starting, + CanonicalGameInstanceLaunchAssociationRepository reads, + AuthoredWorldSourceEvidence source, + FreshGameSessionTenantAssociation tenantAssociation) { + OwnerBackedStarting startWithOwnerPins(StartSessionPostAuthorizationExecutionTuple tuple) { + ReservationResult reservation = + Objects.requireNonNull(transactions.execute(status -> attempts.reserve(tuple))); + AttemptClaim claim = reservation.claim().orElseThrow(); + var projection = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.projection(tuple); + transactions.executeWithoutResult( + status -> attempts.attachAccountRedemptionProjection(claim, projection)); + var initial = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.result( + tuple, claim, new InitialConfigured(), UUID.randomUUID()); + PinnedAssociationSnapshot pinnedAssociation = + Objects.requireNonNull( + transactions.execute( + status -> templateAssociations.pinInitialOrValidateExactReplay(claim, initial))); + var resolved = + GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.descriptorFor( + pinnedAssociation.result(), "original-start-session-descriptor"); + transactions.executeWithoutResult(status -> descriptors.pin(claim, resolved)); + var descriptor = + ((net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec + .DescriptorOutcome) + resolved.outcome()) + .descriptor(); + var binding = + completeBinding( + descriptor, pinnedAssociation.result().association().canonicalVersionId()); + StartingInstance startingInstance = + Objects.requireNonNull( + transactions.execute( + status -> + starting.createStarting( + tenantAssociation, + binding, + tuple.preAuthorizationTuple().action().target().ownerAccountId(), + tuple.controlPlaneRequestId(), + "f".repeat(64)))); + return new OwnerBackedStarting(startingInstance, claim); + } + + StartingInstance startWithoutOwnerPins(StartSessionPostAuthorizationExecutionTuple tuple) { + var descriptor = unpinnedDescriptor(tuple, source); + var binding = completeBinding(descriptor, CANONICAL_VERSION); + return Objects.requireNonNull( + transactions.execute( + status -> + starting.createStarting( + tenantAssociation, + binding, + tuple.preAuthorizationTuple().action().target().ownerAccountId(), + tuple.controlPlaneRequestId(), + "f".repeat(64)))); + } + + java.util.Optional read( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector) { + return reads.readOriginalStartSessionAssociation(selector); + } + } + + private record OwnerBackedStarting(StartingInstance startingInstance, AttemptClaim claim) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java new file mode 100644 index 0000000000..381384c2f7 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java @@ -0,0 +1,618 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +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.account.v1.AuthorityEvidenceBundleReference; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorReadClient; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository.PinnedLaunchDescriptorSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.EvidenceContinuation; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionLaunchDescriptorContinuationService; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionLaunchDescriptorContinuationService.EvidenceContinuationUnavailableException; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof that a descriptor outcome is immutable and tied to the original association. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void pinsCanonicalDescriptorAndExactRepeatReturnsOriginalWireEvidence() { + Fixture fixture = fixture(); + var retained = retainAssociation(fixture, "descriptor-pin-success"); + var candidate = descriptor(retained, "original-descriptor"); + + PinnedLaunchDescriptorSnapshot first = fixture.pin(retained.claim(), candidate); + PinnedLaunchDescriptorSnapshot replay = fixture.pin(retained.claim(), candidate); + Result association = candidate.associationRead(); + var laterPhaseResult = + new Result( + association.request(), + association.association(), + association.releaseBundle(), + association.worldPublishedStartLocationEvidence(), + association.phaseEpoch() + 1); + var laterPhaseReplay = + new StartSessionLaunchDescriptorGrpcCodec.Resolved(laterPhaseResult, candidate.outcome()); + PinnedLaunchDescriptorSnapshot phaseReplay = fixture.pin(retained.claim(), laterPhaseReplay); + PinnedLaunchDescriptorSnapshot read = fixture.find(retained.claim()).orElseThrow(); + + assertThat(first.requestWire()) + .isEqualTo(replay.requestWire()) + .isEqualTo(phaseReplay.requestWire()) + .isEqualTo(read.requestWire()); + assertThat(first.responseWire()) + .isEqualTo(replay.responseWire()) + .isEqualTo(phaseReplay.responseWire()) + .isEqualTo(read.responseWire()); + assertThat(read.resolved()).isEqualTo(candidate); + assertThat(fixture.pinCount()).isEqualTo(1); + + assertThatThrownBy( + () -> fixture.pin(retained.claim(), descriptor(retained, "substituted-descriptor"))) + .isInstanceOf( + GameSessionStartSessionLaunchDescriptorRepository + .StartSessionLaunchDescriptorConflictException.class) + .hasMessageContaining("original immutable StartSession pin"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_start_session_launch_descriptor_pin " + + "SET descriptor_response_digest = ? WHERE target_namespace = ? " + + "AND control_plane_request_id = ?", + "sha256:" + "c".repeat(64), + retained.claim().targetNamespace(), + retained.claim().controlPlaneRequestId())) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.pinCount()).isEqualTo(1); + } + + @Test + void pinsAClosedApplicationFailureAsTheFinalDescriptorOutcome() { + Fixture fixture = fixture(); + var retained = retainAssociation(fixture, "descriptor-pin-application-failure"); + Request exactRequest = exactReplayRequest(retained.association().result()); + Result exactAssociation = exactReplayAssociation(retained.association().result(), exactRequest); + var outcome = + new StartSessionLaunchDescriptorGrpcCodec.ApplicationFailure( + "RELEASE_BUNDLE_NOT_FOUND", "RELEASE_BUNDLE_NOT_FOUND: release is unavailable"); + var candidate = new StartSessionLaunchDescriptorGrpcCodec.Resolved(exactAssociation, outcome); + + PinnedLaunchDescriptorSnapshot pinned = fixture.pin(retained.claim(), candidate); + PinnedLaunchDescriptorSnapshot read = fixture.find(retained.claim()).orElseThrow(); + + assertThat(pinned.resolved().outcome()).isEqualTo(outcome); + assertThat(read.responseWire()).isEqualTo(pinned.responseWire()); + assertThat(fixture.pinCount()).isEqualTo(1); + } + + @Test + void continuationCapabilityCanBeRecreatedFromPersistedAttemptWithoutReselecting() { + Fixture fixture = fixture(); + RetainedAssociation retained = retainAssociation(fixture, "descriptor-continuation-restart"); + var candidate = descriptor(retained, "restart-descriptor"); + EvidenceContinuation originalCapability = fixture.continueEvidence(retained.tuple()); + + PinnedLaunchDescriptorSnapshot first = fixture.pin(originalCapability, candidate); + EvidenceContinuation recreatedCapability = fixture.continueEvidence(retained.tuple()); + PinnedLaunchDescriptorSnapshot replay = fixture.pin(recreatedCapability, candidate); + + assertThat(recreatedCapability).isNotSameAs(originalCapability); + assertThat(replay.requestWire()).isEqualTo(first.requestWire()); + assertThat(replay.responseWire()).isEqualTo(first.responseWire()); + assertThat(replay.resolved()).isEqualTo(first.resolved()); + assertThat(fixture.pinCount()).isEqualTo(1); + } + + @Test + void continuationCannotPinAReselectedAssociationDigest() { + Fixture fixture = fixture(); + RetainedAssociation retained = + retainAssociation(fixture, "descriptor-continuation-reselection"); + EvidenceContinuation continuation = fixture.continueEvidence(retained.tuple()); + var original = descriptor(retained, "reselection-descriptor"); + var originalAssociation = original.associationRead(); + Association selected = originalAssociation.association(); + Association substituted = + new Association( + selected.canonicalTenantId(), + selected.templateId(), + selected.canonicalVersionId(), + selected.selectedCommitId(), + selected.publishWorkflowId(), + selected.publicationSelectionDigest(), + "sha256:" + "c".repeat(64), + selected.targetNamespace(), + selected.intakeRequestId(), + selected.worldOperationId(), + selected.sourceOperationId(), + selected.worldSlug(), + selected.sourceEvidenceDigest(), + selected.worldReadRequest(), + selected.worldReceipt()); + Request originalRequest = originalAssociation.request(); + Request substitutedRequest = + new Request( + originalRequest.schemaVersion(), + originalRequest.targetNamespace(), + originalRequest.readRequestId(), + originalRequest.canonicalPostAuthorizationTuple(), + originalRequest.ownerAttemptId(), + originalRequest.ownerFence(), + new ExactReplay( + substituted.canonicalVersionId(), + substituted.selectedCommitId(), + substituted.publishWorkflowId(), + substituted.associationDigest())); + Result substitutedAssociation = + new Result( + substitutedRequest, + substituted, + originalAssociation.releaseBundle(), + originalAssociation.worldPublishedStartLocationEvidence(), + originalAssociation.phaseEpoch()); + + assertThatThrownBy( + () -> + fixture.pin( + continuation, + new StartSessionLaunchDescriptorGrpcCodec.Resolved( + substitutedAssociation, original.outcome()))) + .isInstanceOf( + GameSessionStartSessionLaunchDescriptorRepository + .StartSessionLaunchDescriptorConflictException.class) + .hasMessageContaining("retained exact"); + assertThat(fixture.pinCount()).isZero(); + } + + @Test + void expiredContinuationCannotCreateDescriptorPin() throws Exception { + Fixture fixture = fixture(Duration.ofSeconds(5)); + RetainedAssociation retained = retainAssociation(fixture, "descriptor-continuation-expired"); + EvidenceContinuation continuation = fixture.continueEvidence(retained.tuple()); + var candidate = descriptor(retained, "expired-descriptor"); + Thread.sleep(5_250L); + + assertThatThrownBy(() -> fixture.pin(continuation, candidate)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired"); + assertThat(fixture.pinCount()).isZero(); + } + + @Test + void concurrentContinuationOutcomesConvergeOnOneImmutableDescriptorOrConflict() throws Exception { + Fixture fixture = fixture(); + RetainedAssociation retained = retainAssociation(fixture, "descriptor-continuation-race"); + var firstCandidate = descriptor(retained, "race-first-descriptor"); + var secondCandidate = descriptor(retained, "race-second-descriptor"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> continueAndPin(fixture, retained, firstCandidate, ready, start)); + Future second = + executor.submit(() -> continueAndPin(fixture, retained, secondCandidate, ready, start)); + assertThat(ready.await(15, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + assertThat(fixture.pinCount()).isEqualTo(1); + assertThat(fixture.find(fixture.continueEvidence(retained.tuple()))).isPresent(); + } finally { + executor.shutdownNow(); + } + } + + @Test + void continuationServiceRequiresAnExistingPinAndDoesNotPinWhenGameDesignReadFails() { + Fixture unselected = fixture(); + StartSessionPostAuthorizationExecutionTuple unselectedTuple = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple( + "descriptor-continuation-no-selection"); + unselected.reserveAndAttach(unselectedTuple); + StartSessionRedeemedOperationProjectionClient unusedAccountClient = + mock(StartSessionRedeemedOperationProjectionClient.class); + StartSessionLaunchDescriptorReadClient unusedClient = + mock(StartSessionLaunchDescriptorReadClient.class); + var unselectedService = unselected.continuationService(unusedAccountClient, unusedClient); + + assertThatThrownBy(() -> unselectedService.continueOriginalEvidence(unselectedTuple)) + .isInstanceOf(EvidenceContinuationUnavailableException.class) + .hasMessageContaining("missing"); + verifyNoInteractions(unusedAccountClient, unusedClient); + assertThat(unselected.pinCount()).isZero(); + + Fixture selected = fixture(); + RetainedAssociation retained = + retainAssociation(selected, "descriptor-continuation-read-denied"); + StartSessionRedeemedOperationProjectionClient accountClient = projectionClient(retained); + StartSessionLaunchDescriptorReadClient unavailableClient = + mock(StartSessionLaunchDescriptorReadClient.class); + when(unavailableClient.resolve(any(Request.class))) + .thenThrow(new IllegalStateException("Game Design rejected changed Account authority")); + var unavailableService = selected.continuationService(accountClient, unavailableClient); + + assertThatThrownBy(() -> unavailableService.continueOriginalEvidence(retained.tuple())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed Account authority"); + ArgumentCaptor request = ArgumentCaptor.forClass(Request.class); + verify(unavailableClient).resolve(request.capture()); + var originalRequest = retained.association().result().request(); + verify(accountClient) + .read(retained.tuple(), originalRequest.ownerAttemptId(), originalRequest.ownerFence()); + assertThat(request.getValue().selection()).isInstanceOf(ExactReplay.class); + assertThat(request.getValue().readRequestId()) + .isEqualTo(retained.association().result().request().readRequestId()); + assertThat(selected.pinCount()).isZero(); + // This mocked transport exercises orchestration only; it is not live Account/mTLS proof. + } + + @Test + void continuationServiceCallsGameDesignOutsideSqlAndPinsItsExactReplayOutcome() { + Fixture fixture = fixture(); + RetainedAssociation retained = retainAssociation(fixture, "descriptor-continuation-service"); + var candidate = descriptor(retained, "continuation-service-descriptor"); + StartSessionRedeemedOperationProjectionClient accountClient = projectionClient(retained); + StartSessionLaunchDescriptorReadClient client = + mock(StartSessionLaunchDescriptorReadClient.class); + when(client.resolve(any(Request.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return candidate; + }); + var service = fixture.continuationService(accountClient, client); + + PinnedLaunchDescriptorSnapshot pinned = service.continueOriginalEvidence(retained.tuple()); + + ArgumentCaptor request = ArgumentCaptor.forClass(Request.class); + verify(client).resolve(request.capture()); + var originalRequest = retained.association().result().request(); + verify(accountClient, org.mockito.Mockito.times(2)) + .read(retained.tuple(), originalRequest.ownerAttemptId(), originalRequest.ownerFence()); + assertThat(request.getValue()).isEqualTo(candidate.associationRead().request()); + assertThat(request.getValue().selection()).isInstanceOf(ExactReplay.class); + assertThat(pinned.responseWire()).isNotEmpty(); + assertThat(fixture.pinCount()).isEqualTo(1); + // The mock proves orchestration only, not Account or Game Design currentness authorization. + } + + private static StartSessionRedeemedOperationProjectionClient projectionClient( + RetainedAssociation retained) { + var request = retained.association().result().request(); + StartSessionRedeemedOperationProjectionClient client = + mock(StartSessionRedeemedOperationProjectionClient.class); + ReadRedeemedOperationProjectionResponse response = + redeemedProjection(retained.tuple(), request.ownerAttemptId(), request.ownerFence()); + when(client.read(retained.tuple(), request.ownerAttemptId(), request.ownerFence())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return response; + }); + return client; + } + + private static ReadRedeemedOperationProjectionResponse redeemedProjection( + StartSessionPostAuthorizationExecutionTuple tuple, UUID attemptId, long ownerFence) { + // Complete deterministic wire fixture for mocked orchestration; it is not Account server proof. + var preTuple = tuple.preAuthorizationTuple(); + var bundle = StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + var bundleReference = tuple.bundleReference(); + Instant referenceExpiresAt = Instant.parse(bundle.authorizationExpiresAt()); + return ReadRedeemedOperationProjectionResponse.newBuilder() + .setControlPlaneRequestId(preTuple.controlPlaneRequestId()) + .setCanonicalPreAuthorizationTupleBytes( + ByteString.copyFrom(preTuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setMutationDigest(preTuple.mutationDigest()) + .setAuthorizationReferenceFingerprint(tuple.authorizationReferenceFingerprint()) + .setReservationOwnerId(tuple.reservationOwnerId().toString()) + .setReservationClaimFence(tuple.reservationClaimFence()) + .setAuthenticatedRedeemerWorkloadIdentity( + "spiffe://firemud/ns/world-runtime/sa/game-session-service") + .setOwnerAttemptId(attemptId.toString()) + .setOwnerFence(ownerFence) + .setReferenceExpiresAt(timestamp(referenceExpiresAt)) + .setRedeemedAt(timestamp(referenceExpiresAt.minusSeconds(60L))) + .setIssuanceOperationId(bundle.issuanceOperationId().toString()) + .setIssuanceFence(Long.parseLong(bundle.issuanceFence())) + .setBundleReference( + AuthorityEvidenceBundleReference.newBuilder() + .setBundleVersion(bundleReference.bundleVersion()) + .setSourceVersion(bundleReference.sourceVersion()) + .setSourceFence(bundleReference.sourceFence()) + .setLinearization(bundleReference.linearization()) + .build()) + .setAuthorityEvidenceBundle(ByteString.copyFrom(tuple.authorityEvidenceBundleBytes())) + .build(); + } + + private static Timestamp timestamp(Instant instant) { + return Timestamp.newBuilder() + .setSeconds(instant.getEpochSecond()) + .setNanos(instant.getNano()) + .build(); + } + + private static RetainedAssociation retainAssociation(Fixture fixture, String requestId) { + StartSessionPostAuthorizationExecutionTuple tuple = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple(requestId); + ReservationResult reservation = fixture.reserve(tuple); + AttemptClaim claim = reservation.claim().orElseThrow(); + AccountRedemptionProjection projection = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.projection(tuple); + fixture.attach(claim, projection); + Result initial = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.result( + tuple, claim, new InitialConfigured(), UUID.randomUUID()); + return new RetainedAssociation(tuple, claim, fixture.pinAssociation(claim, initial)); + } + + private static boolean continueAndPin( + Fixture fixture, + RetainedAssociation retained, + StartSessionLaunchDescriptorGrpcCodec.Resolved candidate, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("descriptor continuation contender did not start"); + } + try { + EvidenceContinuation continuation = fixture.continueEvidence(retained.tuple()); + fixture.pin(continuation, candidate); + return true; + } catch ( + GameSessionStartSessionLaunchDescriptorRepository + .StartSessionLaunchDescriptorConflictException + conflict) { + return false; + } + } + + private static StartSessionLaunchDescriptorGrpcCodec.Resolved descriptor( + RetainedAssociation retained, String descriptorId) { + return descriptorFor(retained.association().result(), descriptorId); + } + + static StartSessionLaunchDescriptorGrpcCodec.Resolved descriptorFor( + Result association, String descriptorId) { + Request request = exactReplayRequest(association); + Result exactAssociation = exactReplayAssociation(association, request); + var selection = association.association(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + request.targetNamespace(), + request.decodedTuple().controlPlaneRequestId(), + selection.canonicalTenantId(), + selection.worldSlug(), + selection.sourceOperationId(), + selection.sourceEvidenceDigest(), + selection.templateId(), + false, + null, + false, + null, + false, + null, + true, + "{}"); + PublishedReleaseBundle release = association.releaseBundle(); + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + descriptorId, + release.getVersionId(), + false, + null, + "{}", + release.getGenerationConfigRevision(), + 5L, + release.getId(), + release.getPublishedReleaseBundleRef(), + false, + null); + return new StartSessionLaunchDescriptorGrpcCodec.Resolved( + exactAssociation, new StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome(evidence)); + } + + private static Request exactReplayRequest(Result original) { + var association = original.association(); + Request first = original.request(); + return new Request( + first.schemaVersion(), + first.targetNamespace(), + first.readRequestId(), + first.canonicalPostAuthorizationTuple(), + first.ownerAttemptId(), + first.ownerFence(), + new ExactReplay( + association.canonicalVersionId(), + association.selectedCommitId(), + association.publishWorkflowId(), + association.associationDigest())); + } + + private static Result exactReplayAssociation(Result original, Request request) { + return new Result( + request, + original.association(), + original.releaseBundle(), + original.worldPublishedStartLocationEvidence(), + original.phaseEpoch()); + } + + private static Fixture fixture() { + return fixture(Duration.ofSeconds(30)); + } + + private static Fixture fixture(Duration ownerClaimLease) { + String schema = "gs_start_session_descriptor_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var attempts = new GameSessionStartSessionOperatorAttemptRepository(dsl, ownerClaimLease); + var associations = new GameSessionStartSessionTemplateAssociationRepository(dsl, attempts); + return new Fixture( + dsl, + transactions, + transactionManager, + attempts, + associations, + new GameSessionStartSessionLaunchDescriptorRepository(dsl, associations)); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactions, + DataSourceTransactionManager transactionManager, + GameSessionStartSessionOperatorAttemptRepository attempts, + GameSessionStartSessionTemplateAssociationRepository associations, + GameSessionStartSessionLaunchDescriptorRepository descriptors) { + ReservationResult reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + return transactions.execute(status -> attempts.reserve(tuple)); + } + + AttemptClaim reserveAndAttach(StartSessionPostAuthorizationExecutionTuple tuple) { + AttemptClaim claim = reserve(tuple).claim().orElseThrow(); + attach( + claim, + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.projection(tuple)); + return claim; + } + + EvidenceContinuation continueEvidence(StartSessionPostAuthorizationExecutionTuple tuple) { + return transactions.execute(status -> attempts.beginEvidenceContinuation(tuple)); + } + + void attach(AttemptClaim claim, AccountRedemptionProjection projection) { + transactions.executeWithoutResult( + status -> attempts.attachAccountRedemptionProjection(claim, projection)); + } + + PinnedAssociationSnapshot pinAssociation(AttemptClaim claim, Result result) { + return transactions.execute( + status -> associations.pinInitialOrValidateExactReplay(claim, result)); + } + + PinnedLaunchDescriptorSnapshot pin( + AttemptClaim claim, StartSessionLaunchDescriptorGrpcCodec.Resolved resolved) { + return transactions.execute(status -> descriptors.pin(claim, resolved)); + } + + PinnedLaunchDescriptorSnapshot pin( + EvidenceContinuation continuation, + StartSessionLaunchDescriptorGrpcCodec.Resolved resolved) { + return transactions.execute(status -> descriptors.pin(continuation, resolved)); + } + + java.util.Optional find(AttemptClaim claim) { + return transactions.execute(status -> descriptors.findPinned(claim)); + } + + java.util.Optional find(EvidenceContinuation continuation) { + return transactions.execute(status -> descriptors.findPinned(continuation)); + } + + GameSessionStartSessionLaunchDescriptorContinuationService continuationService( + StartSessionRedeemedOperationProjectionClient accountClient, + StartSessionLaunchDescriptorReadClient client) { + return new GameSessionStartSessionLaunchDescriptorContinuationService( + attempts, + associations, + descriptors, + accountClient, + client, + transactionManager, + "world-runtime"); + } + + int pinCount() { + return dsl.fetchCount( + DSL.table(DSL.name("game_session_start_session_launch_descriptor_pin"))); + } + } + + private record RetainedAssociation( + StartSessionPostAuthorizationExecutionTuple tuple, + AttemptClaim claim, + PinnedAssociationSnapshot association) {} +} 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 new file mode 100644 index 0000000000..43c94bc553 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java @@ -0,0 +1,671 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec.Resolved; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository.PinnedLaunchDescriptorSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.EvidenceContinuation; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationDisposition; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** PostgreSQL proof of the immutable, non-replayable StartSession owner-attempt reservation. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "world-runtime"; + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void oneConcurrentClaimWinsAndExactReplayReturnsOnlyTheOriginalSnapshot() throws Exception { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("operator-attempt-concurrent"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> contender(fixture, tuple, ready, start)); + Future second = + executor.submit(() -> contender(fixture, tuple, ready, start)); + assertThat(ready.await(15, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + ReservationResult firstResult = first.get(20, TimeUnit.SECONDS); + ReservationResult secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(List.of(firstResult.disposition(), secondResult.disposition())) + .containsExactlyInAnyOrder( + ReservationDisposition.CLAIM_CREATED, ReservationDisposition.EXACT_REPLAY); + ReservationResult created = + firstResult.disposition() == ReservationDisposition.CLAIM_CREATED + ? firstResult + : secondResult; + ReservationResult replay = + firstResult.disposition() == ReservationDisposition.EXACT_REPLAY + ? firstResult + : secondResult; + assertThat(created.claim()).isPresent(); + assertThat(replay.claim()).isEmpty(); + assertThat(replay.snapshot().ownerAttemptId()).isEqualTo(created.snapshot().ownerAttemptId()); + assertThat(replay.snapshot().ownerMutationId()) + .isEqualTo(created.snapshot().ownerMutationId()); + assertThat(replay.snapshot().ownerFence()).isEqualTo(created.snapshot().ownerFence()); + assertThat(replay.snapshot().phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + 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(); + } finally { + executor.shutdownNow(); + } + } + + @Test + void exactAccountProjectionAttachesOnceWhileFingerprintAndSourceSubstitutionsConflict() { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("operator-attempt-projection"); + ReservationResult reservation = fixture.reserve(tuple); + AttemptClaim claim = reservation.claim().orElseThrow(); + byte[] exactBundle = tuple.authorityEvidenceBundleBytes(); + AccountRedemptionProjection exact = projection(FINGERPRINT, exactBundle, ISSUANCE_ID, 23L); + + fixture.transactions.executeWithoutResult( + status -> { + fixture.repository.attachAccountRedemptionProjection(claim, exact); + status.setRollbackOnly(); + }); + assertThat(fixture.reserve(tuple).snapshot().accountRedemptionProjection()).isNull(); + + AttemptSnapshot attached = fixture.attach(claim, exact); + AttemptSnapshot replayed = fixture.attach(claim, exact); + assertThat(attached.accountRedemptionProjection()).isNotEmpty(); + assertThat(replayed.accountRedemptionProjection()) + .containsExactly(attached.accountRedemptionProjection()); + + AccountRedemptionProjection changedFingerprint = + projection("arfp/v1/other-key/" + "c".repeat(64), exactBundle, ISSUANCE_ID, 23L); + assertThatThrownBy(() -> fixture.attach(claim, changedFingerprint)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + + byte[] changedSourceBundle = + bundle(tuple.preAuthorizationTuple(), "18", "sha256:" + "c".repeat(64)); + AccountRedemptionProjection changedSource = + projection(FINGERPRINT, changedSourceBundle, ISSUANCE_ID, 23L); + assertThatThrownBy(() -> fixture.attach(claim, changedSource)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_start_session_operator_attempt")))) + .isEqualTo(1); + } + + @Test + void evidenceContinuationRequiresTheExactAttachedProjectionAndUnexpiredOriginalAttempt() + throws Exception { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = + tuple("operator-attempt-evidence-continuation"); + AttemptClaim claim = fixture.reserve(tuple).claim().orElseThrow(); + + assertThatThrownBy(() -> fixture.continueEvidence(tuple)) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("no attached Account projection"); + fixture.attach( + claim, + projection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + + EvidenceContinuation first = fixture.continueEvidence(tuple); + EvidenceContinuation afterRestart = fixture.continueEvidence(tuple); + assertThat(afterRestart).isNotSameAs(first); + assertThat(fixture.attemptCount()).isEqualTo(1); + ReservationResult exactReplay = fixture.reserve(tuple); + assertThat(exactReplay.claim()).isEmpty(); + assertThat(exactReplay.disposition()).isEqualTo(ReservationDisposition.EXACT_REPLAY); + assertThatThrownBy( + () -> + fixture.continueEvidence( + tuple(tuple.controlPlaneRequestId(), "changed complete action"))) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class) + .hasMessageContaining("complete StartSession attempt"); + + Fixture expiring = fixture(Duration.ofMillis(500)); + StartSessionPostAuthorizationExecutionTuple expiringTuple = + tuple("operator-attempt-evidence-continuation-expired"); + AttemptClaim expiringClaim = expiring.reserve(expiringTuple).claim().orElseThrow(); + expiring.attach( + expiringClaim, + projection( + expiringTuple.authorizationReferenceFingerprint(), + expiringTuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + Thread.sleep(750L); + + assertThatThrownBy(() -> expiring.continueEvidence(expiringTuple)) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired"); + assertThat(expiring.attemptCount()).isEqualTo(1); + } + + @Test + void expiredOriginalReferenceBlocksContinuationWhileTheOwnerClaimRemainsLive() { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = + tuple( + "operator-attempt-reference-expired", + "canonical StartSession owner attempt", + RESERVATION_OWNER, + 19L, + FINGERPRINT, + Instant.parse("2000-01-01T00:05:00Z")); + AttemptClaim claim = fixture.reserve(tuple).claim().orElseThrow(); + fixture.attach( + claim, + projection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + + assertThat(fixture.validate(claim).phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + assertThatThrownBy(() -> fixture.continueEvidence(tuple)) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("authorization reference expired"); + assertThat(fixture.reserve(tuple).claim()).isEmpty(); + assertThat(fixture.validate(claim).ownerFence()).isEqualTo(claim.ownerFence()); + assertThat(fixture.attemptCount()).isEqualTo(1); + } + + @Test + void descriptorInsertRechecksOriginalReferenceExpiryAfterContinuationPrechecks() + throws Exception { + Fixture fixture = fixture(Duration.ofSeconds(30)); + Instant authorityExpiresAt = Instant.now().plusSeconds(15); + StartSessionPostAuthorizationExecutionTuple tuple = + tuple( + "operator-attempt-descriptor-reference-expired", + "canonical StartSession owner attempt", + RESERVATION_OWNER, + 19L, + FINGERPRINT, + authorityExpiresAt); + AttemptClaim claim = fixture.reserve(tuple).claim().orElseThrow(); + fixture.attach( + claim, + projection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + var initialAssociation = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.result( + tuple, + claim, + new net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .InitialConfigured(), + UUID.randomUUID()); + fixture.pinAssociation(claim, initialAssociation); + EvidenceContinuation continuation = fixture.continueEvidence(tuple); + var descriptor = + GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.descriptorFor( + initialAssociation, "reference-expiring-descriptor"); + assertThat(fixture.reserve(tuple).claim()).isEmpty(); + + ExecutorService executor = Executors.newSingleThreadExecutor(); + AtomicReference> pinAttempt = new AtomicReference<>(); + try { + fixture.transactions.executeWithoutResult( + status -> { + fixture.dsl.execute( + "LOCK TABLE game_session_start_session_launch_descriptor_pin IN SHARE MODE"); + pinAttempt.set(executor.submit(() -> fixture.pin(continuation, descriptor))); + awaitDescriptorPinInsertWait(fixture); + long remainingMillis = + Duration.between(Instant.now(), authorityExpiresAt.plusMillis(500)).toMillis(); + if (remainingMillis > 0L) { + try { + Thread.sleep(remainingMillis); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while holding descriptor pin lock", interrupted); + } + } + }); + + try { + pinAttempt.get().get(10, TimeUnit.SECONDS); + throw new AssertionError("expired original reference must not create a descriptor pin"); + } catch (ExecutionException failure) { + assertThat(failure.getCause()) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired or changed before the descriptor pin statement"); + } + } finally { + executor.shutdownNow(); + } + + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_start_session_launch_descriptor_pin")))) + .isZero(); + assertThat(fixture.validate(claim).phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(fixture.reserve(tuple).claim()).isEmpty(); + assertThat(fixture.attemptCount()).isEqualTo(1); + } + + private static void awaitDescriptorPinInsertWait(Fixture fixture) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + Integer waiting = + fixture + .dsl + .fetchSingle( + "SELECT count(*) AS waiting FROM pg_locks " + + "WHERE relation = to_regclass('game_session_start_session_launch_descriptor_pin') " + + "AND NOT granted") + .get("waiting", Integer.class); + if (waiting != null && waiting > 0) { + return; + } + try { + Thread.sleep(10L); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for descriptor pin insert", interrupted); + } + } + throw new IllegalStateException("Descriptor pin insert did not wait for the owner table lock"); + } + + @Test + void changedTupleAndExpiredClaimNeverCreateOrTransferAnotherOwnerAttempt() throws Exception { + Fixture fixture = fixture(Duration.ofMillis(50)); + StartSessionPostAuthorizationExecutionTuple original = + tuple("operator-attempt-conflict", "original action"); + ReservationResult reservation = fixture.reserve(original); + StartSessionPostAuthorizationExecutionTuple changed = + tuple("operator-attempt-conflict", "changed action"); + StartSessionPostAuthorizationExecutionTuple changedReservation = + tuple( + "operator-attempt-conflict", + "original action", + UUID.fromString("53ced645-bf72-4e55-91ba-c9fef2541a72"), + 20L); + + assertThatThrownBy(() -> fixture.reserve(changed)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + assertThatThrownBy(() -> fixture.reserve(changedReservation)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + assertThat(fixture.attemptCount()).isEqualTo(1); + + Thread.sleep(150L); + assertThatThrownBy(() -> fixture.validate(reservation.claim().orElseThrow())) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired"); + ReservationResult expiredReplay = fixture.reserve(original); + assertThat(expiredReplay.disposition()).isEqualTo(ReservationDisposition.EXACT_REPLAY); + assertThat(expiredReplay.claim()).isEmpty(); + assertThat(expiredReplay.snapshot().ownerAttemptId()) + .isEqualTo(reservation.snapshot().ownerAttemptId()); + assertThat(fixture.attemptCount()).isEqualTo(1); + } + + @Test + void rollbackLeavesNoAttemptRecord() { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("operator-attempt-rollback"); + + fixture.transactions.executeWithoutResult( + status -> { + fixture.repository.reserve(tuple); + status.setRollbackOnly(); + }); + + assertThat(fixture.attemptCount()).isZero(); + } + + @Test + void persistsTheMaximumCanonicalAuthorizationFingerprintLength() { + Fixture fixture = fixture(Duration.ofSeconds(30)); + String maximumFingerprint = "arfp/v1/" + "k".repeat(64) + "/" + "d".repeat(64); + assertThat(maximumFingerprint).hasSize(137); + + ReservationResult reservation = + fixture.reserve( + tuple( + "operator-attempt-max-fingerprint", + "canonical StartSession owner attempt", + RESERVATION_OWNER, + 19L, + maximumFingerprint)); + + assertThat(reservation.disposition()).isEqualTo(ReservationDisposition.CLAIM_CREATED); + assertThat(reservation.snapshot().ownerAttemptId()).isNotNull(); + assertThat(fixture.attemptCount()).isEqualTo(1); + } + + private static ReservationResult contender( + Fixture fixture, + StartSessionPostAuthorizationExecutionTuple tuple, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent StartSession contender did not start"); + } + return fixture.reserve(tuple); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String requestId) { + return tuple(requestId, "canonical StartSession owner attempt"); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, String auditReason) { + return tuple(requestId, auditReason, RESERVATION_OWNER, 19L); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, String auditReason, UUID reservationOwner, long reservationFence) { + return tuple(requestId, auditReason, reservationOwner, reservationFence, FINGERPRINT); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, + String auditReason, + UUID reservationOwner, + long reservationFence, + String fingerprint) { + return tuple( + requestId, + auditReason, + reservationOwner, + reservationFence, + fingerprint, + Instant.parse("2099-01-01T00:05:00Z")); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, + String auditReason, + UUID reservationOwner, + long reservationFence, + String fingerprint, + Instant authorityExpiresAt) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + WORKLOAD, + fingerprint, + reservationOwner, + reservationFence, + bundle(pre, "17", "sha256:" + "a".repeat(64), authorityExpiresAt), + reference("17")); + } + + private static AccountRedemptionProjection projection( + String fingerprint, byte[] bundle, UUID issuanceOperationId, long issuanceFence) { + return new AccountRedemptionProjection(fingerprint, bundle, issuanceOperationId, issuanceFence); + } + + private static byte[] bundle( + StartSessionPreAuthorizationReservationTuple tuple, String version, String sourceEvidenceId) { + return bundle(tuple, version, sourceEvidenceId, Instant.parse("2099-01-01T00:05:00Z")); + } + + private static byte[] bundle( + StartSessionPreAuthorizationReservationTuple tuple, + String version, + String sourceEvidenceId, + Instant authorityExpiresAt) { + String tenantId = TENANT.toString(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + sourceEvidenceId, + "sourceEvidenceVersion", + version, + "projectionStatus", + "CURRENT", + "evaluatedAt", + "1999-01-01T00:00:00Z", + "expiresAt", + authorityExpiresAt.toString()); + Map identity = + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException(exception); + } + } + + private static StartSessionAuthorityEvidenceBundle.BundleReference reference(String version) { + return new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, version, "23", "18446744073709551615"); + } + + private static Fixture fixture(Duration claimLease) { + String schema = "gs_operator_attempt_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionStartSessionOperatorAttemptRepository attempts = + new GameSessionStartSessionOperatorAttemptRepository(dsl, claimLease); + GameSessionStartSessionTemplateAssociationRepository associations = + new GameSessionStartSessionTemplateAssociationRepository(dsl, attempts); + return new Fixture( + dsl, + transactions, + attempts, + associations, + new GameSessionStartSessionLaunchDescriptorRepository(dsl, associations)); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactions, + GameSessionStartSessionOperatorAttemptRepository repository, + GameSessionStartSessionTemplateAssociationRepository associations, + GameSessionStartSessionLaunchDescriptorRepository descriptors) { + ReservationResult reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + return Objects.requireNonNull( + transactions.execute(status -> repository.reserve(tuple)), + "StartSession attempt reservation result"); + } + + AttemptSnapshot attach(AttemptClaim claim, AccountRedemptionProjection projection) { + return Objects.requireNonNull( + transactions.execute( + status -> repository.attachAccountRedemptionProjection(claim, projection)), + "StartSession attempt projection snapshot"); + } + + AttemptSnapshot validate(AttemptClaim claim) { + return Objects.requireNonNull( + transactions.execute(status -> repository.validateCurrentClaim(claim)), + "StartSession attempt claim snapshot"); + } + + EvidenceContinuation continueEvidence(StartSessionPostAuthorizationExecutionTuple tuple) { + return Objects.requireNonNull( + transactions.execute(status -> repository.beginEvidenceContinuation(tuple)), + "StartSession owner evidence continuation"); + } + + PinnedAssociationSnapshot pinAssociation(AttemptClaim claim, Result candidate) { + return Objects.requireNonNull( + transactions.execute( + status -> associations.pinInitialOrValidateExactReplay(claim, candidate)), + "StartSession template association pin"); + } + + PinnedLaunchDescriptorSnapshot pin(EvidenceContinuation continuation, Resolved candidate) { + return Objects.requireNonNull( + transactions.execute(status -> descriptors.pin(continuation, candidate)), + "StartSession launch descriptor pin"); + } + + int attemptCount() { + return dsl.fetchCount(DSL.table(DSL.name("game_session_start_session_operator_attempt"))); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..fb30b84baa --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java @@ -0,0 +1,961 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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.authoring.DraftAuthorizationFenceBinding; +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 net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; +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.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** PostgreSQL proof that one normalized association is immutably pinned to the original attempt. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID VERSION = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID WORLD_OPERATION = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID WORLD_REQUEST = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID WORLD_FENCE = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ROOM = UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final UUID INTAKE_REQUEST = + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final UUID INTAKE_OPERATION = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID SOURCE_OPERATION = + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"); + private static final UUID REGISTRATION_REQUEST = + UUID.fromString("abababab-abab-4bab-8bab-abababababab"); + private static final UUID REGION = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE = UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final UUID REGION_REVISION = + UUID.fromString("12345678-1234-4234-8234-123456789001"); + private static final UUID ZONE_REVISION = UUID.fromString("12345678-1234-4234-8234-123456789002"); + private static final UUID ROOM_REVISION = UUID.fromString("12345678-1234-4234-8234-123456789003"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "world-runtime"; + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String WORLD_SLUG = "authored-world"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final Instant AUTHORITY_REFERENCE_TIME = Instant.now(); + private static final Instant AUTHORITY_EVALUATED_AT = AUTHORITY_REFERENCE_TIME.minusSeconds(60L); + private static final Instant AUTHORITY_EXPIRES_AT = + AUTHORITY_REFERENCE_TIME.plus(Duration.ofHours(1)); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void pinsOneInitialSelectionAndExactReplayReturnsTheOriginalWireSelection() { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("association-pin-exact-replay"); + AttemptClaim claim = fixture.reserveAndAttach(tuple); + Result initial = result(tuple, claim, new InitialConfigured(), UUID.randomUUID()); + + PinnedAssociationSnapshot first = fixture.pin(claim, initial); + PinnedAssociationSnapshot stored = fixture.find(claim).orElseThrow(); + Result exactReplay = + result( + tuple, + claim, + new ExactReplay( + first.result().association().canonicalVersionId(), + first.result().association().selectedCommitId(), + first.result().association().publishWorkflowId(), + first.result().association().associationDigest()), + UUID.randomUUID()); + PinnedAssociationSnapshot replay = fixture.pin(claim, exactReplay); + + assertThat(first.result().request().selection()).isInstanceOf(InitialConfigured.class); + assertThat(stored.result().request()).isEqualTo(first.result().request()); + assertThat(replay.result().request()).isEqualTo(first.result().request()); + assertThat(replay.requestDigest()).isEqualTo(first.requestDigest()); + assertThat(replay.responseDigest()).isEqualTo(first.responseDigest()); + assertThat(fixture.pinCount()).isEqualTo(1); + PinnedAssociationSnapshot exactLostAcknowledgementReplay = fixture.pin(claim, initial); + assertThat(exactLostAcknowledgementReplay.result().request()) + .isEqualTo(first.result().request()); + Result changedInitialRead = result(tuple, claim, new InitialConfigured(), UUID.randomUUID()); + assertThatThrownBy(() -> fixture.pin(claim, changedInitialRead)) + .isInstanceOf( + GameSessionStartSessionTemplateAssociationRepository + .StartSessionTemplateAssociationConflictException.class) + .hasMessageContaining("Exact replay"); + StartSessionPostAuthorizationExecutionTuple changedTuple = + tuple("association-pin-exact-replay", "substituted authorized action"); + Result changedTupleResult = + result(changedTuple, claim, new InitialConfigured(), UUID.randomUUID()); + assertThatThrownBy(() -> fixture.pin(claim, changedTupleResult)) + .isInstanceOf( + GameSessionStartSessionTemplateAssociationRepository + .StartSessionTemplateAssociationConflictException.class) + .hasMessageContaining("exact current StartSession owner attempt"); + Result changedAssociationReplay = + withAssociationDigest(exactReplay, "sha256:" + "c".repeat(64)); + assertThatThrownBy(() -> fixture.pin(claim, changedAssociationReplay)) + .isInstanceOf( + GameSessionStartSessionTemplateAssociationRepository + .StartSessionTemplateAssociationConflictException.class) + .hasMessageContaining("Exact replay"); + assertThat(fixture.pinCount()).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(); + + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_start_session_template_association_pin " + + "SET selected_commit_id = ? WHERE target_namespace = ? " + + "AND control_plane_request_id = ?", + UUID.fromString("66666666-6666-4666-8666-666666666666"), + claim.targetNamespace(), + claim.controlPlaneRequestId())) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.pinCount()).isEqualTo(1); + } + + @Test + void concurrentInitialSelectionsCannotReplaceTheFirstCommittedPin() throws Exception { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("association-pin-concurrent"); + AttemptClaim claim = fixture.reserveAndAttach(tuple); + Result firstInitial = result(tuple, claim, new InitialConfigured(), UUID.randomUUID()); + Result secondInitial = withAssociationDigest(firstInitial, "sha256:" + "c".repeat(64)); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> contender(fixture, claim, firstInitial, ready, start)); + Future second = + executor.submit(() -> contender(fixture, claim, secondInitial, ready, start)); + assertThat(ready.await(15, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + List outcomes = + List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); + + assertThat(outcomes.stream().filter(PinOutcome::pinned).count()).isEqualTo(1); + assertThat(outcomes.stream().filter(value -> !value.pinned()).count()).isEqualTo(1); + assertThat(fixture.pinCount()).isEqualTo(1); + assertThat(fixture.find(claim)).isPresent(); + } finally { + executor.shutdownNow(); + } + } + + @Test + void claimWithoutAccountProjectionCannotReadOrCreateASelectionPin() { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("association-pin-no-account"); + ReservationResult reservation = fixture.reserve(tuple); + AttemptClaim claim = reservation.claim().orElseThrow(); + Result initial = result(tuple, claim, new InitialConfigured(), UUID.randomUUID()); + + assertThatThrownBy(() -> fixture.pin(claim, initial)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("Account-attached"); + assertThatThrownBy(() -> fixture.find(claim)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("Account-attached"); + assertThat(fixture.pinCount()).isZero(); + } + + @Test + void oversizedTypedReleaseIsDeniedByTheLocalStorageBudgetBeforeOwnerStorageAccess() { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("association-pin-oversized-response"); + AttemptClaim claim = fixture.reserveAndAttach(tuple); + Result valid = result(tuple, claim, new InitialConfigured(), UUID.randomUUID()); + PublishedReleaseBundle oversizedRelease = + valid.releaseBundle().toBuilder() + .addCommandDefinitions("x".repeat(4 * 1024 * 1024 + 1)) + .build(); + Result oversized = + new Result( + valid.request(), + valid.association(), + oversizedRelease, + valid.worldPublishedStartLocationEvidence(), + valid.phaseEpoch()); + + assertThatThrownBy(() -> fixture.pin(claim, oversized)) + .isInstanceOf( + GameSessionStartSessionTemplateAssociationRepository + .StartSessionTemplateAssociationConflictException.class) + .hasMessageContaining("local fail-closed storage budget"); + assertThat(fixture.pinCount()).isZero(); + } + + private static PinOutcome contender( + Fixture fixture, + AttemptClaim claim, + Result initial, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("association pin contender did not start"); + } + try { + return new PinOutcome(true, fixture.pin(claim, initial)); + } catch ( + GameSessionStartSessionTemplateAssociationRepository + .StartSessionTemplateAssociationConflictException + expected) { + return new PinOutcome(false, null); + } + } + + static Result result( + StartSessionPostAuthorizationExecutionTuple tuple, + AttemptClaim claim, + StartSessionTemplateAssociationReadEvidence.Selection selection, + UUID readRequestId) { + // A closed typed carrier fixture for repository semantics, not GD/World producer or runtime + // authority proof. + WorldPublishedStartLocationEvidence world = worldEvidence(); + var worldRequest = world.request(); + AuthoredWorldSourceEvidence source = source(); + IntakeRequest intakeRequest = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST, + TENANT, + WORLD_SLUG, + SOURCE_OPERATION, + source.evidenceDigest()); + PublicReceipt receipt = + new PublicReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + INTAKE_OPERATION, + TENANT, + WORLD_SLUG, + SOURCE_OPERATION, + source.evidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intakeRequest), + "sha256:" + "9".repeat(64), + source); + Association association = + new Association( + TENANT, + tuple.preAuthorizationTuple().action().target().gameTemplateId(), + VERSION, + COMMIT, + worldRequest.publishWorkflowId(), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + NAMESPACE, + INTAKE_REQUEST, + INTAKE_OPERATION, + SOURCE_OPERATION, + WORLD_SLUG, + source.evidenceDigest(), + new ByIdReadRequest(1, NAMESPACE, UUID.randomUUID(), INTAKE_REQUEST, TENANT), + receipt); + Request request = + new Request( + 1, + NAMESPACE, + readRequestId, + tuple.canonicalBytes(), + claim.ownerAttemptId(), + claim.ownerFence(), + selection); + return new Result(request, association, release(world), world, 5L); + } + + static AuthoredWorldSourceEvidence source() { + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST, TENANT, "test-tenant", WORLD_SLUG, "Authored World"); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + "test-tenant", + WORLD_SLUG, + "Authored World", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + "test-tenant", + WORLD_SLUG, + "Authored World", + 42L, + "tenant-key", + "NEW_GAME_ROW", + sourceEvidenceDigest); + } + + private static Result withAssociationDigest(Result original, String changedDigest) { + Association pinned = original.association(); + Association changed = + new Association( + pinned.canonicalTenantId(), + pinned.templateId(), + pinned.canonicalVersionId(), + pinned.selectedCommitId(), + pinned.publishWorkflowId(), + pinned.publicationSelectionDigest(), + changedDigest, + pinned.targetNamespace(), + pinned.intakeRequestId(), + pinned.worldOperationId(), + pinned.sourceOperationId(), + pinned.worldSlug(), + pinned.sourceEvidenceDigest(), + pinned.worldReadRequest(), + pinned.worldReceipt()); + Request oldRequest = original.request(); + StartSessionTemplateAssociationReadEvidence.Selection selection = + oldRequest.selection() instanceof ExactReplay + ? new ExactReplay( + changed.canonicalVersionId(), + changed.selectedCommitId(), + changed.publishWorkflowId(), + changed.associationDigest()) + : oldRequest.selection(); + Request replay = + new Request( + oldRequest.schemaVersion(), + oldRequest.targetNamespace(), + UUID.randomUUID(), + oldRequest.canonicalPostAuthorizationTuple(), + oldRequest.ownerAttemptId(), + oldRequest.ownerFence(), + selection); + return new Result( + replay, + changed, + original.releaseBundle(), + original.worldPublishedStartLocationEvidence(), + original.phaseEpoch()); + } + + private static PublishedReleaseBundle release(WorldPublishedStartLocationEvidence world) { + var request = world.request(); + var builder = + PublishedReleaseBundle.newBuilder() + .setId(91L) + .setVersionId(19L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v2") + .setPublishWorkflowId(request.publishWorkflowId()) + .setManifestHash("sha256:" + "c".repeat(64)) + .setGenerationConfigRevision("generation-1") + .setPublishedReleaseBundleRef("immutable-release-ref") + .setCanonicalTenantId(TENANT.toString()) + .setCanonicalVersionId(VERSION.toString()) + .setManifestSchemaVersion(1); + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder() + .forEach( + owner -> { + ParticipantDigest.Builder participant = + ParticipantDigest.newBuilder() + .setParticipantKey(owner) + .setScopeValue("19") + .setAppliedCommitId(request.appliedCommitId()) + .setContentDigest( + "WORLD_MANAGEMENT".equals(owner) + ? request.contentDigest() + : "d".repeat(64)) + .setDigestSchemaVersion( + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION)); + if ("GAME_LOGIC".equals(owner)) { + participant.setAbilitySchemaDigest("sha256:" + "e".repeat(64)); + } + builder.addParticipantDigests(participant); + }); + return builder.build(); + } + + private static WorldPublishedStartLocationEvidence worldEvidence() { + try { + DraftCommitBinding draft = freshGraphBinding(); + byte[] accountBytes = accountBinding(draft); + WorldDraftTerminalReadEvidence.Request terminalRequest = + WorldDraftTerminalReadEvidence.Request.create(NAMESPACE, accountBytes); + byte[] appliedBytes = appliedReadback(terminalRequest, draft); + String graphDigest = graphDigest(terminalRequest, draft); + WorldDraftStartLocationEvidence receipt = + WorldDraftStartLocationEvidence.create( + NAMESPACE, + WORLD_OPERATION, + WORLD_REQUEST, + COMMIT, + WORLD_FENCE, + sha256(accountBytes), + draft.digest(), + new RoomTemplateRef(TENANT, VERSION, ROOM), + graphDigest); + var tuples = + draft.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(); + var selectorRequest = + new WorldPublishedStartLocationEvidence.Request( + NAMESPACE, + TENANT, + VERSION, + INTAKE_REQUEST, + WORLD_FENCE, + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + COMMIT.toString(), + "b".repeat(64), + 3, + tuples); + return new WorldPublishedStartLocationEvidence( + selectorRequest, receipt.canonicalBytes(), accountBytes, appliedBytes); + } catch (IOException impossible) { + throw new AssertionError(impossible); + } + } + + private static DraftCommitBinding freshGraphBinding() throws IOException { + String declaration = + JSON.writeValueAsString( + orderedMap( + "tenantId", + TENANT.toString(), + "versionId", + VERSION.toString(), + "startLocation", + orderedMap( + "tenantId", TENANT.toString(), + "versionId", VERSION.toString(), + "roomTemplateId", ROOM.toString()), + "familyCounts", + List.of( + orderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + orderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + orderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + orderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + orderedMap("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + orderedMap( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + new TargetProof(TENANT, VERSION, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + WORLD_REQUEST, + COMMIT, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevision( + REGION_REVISION, "WORLD_DESIGN_AGGREGATE_TYPE_REGION", REGION, declaration)), + new RevisionPayload( + "1", + ZONE_REVISION, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevision(ZONE_REVISION, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE, null)), + new RevisionPayload( + "2", + ROOM_REVISION, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevision(ROOM_REVISION, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM, null))), + List.of( + affected("REGION", REGION, "REGION_SUBTREE", REGION), + affected("ZONE", ZONE, "REGION_SUBTREE", REGION), + affected("ROOM", ROOM, "ZONE_SUBTREE", ZONE)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static byte[] accountBinding(DraftCommitBinding draft) { + return new DraftAuthorizationFenceBinding( + WORLD_OPERATION, + WORLD_REQUEST, + COMMIT, + WORLD_FENCE, + ACTOR, + TENANT, + VERSION, + "base-1", + "0", + draft.canonicalBytes(), + draft.canonicalBytes(), + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static byte[] appliedReadback( + WorldDraftTerminalReadEvidence.Request terminalRequest, DraftCommitBinding draft) + throws IOException { + byte[] operation = operationBytes(terminalRequest, draft); + byte[] graph = graphBytes(terminalRequest, draft); + String graphDigest = sha256(graph); + WorldDraftStartLocationEvidence receipt = + WorldDraftStartLocationEvidence.create( + NAMESPACE, + WORLD_OPERATION, + WORLD_REQUEST, + COMMIT, + WORLD_FENCE, + sha256(terminalRequest.originalAccountBinding()), + draft.digest(), + new RoomTemplateRef(TENANT, VERSION, ROOM), + graphDigest); + Map applied = new LinkedHashMap<>(); + applied.put("schema", "world-draft-graph-applied/v2"); + applied.put("status", "APPLIED"); + applied.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation)); + applied.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + applied.put("graphDigest", graphDigest); + applied.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(receipt.canonicalBytes())); + applied.put("startLocationReceiptDigest", receipt.receiptDigest()); + applied.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", unit.aggregateType(), + "aggregateId", unit.aggregateId(), + "scopeType", unit.scopeType(), + "scopeId", unit.scopeId(), + "expectedEpoch", unit.expectedEpoch(), + "resultingEpoch", "1")) + .toList()); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(applied)); + } + + private static byte[] operationBytes( + WorldDraftTerminalReadEvidence.Request terminalRequest, DraftCommitBinding draft) + throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + DataOutputStream frames = new DataOutputStream(output); + frame(frames, "world-draft-terminal-operation/v1"); + for (UUID id : List.of(WORLD_OPERATION, WORLD_REQUEST, COMMIT, WORLD_FENCE, TENANT, VERSION)) { + frame(frames, id.toString()); + } + frame(frames, draft.canonicalBytes()); + for (String value : + List.of( + NAMESPACE, + TENANT.toString(), + VERSION.toString(), + WORLD_OPERATION.toString(), + "19", + INTAKE_REQUEST.toString(), + INTAKE_OPERATION.toString(), + "a".repeat(64), + SOURCE_OPERATION.toString(), + "b".repeat(64), + "c".repeat(64))) { + frame(frames, value); + } + byte[] account = terminalRequest.originalAccountBinding(); + frame(frames, sha256(account)); + frame(frames, account); + return output.toByteArray(); + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request terminalRequest, DraftCommitBinding draft) + throws IOException { + Map graph = new LinkedHashMap<>(); + graph.put("schemaVersion", "2"); + graph.put("canonicalTenantId", TENANT.toString()); + graph.put("canonicalVersionId", VERSION.toString()); + List> rows = new ArrayList<>(); + int mappingId = 1; + long privateRowKey = 101L; + for (RevisionPayload revision : draft.revisions()) { + String family = + revision.payload().contains("WORLD_DESIGN_AGGREGATE_TYPE_REGION") + ? "REGION" + : revision.payload().contains("WORLD_DESIGN_AGGREGATE_TYPE_ZONE") ? "ZONE" : "ROOM"; + UUID templateId = "REGION".equals(family) ? REGION : "ZONE".equals(family) ? ZONE : ROOM; + Map mapping = new LinkedHashMap<>(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", terminalRequest.targetNamespace()); + mapping.put("canonical_tenant_id", TENANT.toString()); + mapping.put("canonical_version_id", VERSION.toString()); + mapping.put("family", family); + mapping.put("template_id", templateId.toString()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", WORLD_OPERATION.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + graph.put("rows", rows); + return JSON.writeValueAsBytes(graph); + } + + private static String graphDigest( + WorldDraftTerminalReadEvidence.Request terminalRequest, DraftCommitBinding draft) + throws IOException { + return sha256(graphBytes(terminalRequest, draft)); + } + + private static String worldRevision( + UUID revisionId, String family, UUID templateId, String declaration) throws IOException { + Map mutation = new LinkedHashMap<>(); + mutation.put("logicalRevisionId", revisionId.toString()); + mutation.put("commitId", COMMIT.toString()); + mutation.put("aggregateType", family); + mutation.put("aggregateId", templateId.toString()); + if (declaration != null) mutation.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(mutation); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_DESIGN_AGGREGATE_TYPE_" + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_DESIGN_AGGREGATE_TYPE_" + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + static StartSessionPostAuthorizationExecutionTuple tuple(String requestId) { + return tuple(requestId, "pin one normalized template association"); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, String auditReason) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + WORKLOAD, + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + AUTHORITY_EVALUATED_AT.toString(), + "expiresAt", + AUTHORITY_EXPIRES_AT.toString()); + Map identity = + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(TENANT.toString(), 3L), + "membershipAuthorityGeneration", Map.of(TENANT.toString(), 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", TENANT.toString(), "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", TENANT.toString()), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(TENANT.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + static AccountRedemptionProjection projection(StartSessionPostAuthorizationExecutionTuple tuple) { + return new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L); + } + + private static Map orderedMap(Object... entries) { + Map result = new LinkedHashMap<>(); + for (int index = 0; index < entries.length; index += 2) { + result.put((String) entries[index], entries[index + 1]); + } + return result; + } + + private static void frame(DataOutputStream frames, String value) throws IOException { + frame(frames, value.getBytes(StandardCharsets.UTF_8)); + } + + private static void frame(DataOutputStream frames, byte[] value) throws IOException { + frames.writeInt(value.length); + frames.write(value); + } + + private static String sha256(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static Fixture fixture() { + String schema = "gs_template_association_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + var transactions = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var attempts = + new GameSessionStartSessionOperatorAttemptRepository(dsl, Duration.ofSeconds(30)); + return new Fixture( + dsl, + transactions, + attempts, + new GameSessionStartSessionTemplateAssociationRepository(dsl, attempts)); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactions, + GameSessionStartSessionOperatorAttemptRepository attempts, + GameSessionStartSessionTemplateAssociationRepository pins) { + ReservationResult reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + return Objects.requireNonNull( + transactions.execute(status -> attempts.reserve(tuple)), "owner attempt reservation"); + } + + AttemptClaim reserveAndAttach(StartSessionPostAuthorizationExecutionTuple tuple) { + ReservationResult reservation = reserve(tuple); + AttemptClaim claim = reservation.claim().orElseThrow(); + transactions.executeWithoutResult( + status -> attempts.attachAccountRedemptionProjection(claim, projection(tuple))); + return claim; + } + + PinnedAssociationSnapshot pin(AttemptClaim claim, Result result) { + return Objects.requireNonNull( + transactions.execute(status -> pins.pinInitialOrValidateExactReplay(claim, result)), + "pinned template association"); + } + + java.util.Optional find(AttemptClaim claim) { + return Objects.requireNonNull( + transactions.execute(status -> pins.findPinned(claim)), "template association read"); + } + + int pinCount() { + return dsl.fetchCount( + DSL.table(DSL.name("game_session_start_session_template_association_pin"))); + } + } + + private record PinOutcome(boolean pinned, PinnedAssociationSnapshot snapshot) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java new file mode 100644 index 0000000000..4a6fce5458 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java @@ -0,0 +1,89 @@ +package unit.net.firedevops.firemud.gamesession.repository; + +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.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalGameInstanceLaunchAssociationRepositoryTest { + private static final String NAMESPACE = "launch-owner"; + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void captureRequiresAWritableOwnerTransactionBeforeReadingAnyRuntimeRow() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + var tenant = freshTenant(); + + assertThatThrownBy(() -> repository.capture(tenant, 92L, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void committedReadCannotBeComposedInsideAnotherOwnerTransaction() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.read("launch-request-1")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed owner read"); + + verifyNoInteractions(dsl); + } + + @Test + void originalStartSessionOwnerReadAlsoRequiresOneCommittedOwnerSnapshot() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + var selector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("44444444-4444-4444-8444-444444444444"), + NAMESPACE, + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "world", + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "launch-request-1", + "descriptor-1", + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.readOriginalStartSessionAssociation(selector)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed owner read"); + + verifyNoInteractions(dsl); + } + + private static FreshGameSessionTenantAssociation freshTenant() { + RuntimeTenantIdentityEvidence source = + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 1L, + "source-game-tenant-key", + "NEW_GAME_ROW"); + return new FreshGameSessionTenantAssociation( + UUID.fromString("33333333-3333-4333-8333-333333333333"), 701L, source); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java new file mode 100644 index 0000000000..ca61e68055 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.junit.jupiter.api.Test; + +class GameSessionAuthoredWorldIntakeDigestTest { + private static final UUID REQUEST = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID OPERATION = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String SOURCE_GAME_TENANT_KEY = "source-22222222"; + private static final String SOURCE_PROVENANCE_KIND = "NEW_GAME_ROW"; + + @Test + void emitsFixedVectorsBindingTheCompleteMultibyteOwnerReceipt() { + var source = source("Café 🐉"); + String request = GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, source); + assertThat(source.evidenceDigest()) + .isEqualTo("sha256:ea835c1f4fbae6206a7f870f509bbdc6b767415608f7be56a44dcd061f1116f7"); + assertThat(request) + .isEqualTo("sha256:7b9ee59edffc076f301c1a47e73e45417dfdff99f2916e6043faa68bbb5aca28"); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, request, source.evidenceDigest())) + .isEqualTo("sha256:4d1afd818098152d268f33d0ba7467bd1c0963700fa05ec170b1181100de93e9"); + } + + @Test + void changedRequestSourceOrOperationCannotReplayTheSameLocalReceipt() { + var source = source("Café 🐉"); + var changedSource = source("Café 🐲"); + String request = GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, source); + String receipt = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, request, source.evidenceDigest()); + assertThat(GameSessionAuthoredWorldIntakeDigest.requestDigest(OPERATION, source)) + .isNotEqualTo(request); + assertThat(GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, changedSource)) + .isNotEqualTo(request); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + REQUEST, request, source.evidenceDigest())) + .isNotEqualTo(receipt); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, + GameSessionAuthoredWorldIntakeDigest.requestDigest(OPERATION, source), + source.evidenceDigest())) + .isNotEqualTo(receipt); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, request, changedSource.evidenceDigest())) + .isNotEqualTo(receipt); + } + + @Test + void rejectsMissingNilOrMalformedOperationAndDigestInputs() { + assertThatThrownBy(() -> GameSessionAuthoredWorldIntakeDigest.requestDigest(null, source("x"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> GameSessionAuthoredWorldIntakeDigest.requestDigest(new UUID(0, 0), source("x"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + new UUID(0, 0), source("x").requestDigest(), source("x").evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> GameSessionAuthoredWorldIntakeDigest.receiptDigest(OPERATION, null, "sha256:x")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, source("x").requestDigest(), "SHA256:" + "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AuthoredWorldSourceEvidence source(String displayName) { + var registration = UUID.fromString("11111111-1111-4111-8111-111111111111"); + var tenant = UUID.fromString("22222222-2222-4222-8222-222222222222"); + var operation = UUID.fromString("33333333-3333-4333-8333-333333333333"); + String request = + AuthoredWorldSourceDigest.requestDigest( + "firemud", registration, tenant, "north-star", "violet-wilds", displayName); + String evidence = + AuthoredWorldSourceDigest.evidenceDigest( + "firemud", + registration, + operation, + request, + tenant, + "north-star", + "violet-wilds", + displayName, + 42L, + SOURCE_GAME_TENANT_KEY, + SOURCE_PROVENANCE_KIND); + return new AuthoredWorldSourceEvidence( + 1, + "firemud", + registration, + operation, + request, + tenant, + "north-star", + "violet-wilds", + displayName, + 42L, + SOURCE_GAME_TENANT_KEY, + SOURCE_PROVENANCE_KIND, + evidence); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryTest.java new file mode 100644 index 0000000000..4ccfb4f568 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryTest.java @@ -0,0 +1,79 @@ +package unit.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class GameSessionStartSessionLaunchDescriptorRepositoryTest { + @Test + void requiresTheExactOwnerClaimBeforeReading() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionTemplateAssociationRepository associations = + mock(GameSessionStartSessionTemplateAssociationRepository.class); + var repository = new GameSessionStartSessionLaunchDescriptorRepository(dsl, associations); + + assertThatThrownBy( + () -> + repository.findPinned( + (GameSessionStartSessionOperatorAttemptRepository.AttemptClaim) null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("claim"); + + verifyNoInteractions(dsl); + verifyNoInteractions(associations); + } + + @Test + void requiresTypedDescriptorEvidenceBeforeOwnerReads() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionTemplateAssociationRepository associations = + mock(GameSessionStartSessionTemplateAssociationRepository.class); + var repository = new GameSessionStartSessionLaunchDescriptorRepository(dsl, associations); + var claim = + new GameSessionStartSessionOperatorAttemptRepository.AttemptClaim( + "world-runtime", + "operator-request", + java.util.UUID.fromString("02222222-2222-4222-8222-222222222222"), + java.util.UUID.fromString("03333333-3333-4333-8333-333333333333"), + java.util.UUID.fromString("04444444-4444-4444-8444-444444444444"), + 7L); + + assertThatThrownBy( + () -> + repository.pin( + (GameSessionStartSessionOperatorAttemptRepository.AttemptClaim) null, null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("claim"); + assertThatThrownBy(() -> repository.pin(claim, null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("candidate"); + + verifyNoInteractions(dsl); + verifyNoInteractions(associations); + } + + @Test + void requiresOpaqueContinuationBeforeDescriptorReadsOrWrites() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionTemplateAssociationRepository associations = + mock(GameSessionStartSessionTemplateAssociationRepository.class); + var repository = new GameSessionStartSessionLaunchDescriptorRepository(dsl, associations); + var continuation = (GameSessionStartSessionOperatorAttemptRepository.EvidenceContinuation) null; + + assertThatThrownBy(() -> repository.findPinned(continuation)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("continuation"); + assertThatThrownBy(() -> repository.pin(continuation, null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("continuation"); + + verifyNoInteractions(dsl); + verifyNoInteractions(associations); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java new file mode 100644 index 0000000000..985b2d9f31 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java @@ -0,0 +1,64 @@ +package net.firedevops.firemud.gamesession.repository; + +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.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionStartSessionOperatorAttemptRepositoryTest { + @AfterEach + void clearTransactionSynchronization() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsCallsOutsideWritableOwnerTransactionBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionOperatorAttemptRepository repository = + new GameSessionStartSessionOperatorAttemptRepository(dsl, java.time.Duration.ofSeconds(30)); + + assertThatThrownBy(() -> repository.reserve(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable READ COMMITTED"); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsReadOnlyOwnerTransactionBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionOperatorAttemptRepository repository = + new GameSessionStartSessionOperatorAttemptRepository(dsl, java.time.Duration.ofSeconds(30)); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy(() -> repository.reserve(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable READ COMMITTED"); + + verifyNoInteractions(dsl); + } + + @Test + void requiresAnExplicitlyBoundedClaimLease() { + DSLContext dsl = mock(DSLContext.class); + + assertThatThrownBy( + () -> + new GameSessionStartSessionOperatorAttemptRepository(dsl, java.time.Duration.ZERO)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive and at most five minutes"); + assertThatThrownBy( + () -> + new GameSessionStartSessionOperatorAttemptRepository( + dsl, java.time.Duration.ofMinutes(6))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive and at most five minutes"); + + verifyNoInteractions(dsl); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryTest.java new file mode 100644 index 0000000000..4f280a2fcd --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryTest.java @@ -0,0 +1,74 @@ +package unit.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class GameSessionStartSessionTemplateAssociationRepositoryTest { + @Test + void requiresTheExactOwnerClaimBeforeReading() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionOperatorAttemptRepository attempts = + mock(GameSessionStartSessionOperatorAttemptRepository.class); + var repository = new GameSessionStartSessionTemplateAssociationRepository(dsl, attempts); + + assertThatThrownBy( + () -> + repository.findPinned( + (GameSessionStartSessionOperatorAttemptRepository.AttemptClaim) null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("claim"); + + verifyNoInteractions(dsl); + verifyNoInteractions(attempts); + } + + @Test + void requiresOpaqueContinuationBeforeAssociationRead() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionOperatorAttemptRepository attempts = + mock(GameSessionStartSessionOperatorAttemptRepository.class); + var repository = new GameSessionStartSessionTemplateAssociationRepository(dsl, attempts); + var continuation = (GameSessionStartSessionOperatorAttemptRepository.EvidenceContinuation) null; + + assertThatThrownBy(() -> repository.findPinned(continuation)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("continuation"); + + verifyNoInteractions(dsl); + verifyNoInteractions(attempts); + } + + @Test + void requiresTypedAssociationEvidenceBeforeOwnerReads() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionOperatorAttemptRepository attempts = + mock(GameSessionStartSessionOperatorAttemptRepository.class); + var repository = new GameSessionStartSessionTemplateAssociationRepository(dsl, attempts); + + assertThatThrownBy(() -> repository.pinInitialOrValidateExactReplay(null, null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("claim"); + assertThatThrownBy( + () -> + repository.pinInitialOrValidateExactReplay( + new GameSessionStartSessionOperatorAttemptRepository.AttemptClaim( + "world-runtime", + "operator-request", + java.util.UUID.fromString("02222222-2222-4222-8222-222222222222"), + java.util.UUID.fromString("03333333-3333-4333-8333-333333333333"), + java.util.UUID.fromString("04444444-4444-4444-8444-444444444444"), + 7L), + null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("candidate"); + + verifyNoInteractions(dsl); + verifyNoInteractions(attempts); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java new file mode 100644 index 0000000000..1c5e69a9c0 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java @@ -0,0 +1,554 @@ +package unit.net.firedevops.firemud.gamesession.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.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +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.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorReadClient; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository.PinnedLaunchDescriptorSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.EvidenceContinuation; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionLaunchDescriptorContinuationService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.MockedStatic; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unit-level continuation orchestration proof. The canonical tuple is an integrity-only typed + * fixture; mocked owner and remote collaborators do not prove current Account redemption or the + * PostgreSQL owner-claim predicates. + */ +class GameSessionStartSessionLaunchDescriptorContinuationServiceTest { + private static final String NAMESPACE = "runtime-a"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT_ID = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID VERSION_ID = uuid("03333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT_ID = uuid("04444444-4444-4444-8444-444444444444"); + private static final String PUBLISH_WORKFLOW_ID = "publish-workflow-1"; + private static final String ASSOCIATION_DIGEST = "sha256:" + "a".repeat(64); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String REQUEST_DIGEST = "sha256:" + "c".repeat(64); + private static final String RESPONSE_DIGEST = "sha256:" + "d".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionSynchronizationState() { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void rejectsNamespaceMismatchBeforeOwnerOrRemoteWork() { + Fixture fixture = new Fixture(NAMESPACE); + + assertThatThrownBy(() -> fixture.service.continueOriginalEvidence(tuple("runtime-b"))) + .isInstanceOf( + GameSessionStartSessionLaunchDescriptorContinuationService + .EvidenceContinuationUnavailableException.class) + .hasMessageContaining("outside the configured Game Session namespace"); + + assertThat(fixture.transactionManager.startedTransactions).isZero(); + verifyNoInteractions( + fixture.attemptRepository, + fixture.associationRepository, + fixture.descriptorRepository, + fixture.accountProjectionClient, + fixture.descriptorReadClient); + } + + @Test + void rejectsAmbientOwnerTransactionBeforeOwnerOrRemoteWork() { + Fixture fixture = new Fixture(NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy(() -> fixture.service.continueOriginalEvidence(fixture.tuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must occur outside owner SQL transactions"); + + assertThat(fixture.transactionManager.startedTransactions).isZero(); + verifyNoInteractions( + fixture.attemptRepository, + fixture.associationRepository, + fixture.descriptorRepository, + fixture.accountProjectionClient, + fixture.descriptorReadClient); + } + + @Test + void missingOriginalSelectionStopsBeforeDescriptorReadOrPin() { + Fixture fixture = new Fixture(NAMESPACE); + when(fixture.associationRepository.findPinned(fixture.continuation)) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> fixture.service.continueOriginalEvidence(fixture.tuple)) + .isInstanceOf( + GameSessionStartSessionLaunchDescriptorContinuationService + .EvidenceContinuationUnavailableException.class) + .hasMessageContaining("Original selection is missing"); + + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); + verify(fixture.attemptRepository).beginEvidenceContinuation(fixture.tuple); + verify(fixture.associationRepository).findPinned(fixture.continuation); + verifyNoMoreInteractions(fixture.attemptRepository, fixture.associationRepository); + verifyNoInteractions( + fixture.descriptorRepository, + fixture.accountProjectionClient, + fixture.descriptorReadClient); + } + + @Test + void accountCurrentnessFailureBeforeDescriptorReadPreventsRemoteReadAndPin() { + Fixture fixture = new Fixture(NAMESPACE); + Result originalResult = fixture.originalResult(); + PinnedAssociationSnapshot original = fixture.snapshot(originalResult); + when(fixture.associationRepository.findPinned(fixture.continuation)) + .thenReturn(Optional.of(original)); + when(fixture.accountProjectionClient.read(fixture.tuple, ATTEMPT_ID, 8L)) + .thenThrow(new IllegalStateException("Account currentness is unavailable")); + + assertThatThrownBy(() -> fixture.service.continueOriginalEvidence(fixture.tuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account currentness is unavailable"); + + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); + verify(fixture.accountProjectionClient).read(fixture.tuple, ATTEMPT_ID, 8L); + verifyNoMoreInteractions(fixture.accountProjectionClient); + verifyNoInteractions(fixture.descriptorReadClient, fixture.descriptorRepository); + } + + @Test + void accountCurrentnessFailureAfterDescriptorReadPreventsOwnerPin() { + Fixture fixture = new Fixture(NAMESPACE); + Result originalResult = fixture.originalResult(); + PinnedAssociationSnapshot original = fixture.snapshot(originalResult); + when(fixture.associationRepository.findPinned(fixture.continuation)) + .thenReturn(Optional.of(original)); + when(fixture.accountProjectionClient.read(fixture.tuple, ATTEMPT_ID, 8L)) + .thenReturn(redeemedProjection("original")) + .thenThrow(new IllegalStateException("Account currentness changed after descriptor read")); + when(fixture.descriptorReadClient.resolve(any(Request.class))) + .thenReturn(mock(StartSessionLaunchDescriptorGrpcCodec.Resolved.class)); + + assertThatThrownBy(() -> fixture.service.continueOriginalEvidence(fixture.tuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account currentness changed after descriptor read"); + + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); + verify(fixture.accountProjectionClient, times(2)).read(fixture.tuple, ATTEMPT_ID, 8L); + verify(fixture.descriptorReadClient).resolve(any(Request.class)); + verifyNoInteractions(fixture.descriptorRepository); + } + + @Test + void changedAccountProjectionAfterDescriptorReadPreventsOwnerPin() { + Fixture fixture = new Fixture(NAMESPACE); + Result originalResult = fixture.originalResult(); + PinnedAssociationSnapshot original = fixture.snapshot(originalResult); + when(fixture.associationRepository.findPinned(fixture.continuation)) + .thenReturn(Optional.of(original)); + when(fixture.accountProjectionClient.read(fixture.tuple, ATTEMPT_ID, 8L)) + .thenReturn(redeemedProjection("original"), redeemedProjection("changed")); + when(fixture.descriptorReadClient.resolve(any(Request.class))) + .thenReturn(mock(StartSessionLaunchDescriptorGrpcCodec.Resolved.class)); + + assertThatThrownBy(() -> fixture.service.continueOriginalEvidence(fixture.tuple)) + .isInstanceOf( + GameSessionStartSessionLaunchDescriptorContinuationService + .EvidenceContinuationUnavailableException.class) + .hasMessageContaining("Account's original redeemed operation projection changed"); + + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); + verify(fixture.accountProjectionClient, times(2)).read(fixture.tuple, ATTEMPT_ID, 8L); + verify(fixture.descriptorReadClient).resolve(any(Request.class)); + verifyNoInteractions(fixture.descriptorRepository); + } + + @Test + void changedOriginalSelectionAfterRemoteReadPreventsDescriptorPin() { + Fixture fixture = new Fixture(NAMESPACE); + Result originalResult = fixture.originalResult(); + Result changedResult = fixture.originalResult(); + PinnedAssociationSnapshot original = fixture.snapshot(originalResult); + PinnedAssociationSnapshot changed = fixture.snapshot(changedResult); + when(fixture.associationRepository.findPinned(fixture.continuation)) + .thenReturn(Optional.of(original), Optional.of(changed)); + when(fixture.accountProjectionClient.read(fixture.tuple, ATTEMPT_ID, 8L)) + .thenReturn(redeemedProjection("original"), redeemedProjection("original")); + StartSessionLaunchDescriptorGrpcCodec.Resolved resolved = + mock(StartSessionLaunchDescriptorGrpcCodec.Resolved.class); + when(fixture.descriptorReadClient.resolve(any(Request.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); + return resolved; + }); + + ReadStartSessionTemplateAssociationResponse originalWire = response(1L); + ReadStartSessionTemplateAssociationResponse changedWire = response(2L); + try (MockedStatic codec = + mockStatic(StartSessionTemplateAssociationReadGrpcCodec.class)) { + codec + .when(() -> StartSessionTemplateAssociationReadGrpcCodec.toResponse(originalResult)) + .thenReturn(originalWire); + codec + .when(() -> StartSessionTemplateAssociationReadGrpcCodec.toResponse(changedResult)) + .thenReturn(changedWire); + + assertThatThrownBy(() -> fixture.service.continueOriginalEvidence(fixture.tuple)) + .isInstanceOf( + GameSessionStartSessionLaunchDescriptorRepository + .StartSessionLaunchDescriptorConflictException.class) + .hasMessageContaining("Original immutable selection changed"); + } + + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(2); + verify(fixture.descriptorReadClient).resolve(any(Request.class)); + verify(fixture.accountProjectionClient, times(2)).read(fixture.tuple, ATTEMPT_ID, 8L); + verifyNoMoreInteractions(fixture.accountProjectionClient); + verify(fixture.attemptRepository).beginEvidenceContinuation(fixture.tuple); + verifyNoMoreInteractions(fixture.attemptRepository); + verify(fixture.associationRepository, times(2)).findPinned(fixture.continuation); + verifyNoMoreInteractions(fixture.associationRepository); + verify(fixture.descriptorRepository, never()).pin(fixture.continuation, resolved); + } + + @Test + void exactUnchangedReplayReadsOutsideSqlAndPinsOnlyTheExistingOpaqueContinuation() { + Fixture fixture = new Fixture(NAMESPACE); + Result originalResult = fixture.originalResult(); + PinnedAssociationSnapshot original = fixture.snapshot(originalResult); + when(fixture.associationRepository.findPinned(fixture.continuation)) + .thenReturn(Optional.of(original), Optional.of(original)); + ReadRedeemedOperationProjectionResponse projection = redeemedProjection("original"); + when(fixture.accountProjectionClient.read(fixture.tuple, ATTEMPT_ID, 8L)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); + return projection; + }); + StartSessionLaunchDescriptorGrpcCodec.Resolved resolved = + mock(StartSessionLaunchDescriptorGrpcCodec.Resolved.class); + PinnedLaunchDescriptorSnapshot pinned = + new PinnedLaunchDescriptorSnapshot( + resolved, + new byte[] {1}, + new byte[] {2}, + REQUEST_DIGEST, + RESPONSE_DIGEST, + Instant.parse("2026-10-10T00:00:00Z")); + when(fixture.descriptorReadClient.resolve(any(Request.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); + return resolved; + }); + when(fixture.descriptorRepository.pin(fixture.continuation, resolved)).thenReturn(pinned); + + ReadStartSessionTemplateAssociationResponse originalWire = response(1L); + try (MockedStatic codec = + mockStatic(StartSessionTemplateAssociationReadGrpcCodec.class)) { + codec + .when(() -> StartSessionTemplateAssociationReadGrpcCodec.toResponse(originalResult)) + .thenReturn(originalWire); + + assertThat(fixture.service.continueOriginalEvidence(fixture.tuple)).isSameAs(pinned); + } + + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(2); + InOrder remoteOrder = inOrder(fixture.accountProjectionClient, fixture.descriptorReadClient); + remoteOrder.verify(fixture.accountProjectionClient).read(fixture.tuple, ATTEMPT_ID, 8L); + remoteOrder.verify(fixture.descriptorReadClient).resolve(any(Request.class)); + remoteOrder.verify(fixture.accountProjectionClient).read(fixture.tuple, ATTEMPT_ID, 8L); + verify(fixture.accountProjectionClient, times(2)).read(fixture.tuple, ATTEMPT_ID, 8L); + verifyNoMoreInteractions(fixture.accountProjectionClient); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); + verify(fixture.descriptorReadClient).resolve(requestCaptor.capture()); + Request replayRequest = requestCaptor.getValue(); + assertThat(replayRequest.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(replayRequest.canonicalPostAuthorizationTuple()) + .isEqualTo(fixture.tuple.canonicalBytes()); + assertThat(replayRequest.ownerAttemptId()).isEqualTo(ATTEMPT_ID); + assertThat(replayRequest.ownerFence()).isEqualTo(8L); + assertThat(replayRequest.selection()) + .isEqualTo(new ExactReplay(VERSION_ID, COMMIT_ID, PUBLISH_WORKFLOW_ID, ASSOCIATION_DIGEST)); + + verify(fixture.attemptRepository).beginEvidenceContinuation(fixture.tuple); + verifyNoMoreInteractions(fixture.attemptRepository); + verify(fixture.associationRepository, times(2)).findPinned(fixture.continuation); + verifyNoMoreInteractions(fixture.associationRepository); + verify(fixture.descriptorRepository).pin(fixture.continuation, resolved); + verifyNoMoreInteractions(fixture.descriptorRepository); + } + + private static ReadStartSessionTemplateAssociationResponse response(long phaseEpoch) { + return ReadStartSessionTemplateAssociationResponse.newBuilder() + .setReferencePhaseEpoch(phaseEpoch) + .build(); + } + + private static ReadRedeemedOperationProjectionResponse redeemedProjection(String identity) { + // Synthetic marker only: this unit test proves equality/order, not Account currentness. + return ReadRedeemedOperationProjectionResponse.newBuilder() + .setControlPlaneRequestId(identity) + .build(); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String namespace) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "unit-only continuation identity fixture"); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "descriptor-continuation-request", ACTOR, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre, namespace), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, String namespace) { + String tenant = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", namespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "e".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + "2030-01-01T00:00:00Z", + "expiresAt", + "2030-01-01T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + ISSUANCE_ID.toString(), + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException("Could not encode the typed tuple fixture", invalid); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Fixture { + private final TrackingTransactionManager transactionManager = new TrackingTransactionManager(); + private final GameSessionStartSessionOperatorAttemptRepository attemptRepository = + mock(GameSessionStartSessionOperatorAttemptRepository.class); + private final GameSessionStartSessionTemplateAssociationRepository associationRepository = + mock(GameSessionStartSessionTemplateAssociationRepository.class); + private final GameSessionStartSessionLaunchDescriptorRepository descriptorRepository = + mock(GameSessionStartSessionLaunchDescriptorRepository.class); + private final StartSessionRedeemedOperationProjectionClient accountProjectionClient = + mock(StartSessionRedeemedOperationProjectionClient.class); + private final StartSessionLaunchDescriptorReadClient descriptorReadClient = + mock(StartSessionLaunchDescriptorReadClient.class); + private final StartSessionPostAuthorizationExecutionTuple tuple; + private final EvidenceContinuation continuation = mock(EvidenceContinuation.class); + private final GameSessionStartSessionLaunchDescriptorContinuationService service; + + private Fixture(String workloadNamespace) { + tuple = tuple(workloadNamespace); + when(attemptRepository.beginEvidenceContinuation(tuple)).thenReturn(continuation); + service = + new GameSessionStartSessionLaunchDescriptorContinuationService( + attemptRepository, + associationRepository, + descriptorRepository, + accountProjectionClient, + descriptorReadClient, + transactionManager, + workloadNamespace); + } + + private Result originalResult() { + Request originalRequest = + new Request( + StartSessionTemplateAssociationReadEvidence.SCHEMA_VERSION, + NAMESPACE, + READ_ID, + tuple.canonicalBytes(), + ATTEMPT_ID, + 8L, + new InitialConfigured()); + Result result = mock(Result.class); + Association association = mock(Association.class); + when(result.request()).thenReturn(originalRequest); + when(result.association()).thenReturn(association); + when(association.canonicalVersionId()).thenReturn(VERSION_ID); + when(association.selectedCommitId()).thenReturn(COMMIT_ID); + when(association.publishWorkflowId()).thenReturn(PUBLISH_WORKFLOW_ID); + when(association.associationDigest()).thenReturn(ASSOCIATION_DIGEST); + return result; + } + + private PinnedAssociationSnapshot snapshot(Result result) { + return new PinnedAssociationSnapshot( + result, REQUEST_DIGEST, RESPONSE_DIGEST, Instant.parse("2026-10-10T00:00:00Z")); + } + } + + /** A resource-free manager that exposes TransactionTemplate's active callback boundary. */ + private static final class TrackingTransactionManager implements PlatformTransactionManager { + private int startedTransactions; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Nested test transactions are not supported"); + } + if (definition.getPropagationBehavior() != TransactionDefinition.PROPAGATION_REQUIRES_NEW + || definition.getIsolationLevel() != TransactionDefinition.ISOLATION_READ_COMMITTED + || definition.isReadOnly()) { + throw new IllegalStateException("Continuation transaction settings changed"); + } + startedTransactions++; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.initSynchronization(); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + clearActiveTransaction(); + } + + @Override + public void rollback(TransactionStatus status) { + clearActiveTransaction(); + } + + private static void clearActiveTransaction() { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } +} From ac26785ac82fa045d2d1242e675bc63f2fc1c32d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:31:55 +1300 Subject: [PATCH 02/22] Prepare inactive canonical Game Session initial-admission owner foundation --- .../player-access-and-session.md | 2 + .../AuthoredWorldLaunchDescriptorClient.java | 201 +++ .../StartSessionOperatorRedemptionClient.java | 287 ++++ ...nonicalClosedAdmissionPointerSnapshot.java | 60 + .../CanonicalInitialAdmissionWorldProof.java | 85 + .../CanonicalLaunchPreparationSnapshot.java | 73 + ...anonicalClosedAdmissionPointerRequest.java | 73 + ...eateCanonicalLaunchPreparationRequest.java | 130 ++ ...nicalCurrentOpenPointerSnapshotDigest.java | 262 +++ .../CanonicalInitialAdmissionRepository.java | 1472 +++++++++++++++++ ...onCanonicalAdmissionPointerRepository.java | 1074 ++++++++++++ ...nCanonicalLaunchPreparationRepository.java | 654 ++++++++ ...meplayAdmissionPointerEventRepository.java | 138 ++ .../CanonicalInitialAdmissionService.java | 14 + ...anonicalInitialAdmissionWorldVerifier.java | 14 + ...sionCanonicalLaunchPreparationService.java | 444 +++++ ...ssionOperatorAuthorizationCoordinator.java | 232 +++ ...abaseCanonicalInitialAdmissionService.java | 115 ++ ...ialAdmissionRepositoryIntegrationTest.java | 830 ++++++++++ ...unchPreparationServiceIntegrationTest.java | 590 +++++++ ...thorizationCoordinatorIntegrationTest.java | 405 +++++ ...lCurrentOpenPointerSnapshotDigestTest.java | 234 +++ ...rtSessionOperatorRedemptionClientTest.java | 415 +++++ ...nonicalAdmissionPointerRepositoryTest.java | 232 +++ ...CanonicalLaunchPreparationServiceTest.java | 1224 ++++++++++++++ ...nOperatorAuthorizationCoordinatorTest.java | 507 ++++++ ...eCanonicalInitialAdmissionServiceTest.java | 164 ++ 27 files changed, 9931 insertions(+) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.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 7d196919c2..6967e94534 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 Game Session has an unregistered original-claim evidence-continuation preparation: owner repositories, typed read/pin carriers, before-and-after authenticated Account projection reads outside SQL, and database-clock claim/reference-expiry checks at descriptor pinning. Consolidated Common/Game Session unit and non-container integration checks pass, as do generated-source compilation, formatting, static analysis, and documentation checks. PostgreSQL fixtures cover expiry, exact replay, mismatch, and pin races but remain unexecuted locally without Docker. Genuine Account original-redeemed receiver revalidation and full pointer/audit/live-owner composition remain required; mocked responses do not prove that receiver. This preparation grants no new mutation authorization or admission and does not establish playable closure. The bounded contract is owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). +The same inactive preparation now includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These new repositories, coordinator and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Consolidated local checks passed in 2m36s: 271 Common and 1,992 Game Session unit definitions had zero failures (17 Game Session skips); 208 integration definitions executed 18 and skipped 190 without Docker, while cross-service definitions executed one and skipped 38. The new PostgreSQL fixtures compile but have not physically executed. The prepared request requires a World-owned hold-binding digest and supports a CLOSED origin that the current no-prior-pointer World hold RPC does not supply; those interfaces must converge before authenticated composition. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. + The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. The 7a physical and local proof scopes, failures, and V98 limitation are detailed below and in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Hosted-terms acceptance, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898/#2848 and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). Proof qualification for the Account source/currentness cut: at `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2`, the physical Account suite ran 92 cases with zero skips. Fresh installation through V97, V73 upgrade, the closed reset/logout V80 case, and the terms-binding V86 case passed. Three other cases failed: a fixture supplied `varchar` where `timestamptz` was expected, a schema identifier exceeded PostgreSQL's 63-character limit, and a rejection-message expectation differed. A subsequent historical post-7a local-repair snapshot passed the consolidated Account check in 28 seconds; the unchanged 636 Account unit outputs and 245 Common unit outputs were reused. Its local integration run executed two cases and skipped 83 without Docker; those counts are not the corrected V98 batch or current-head proof. The corrected V98 batch at `3123c3d883cb025eb28149bd62c99ec389c9f5fb` reported 86 local integration cases, with two executed and 84 skipped, and made no physical PostgreSQL claim. Smoke run `37983056841` passed against 7a in 15m36s. V98 and the new disclosure persistence proof have not yet been physically executed, so the physical run does not qualify that migration. The V84 truncate-guard additions in this batch are later SQL and likewise have not been physically verified; the 7a result predates those changes. These bounded results do not establish whole-suite Account readiness or activation. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for exact scope and limitations. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java new file mode 100644 index 0000000000..0cfe9621fe --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java @@ -0,0 +1,201 @@ +package net.firedevops.firemud.common.gamedesign; + +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.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 net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; + +/** + * Explicit mTLS client for exact authored-world launch descriptor resolution and owner readback. + */ +public final class AuthoredWorldLaunchDescriptorClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignServiceGrpc.GameDesignServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AuthoredWorldLaunchDescriptorClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AuthoredWorldLaunchDescriptorClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Authored-world launch descriptor client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Authored-world launch descriptor client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Resolves a descriptor for exactly the supplied authored-world request tuple. */ + public AuthoredWorldLaunchDescriptorEvidence resolve( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(request)); + try { + return AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid authored-world launch descriptor evidence", exception); + } + } + + /** Reads back the immutable result using a separate read request UUID and the complete tuple. */ + public AuthoredWorldLaunchDescriptorEvidence get( + AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.expectedRequest().targetNamespace()); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getLaunchDescriptor(AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(request)); + try { + return AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid exact authored-world launch descriptor readback", + exception); + } + } + + /** Reads and validates the descriptor and separate release attestation as one exact pair. */ + public CompleteLaunchBindingEvidence getComplete(GetLaunchDescriptorRequest request) { + Objects.requireNonNull(request, "request"); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCompleteLaunchBinding(request); + try { + CompleteLaunchBindingEvidence evidence = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response); + requireNamespace(evidence.descriptor().targetNamespace()); + return evidence; + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid complete authored-world launch binding evidence", + exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub(ManagedChannel channel) { + String expectedGameDesignPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedGameDesignPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedGameDesignPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignServiceGrpc.GameDesignServiceBlockingStub requireStub() { + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Authored-world launch descriptor client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Launch descriptor request must use the configured workload namespace"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null) { + throw new IllegalArgumentException("gRPC mTLS configuration is required"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Launch descriptor reads require 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( + "Launch descriptor reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Launch descriptor reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Launch descriptor " + label + " must be a readable file-backed path", exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Launch descriptor " + label + " must be an existing readable file"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java new file mode 100644 index 0000000000..0bc51e4aaa --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java @@ -0,0 +1,287 @@ +package net.firedevops.firemud.gamesession.client; + +import com.google.protobuf.ByteString; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +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.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; + +/** + * Typed Game Session client for Account's StartSession redemption RPC, registered only by the + * disabled-by-default owner authorization configuration. + * + *

This transport does not acquire claims, retry ambiguous redemption, issue references, dispatch + * a mutation, or transition an owner attempt to a terminal result. The raw reference exists only in + * the bounded in-flight request object. + */ +public class StartSessionOperatorRedemptionClient + extends AbstractReloadingBlockingGrpcClient< + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub> { + private static final int MAX_PRE_AUTHORIZATION_TUPLE_BYTES = 8 * 1_024; + private static final int MAX_AUTHORIZATION_REFERENCE_BYTES = 128; + private static final long REDEMPTION_DEADLINE_SECONDS = 5L; + private static final Pattern OPAQUE_REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final Pattern AUTHORIZATION_REFERENCE_FINGERPRINT = + Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final Clock clock; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "This constructor validates input only; managed channels are acquired later by initialize().") + public StartSessionOperatorRedemptionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer) { + this(endpoints, tlsProps, channelFactory, stubCustomizer, Clock.systemUTC()); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "This constructor validates input only; managed channels are acquired later by initialize().") + public StartSessionOperatorRedemptionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + Clock clock) { + super( + endpoints, + requireMutualTls(tlsProps), + channelFactory, + stubCustomizer, + StartSessionOperatorRedemptionClient.class); + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + /** + * Opens the managed mutual-TLS channel only when an owning workflow explicitly initializes it. + */ + public void initialize() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + buildStub(ManagedChannel channel) { + return applyStubCustomizer( + StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel) + .withCompression("gzip")); + } + + /** + * Redeems once for the exact newly-created Game Session owner claim. Transport ambiguity is + * propagated unchanged; this method never retries or alters the pending owner record. + */ + public RedemptionResult redeem( + StartSessionPostAuthorizationExecutionTuple tuple, + String transientOperatorAuthorizationReference, + AttemptClaim actualGameSessionClaim) { + Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); + Objects.requireNonNull(actualGameSessionClaim, "Game Session owner attempt claim is required"); + requireExactClaimBinding(tuple, actualGameSessionClaim); + requireOpaqueReference(transientOperatorAuthorizationReference); + requireUnexpiredTupleEvidence(tuple); + + byte[] canonicalPreTuple = + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8); + if (canonicalPreTuple.length == 0 + || canonicalPreTuple.length > MAX_PRE_AUTHORIZATION_TUPLE_BYTES) { + throw new IllegalArgumentException( + "canonical StartSession pre-authorization tuple is over its bound"); + } + RedeemOperatorAuthorizationRequest request = + RedeemOperatorAuthorizationRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(canonicalPreTuple)) + .setOperatorAuthorizationReference(transientOperatorAuthorizationReference) + .setAuthorizationReferenceFingerprint(tuple.authorizationReferenceFingerprint()) + .setReservationOwnerId(tuple.reservationOwnerId().toString()) + .setReservationClaimFence(tuple.reservationClaimFence()) + .setOwnerAttemptId(actualGameSessionClaim.ownerAttemptId().toString()) + .setOwnerFence(actualGameSessionClaim.ownerFence()) + .build(); + + var response = + requireStub() + .withDeadlineAfter(REDEMPTION_DEADLINE_SECONDS, TimeUnit.SECONDS) + .redeemOperatorAuthorization(request); + AccountRedemptionProjection projection = validateResponse(response, tuple); + return new RedemptionResult(actualGameSessionClaim, projection, response.getReplay()); + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + requireStub() { + var value = stub(); + if (value == null) { + throw new IllegalStateException( + "Account StartSession redemption client has not been explicitly initialized"); + } + return value; + } + + private AccountRedemptionProjection validateResponse( + RedeemOperatorAuthorizationResponse response, + StartSessionPostAuthorizationExecutionTuple tuple) { + try { + if (response == null || !response.getUnknownFields().asMap().isEmpty()) { + throw malformedResponse(); + } + String fingerprint = response.getAuthorizationReferenceFingerprint(); + if (fingerprint == null + || !AUTHORIZATION_REFERENCE_FINGERPRINT.matcher(fingerprint).matches() + || !tuple.authorizationReferenceFingerprint().equals(fingerprint)) { + throw malformedResponse(); + } + + byte[] responseBundle = response.getAuthorityEvidenceBundle().toByteArray(); + byte[] originalBundle = tuple.authorityEvidenceBundleBytes(); + if (responseBundle.length == 0 || !Arrays.equals(responseBundle, originalBundle)) { + throw malformedResponse(); + } + UUID issuanceOperationId = canonicalNonNilUuid(response.getIssuanceOperationId()); + long issuanceFence = response.getIssuanceFence(); + if (issuanceFence <= 0L) { + throw malformedResponse(); + } + + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(responseBundle); + bundle.requireTupleBinding(tuple.preAuthorizationTuple()); + bundle.requireReferenceBinding(tuple.bundleReference()); + if (!bundle.issuanceOperationId().equals(issuanceOperationId) + || !tuple.issuanceFence().equals(Long.toString(issuanceFence)) + || !bundle.issuanceFence().equals(Long.toString(issuanceFence)) + || !bundle.expiresAt().isAfter(clock.instant())) { + throw malformedResponse(); + } + return new AccountRedemptionProjection( + fingerprint, responseBundle, issuanceOperationId, issuanceFence); + } catch (IllegalStateException expected) { + throw expected; + } catch (RuntimeException malformed) { + throw malformedResponse(); + } + } + + private void requireUnexpiredTupleEvidence(StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + bundle.requireTupleBinding(tuple.preAuthorizationTuple()); + bundle.requireReferenceBinding(tuple.bundleReference()); + if (!bundle.expiresAt().isAfter(clock.instant())) { + throw new IllegalStateException("Account StartSession authorization evidence has expired"); + } + } + + private static void requireExactClaimBinding( + StartSessionPostAuthorizationExecutionTuple tuple, AttemptClaim claim) { + if (!tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(claim.targetNamespace()) + || !tuple.controlPlaneRequestId().equals(claim.controlPlaneRequestId()) + || claim.ownerAttemptId().equals(NIL_UUID) + || claim.ownerMutationId().equals(NIL_UUID) + || claim.claimOwnerId().equals(NIL_UUID) + || claim.ownerFence() <= 0L) { + throw new IllegalArgumentException( + "Game Session owner attempt claim differs from the complete StartSession tuple"); + } + } + + private static void requireOpaqueReference(String value) { + if (value == null + || !OPAQUE_REFERENCE.matcher(value).matches() + || value.getBytes(StandardCharsets.UTF_8).length > MAX_AUTHORIZATION_REFERENCE_BYTES) { + throw new IllegalArgumentException("transient Account authorization reference is malformed"); + } + } + + private static UUID canonicalNonNilUuid(String value) { + if (value == null || !CANONICAL_UUID.matcher(value).matches()) { + throw malformedResponse(); + } + try { + UUID parsed = UUID.fromString(value); + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { + throw malformedResponse(); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw malformedResponse(); + } + } + + private static CommonGrpcClientProperties requireMutualTls( + CommonGrpcClientProperties tlsProperties) { + Objects.requireNonNull(tlsProperties, "gRPC TLS properties are required"); + if (tlsProperties.isPlaintext() + || blank(tlsProperties.getCertChain()) + || blank(tlsProperties.getPrivateKey()) + || blank(tlsProperties.getCaCert())) { + throw new IllegalArgumentException( + "Account StartSession redemption requires configured mutual TLS credentials and CA"); + } + return tlsProperties; + } + + private static boolean blank(String value) { + return value == null || value.isBlank(); + } + + private static IllegalStateException malformedResponse() { + return new IllegalStateException( + "Account returned a malformed or tuple-substituted StartSession redemption projection"); + } + + /** Successful response bound to the exact locally reserved owner claim, without raw secret. */ + public record RedemptionResult( + AttemptClaim gameSessionClaim, + AccountRedemptionProjection projection, + boolean accountReplay) { + public RedemptionResult { + Objects.requireNonNull(gameSessionClaim, "Game Session owner claim is required"); + Objects.requireNonNull(projection, "Account redemption projection is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java new file mode 100644 index 0000000000..6ac773e430 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.gamesession.dto; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import org.springframework.lang.Nullable; + +/** Exact committed owner evidence for one initial canonical CLOSED route. */ +public record CanonicalClosedAdmissionPointerSnapshot( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + String worldSlug, + String realmSlug, + long pointerVersion, + long catalogRevision, + String admissionState, + @Nullable UUID admissibleGameInstanceId, + UUID requestId, + String requestDigest, + String receiptDigest, + String actorPrincipal, + String reason, + long auditEventId, + Instant updatedAt, + CanonicalRealmCatalogSnapshot catalogSnapshot) { + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "CLOSED routing requires the nullable admissible instance to be absent; this constructor rejects any supplied UUID.") + public CanonicalClosedAdmissionPointerSnapshot { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(admissionState, "admissionState"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + Objects.requireNonNull(actorPrincipal, "actorPrincipal"); + Objects.requireNonNull(reason, "reason"); + Objects.requireNonNull(updatedAt, "updatedAt"); + Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + if (!"CLOSED".equals(admissionState) + || admissibleGameInstanceId != null + || pointerVersion != 1L + || catalogRevision != catalogSnapshot.catalogRevision() + || !targetNamespace.equals(catalogSnapshot.targetNamespace()) + || !canonicalTenantId.equals(catalogSnapshot.tenantId()) + || !realmId.equals(catalogSnapshot.realmId()) + || !worldSlug.equals(catalogSnapshot.worldSlug()) + || !realmSlug.equals(catalogSnapshot.realmSlug()) + || auditEventId <= 0L) { + throw new IllegalArgumentException( + "Canonical closed pointer snapshot does not match its exact initial catalog evidence"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java new file mode 100644 index 0000000000..610fd2f04d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Exact World-owned ACTIVE lifecycle and initial-admission hold read returned outside SQL. */ +public record CanonicalInitialAdmissionWorldProof( + String initialAdmissionRequestId, + String requestDigest, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + String lifecycleState, + long activeLifecycleEpoch, + CanonicalInitialAdmissionRequest.OriginKind originKind, + long expectedCatalogRevision, + Long expectedPriorPointerVersion, + UUID holdId, + UUID holdFence, + String holdBindingDigest) { + private static final Pattern WORLD_BINDING_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + public CanonicalInitialAdmissionWorldProof { + Objects.requireNonNull(initialAdmissionRequestId, "initialAdmissionRequestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + Objects.requireNonNull(canonicalGameInstanceId, "canonicalGameInstanceId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + Objects.requireNonNull(lifecycleState, "lifecycleState"); + Objects.requireNonNull(originKind, "originKind"); + Objects.requireNonNull(holdId, "holdId"); + Objects.requireNonNull(holdFence, "holdFence"); + if (!WORLD_BINDING_DIGEST + .matcher(Objects.requireNonNull(holdBindingDigest, "holdBindingDigest")) + .matches()) { + throw new IllegalArgumentException("World hold proof has an invalid binding digest"); + } + if (activeLifecycleEpoch <= 0L + || expectedCatalogRevision <= 0L + || !"ACTIVE".equals(lifecycleState)) { + throw new IllegalArgumentException("World proof must contain an exact positive ACTIVE epoch"); + } + if ((originKind == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER + && expectedPriorPointerVersion != null) + || (originKind == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED + && (expectedPriorPointerVersion == null || expectedPriorPointerVersion <= 0L))) { + throw new IllegalArgumentException("World hold proof has an invalid tagged origin"); + } + } + + public void requireMatches(CanonicalInitialAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + if (!initialAdmissionRequestId.equals(request.initialAdmissionRequestId()) + || !requestDigest.equals(request.requestDigest()) + || !targetNamespace.equals(request.targetNamespace()) + || !canonicalTenantId.equals(request.canonicalTenantId()) + || !worldSlug.equals(request.worldSlug()) + || !realmId.equals(request.realmId()) + || !playableStateNamespaceId.equals(request.playableStateNamespaceId()) + || !playableStateScope.equals(request.playableStateScope()) + || !canonicalGameInstanceId.equals(request.canonicalGameInstanceId()) + || !canonicalVersionId.equals(request.canonicalVersionId()) + || activeLifecycleEpoch != request.activeLifecycleEpoch() + || originKind != request.originKind() + || expectedCatalogRevision != request.expectedCatalogRevision() + || !Objects.equals(expectedPriorPointerVersion, request.expectedPriorPointerVersion()) + || !holdId.equals(request.holdId()) + || !holdFence.equals(request.holdFence()) + || !holdBindingDigest.equals(request.holdBindingDigest())) { + throw new IllegalArgumentException( + "World ACTIVE/hold proof does not match the exact initial admission request"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java new file mode 100644 index 0000000000..7ffea40a81 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; + +/** Exact immutable source/catalog/descriptor evidence consumed by one launch preparation. */ +public record CanonicalLaunchPreparationSnapshot( + UUID operationId, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalogSnapshot, + IntakeReceipt sourceIntakeReceipt, + AuthoredWorldLaunchDescriptorEvidence launchDescriptorEvidence, + String requestDigest, + String receiptDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + public CanonicalLaunchPreparationSnapshot { + requireNonNil(operationId, "operationId"); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(launchDescriptorEvidence, "launchDescriptorEvidence"); + requireDigest(requestDigest, "requestDigest"); + requireDigest(receiptDigest, "receiptDigest"); + requireConsumedEvidence( + request, catalogSnapshot, sourceIntakeReceipt, launchDescriptorEvidence); + } + + /** Revalidates the complete closed shared descriptor and all local identity joins. */ + public void requireValid() { + requireConsumedEvidence( + request, catalogSnapshot, sourceIntakeReceipt, launchDescriptorEvidence); + launchDescriptorEvidence.requireValid(); + } + + private static void requireConsumedEvidence( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !source.equals(catalog.sourceIntakeReceipt()) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !descriptor.request().equals(request.descriptorRequest(catalog, source.source()))) { + throw new IllegalArgumentException( + "Launch preparation evidence does not match its exact request, catalog, and source"); + } + descriptor.requireValid(); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java new file mode 100644 index 0000000000..c07f92c6e1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Local audit inputs for one immutable initial canonical CLOSED admission pointer. */ +public record CreateCanonicalClosedAdmissionPointerRequest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID catalogCreationRequestId, + long catalogRevision, + String actorPrincipal, + String reason) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CreateCanonicalClosedAdmissionPointerRequest { + requireNonNil(requestId, "requestId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(catalogCreationRequestId, "catalogCreationRequestId"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + validateBoundedText(actorPrincipal, "actorPrincipal", 200, 800); + validateBoundedText(reason, "reason", 500, 2000); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void validateBoundedText( + String value, String name, int maximumCodePoints, int maximumUtf8Bytes) { + Objects.requireNonNull(value, name); + byte[] bytes = strictUtf8(value, name); + if (value.isBlank() + || value.codePointCount(0, value.length()) > maximumCodePoints + || bytes.length > maximumUtf8Bytes) { + throw new IllegalArgumentException(name + " must be bounded and nonblank"); + } + } + + private static byte[] strictUtf8(String value, String name) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(name + " must be well-formed UTF-8 text", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java new file mode 100644 index 0000000000..1b9b7cdded --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java @@ -0,0 +1,130 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.springframework.lang.Nullable; + +/** Immutable input for source-qualified Game Design launch preparation; it grants no authority. */ +public record CreateCanonicalLaunchPreparationRequest( + String controlPlaneRequestId, + UUID actingAccountUuid, + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID catalogCreationRequestId, + long catalogRevision, + UUID sourceIntakeOperationId, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + @Nullable String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + @Nullable Long sourceVersionId, + boolean targetVersionIdPresent, + @Nullable Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + @Nullable String requestedRuntimeFlagsJson) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CreateCanonicalLaunchPreparationRequest { + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireNonNil(actingAccountUuid, "actingAccountUuid"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(catalogCreationRequestId, "catalogCreationRequestId"); + requireNonNil(sourceIntakeOperationId, "sourceIntakeOperationId"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + if (gameTemplateId <= 0L) { + throw new IllegalArgumentException("gameTemplateId must be positive"); + } + requireOptional( + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + "requestedScriptPatchVersion"); + requireOptional(sourceVersionIdPresent, sourceVersionId, "sourceVersionId"); + if (sourceVersionIdPresent && sourceVersionId <= 0L) { + throw new IllegalArgumentException("sourceVersionId must be positive when present"); + } + requireOptional(targetVersionIdPresent, targetVersionId, "targetVersionId"); + if (targetVersionIdPresent && targetVersionId <= 0L) { + throw new IllegalArgumentException("targetVersionId must be positive when present"); + } + requireOptional( + requestedRuntimeFlagsJsonPresent, requestedRuntimeFlagsJson, "requestedRuntimeFlagsJson"); + } + + public AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest( + CanonicalRealmCatalogSnapshot catalog, AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(source, "source"); + return new AuthoredWorldLaunchDescriptorEvidence.Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + catalog.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text, name); + } + } + + private static void requireText(String value, String name, int maxUtf8Bytes) { + Objects.requireNonNull(value, name); + byte[] bytes = strictUtf8(value, name); + if (value.isBlank() || bytes.length > maxUtf8Bytes) { + throw new IllegalArgumentException(name + " must be nonblank and bounded"); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static byte[] strictUtf8(String value, String name) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(name + " must be well-formed UTF-8", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java new file mode 100644 index 0000000000..5ba3c50e1c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java @@ -0,0 +1,262 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; + +/** Closed canonical bytes for the owner-resolved current OPEN pointer projection. */ +final class CanonicalCurrentOpenPointerSnapshotDigest { + static final String DOMAIN = "gs-canonical-current-open-pointer-snapshot/v1"; + + private static final int MAX_STRING_BYTES = 4096; + private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern OWNER_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String AUDIT_ACTOR = "game-session-canonical-initial-admission"; + private static final String AUDIT_REASON = "World-held initial admission"; + + private CanonicalCurrentOpenPointerSnapshotDigest() {} + + static String digest(Projection projection) { + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonicalBytes(projection))); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + static byte[] canonicalBytes(Projection projection) { + Objects.requireNonNull(projection, "projection"); + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + writeString(output, DOMAIN); + output.writeInt(projection.representationVersion()); + writeString(output, projection.targetNamespace()); + writeUuid(output, projection.canonicalTenantId()); + writeString(output, projection.worldSlug()); + writeString(output, projection.worldDisplayName()); + writeUuid(output, projection.realmId()); + writeString(output, projection.realmSlug()); + writeString(output, projection.realmDisplayName()); + writeUuid(output, projection.playableStateNamespaceId()); + writeString(output, projection.playableStateScope()); + writeCounter(output, projection.catalogRevision()); + writeCounter(output, projection.pointerVersion()); + writeString(output, projection.admissionState()); + output.writeBoolean(projection.visible()); + output.writeBoolean(projection.publicProductionRealm()); + writeNullableBoolean(output, projection.requiresCharacterSelection()); + writeString(output, projection.characterCreationPolicy()); + writeUuid(output, projection.canonicalGameInstanceId()); + writeUuid(output, projection.canonicalVersionId()); + writeString(output, projection.initialAdmissionRequestId()); + writeString(output, projection.initialAdmissionRequestDigest()); + writeString(output, projection.originKind().name()); + writeNullableLong(output, projection.expectedPriorPointerVersion()); + writeCounter(output, projection.activeWorldEpoch()); + writeUuid(output, projection.holdId()); + writeUuid(output, projection.holdFence()); + writeString(output, projection.holdBindingDigest()); + writeString(output, projection.lastUpdatedBy()); + writeString(output, projection.lastUpdateReason()); + writeString(output, projection.preparedVersionUpgradeId()); + writeString(output, "COMMITTED"); + writeString(output, projection.ownerProofDigest()); + writeCounter(output, projection.auditEventId()); + writeString(output, projection.terminalAt().toString()); + } + return bytes.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Canonical pointer snapshot encoding failed", impossible); + } + } + + private static void writeUuid(DataOutputStream output, UUID value) throws IOException { + writeString(output, Objects.requireNonNull(value, "UUID").toString()); + } + + /** Strings are exact UTF-8 with a signed 32-bit byte count; -1 is the sole null marker. */ + private static void writeString(DataOutputStream output, String value) throws IOException { + if (value == null) { + output.writeInt(-1); + return; + } + byte[] encoded = strictUtf8(value); + if (encoded.length > MAX_STRING_BYTES) { + throw new IllegalArgumentException("Canonical snapshot string exceeds its byte bound"); + } + output.writeInt(encoded.length); + output.write(encoded); + } + + private static byte[] strictUtf8(String value) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException invalid) { + throw new IllegalArgumentException("Canonical snapshot string is not valid Unicode", invalid); + } + } + + private static void writeNullableBoolean(DataOutputStream output, Boolean value) + throws IOException { + output.writeByte(value == null ? 0 : value ? 2 : 1); + } + + private static void writeNullableLong(DataOutputStream output, Long value) throws IOException { + output.writeBoolean(value != null); + if (value != null) { + writeCounter(output, value); + } + } + + /** Long counters use their unique, nonlocalized base-10 representation. */ + private static void writeCounter(DataOutputStream output, long value) throws IOException { + writeString(output, Long.toString(value)); + } + + /** Values are copied from one validated V3 OPEN row and its exact terminal owner readback. */ + record Projection( + int representationVersion, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + String worldDisplayName, + UUID realmId, + String realmSlug, + String realmDisplayName, + UUID playableStateNamespaceId, + String playableStateScope, + long catalogRevision, + long pointerVersion, + String admissionState, + boolean visible, + boolean publicProductionRealm, + Boolean requiresCharacterSelection, + String characterCreationPolicy, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + String initialAdmissionRequestId, + String initialAdmissionRequestDigest, + OriginKind originKind, + Long expectedPriorPointerVersion, + long activeWorldEpoch, + UUID holdId, + UUID holdFence, + String holdBindingDigest, + String lastUpdatedBy, + String lastUpdateReason, + String preparedVersionUpgradeId, + String ownerProofDigest, + long auditEventId, + Instant terminalAt) { + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "Canonical OPEN projection requires absent selection and upgrade fields; the record stores those validated nulls without dereferencing them.") + Projection { + if (originKind == null) { + throw new IllegalArgumentException("Current OPEN pointer snapshot origin is required"); + } + OriginKind validatedOriginKind = originKind; + if (representationVersion != 3 + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !nonNil(canonicalTenantId) + || !RealmEntryPolicy.isCanonicalSlug(worldSlug) + || !text(worldDisplayName, 200) + || !nonNil(realmId) + || !RealmEntryPolicy.isCanonicalSlug(realmSlug) + || !text(realmDisplayName, 200) + || !nonNil(playableStateNamespaceId) + || !"SHARED".equals(playableStateScope) + || catalogRevision <= 0L + || pointerVersion <= 0L + || !"OPEN".equals(admissionState) + || !visible + || !publicProductionRealm + || requiresCharacterSelection != null + || !text(characterCreationPolicy, 32) + || !nonNil(canonicalGameInstanceId) + || !nonNil(canonicalVersionId) + || !text(initialAdmissionRequestId, 120) + || !REQUEST_DIGEST + .matcher(Objects.requireNonNull(initialAdmissionRequestDigest)) + .matches() + || (validatedOriginKind == OriginKind.NO_PRIOR_POINTER + && expectedPriorPointerVersion != null) + || (validatedOriginKind == OriginKind.EXPECT_CLOSED + && (expectedPriorPointerVersion == null || expectedPriorPointerVersion <= 0L)) + || activeWorldEpoch <= 0L + || !nonNil(holdId) + || !nonNil(holdFence) + || !OWNER_DIGEST.matcher(Objects.requireNonNull(holdBindingDigest)).matches() + || !AUDIT_ACTOR.equals(lastUpdatedBy) + || !AUDIT_REASON.equals(lastUpdateReason) + || preparedVersionUpgradeId != null + || !OWNER_DIGEST.matcher(Objects.requireNonNull(ownerProofDigest)).matches() + || auditEventId <= 0L + || terminalAt == null + || terminalAt.getNano() % 1_000 != 0) { + throw new IllegalArgumentException( + "Current OPEN pointer snapshot is incomplete or invalid"); + } + // Reject malformed UTF-16 rather than allowing replacement-byte collisions in the digest. + for (String value : + new String[] { + targetNamespace, + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + playableStateScope, + admissionState, + characterCreationPolicy, + initialAdmissionRequestId, + initialAdmissionRequestDigest, + validatedOriginKind.name(), + holdBindingDigest, + lastUpdatedBy, + lastUpdateReason, + ownerProofDigest + }) { + strictUtf8(value); + } + } + + private static boolean nonNil(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + private static boolean text(String value, int maxChars) { + return value != null + && !value.isBlank() + && value.equals(value.trim()) + && value.length() <= maxChars; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java new file mode 100644 index 0000000000..3442966f06 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java @@ -0,0 +1,1472 @@ +package net.firedevops.firemud.gamesession.repository; + +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.ExpectedClosedEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.PreparedExpectedClosed; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Durable Game Session owner transaction and exact readback for one canonical first-OPEN bind. */ +public class CanonicalInitialAdmissionRepository { + private static final String COMMITTED = "COMMITTED"; + private static final String PENDING = "PENDING"; + private static final String ABORTED = "ABORTED"; + private static final String AUDIT_ACTOR = "game-session-canonical-initial-admission"; + private static final String AUDIT_REASON = "World-held initial admission"; + private static final String COMMIT_PROOF_DOMAIN = + "gs-canonical-initial-admission-commit-proof/v1"; + private static final String ABORT_PROOF_DOMAIN = "gs-canonical-initial-admission-abort-proof/v1"; + private static final String OPERATION_TABLE = "game_session_canonical_initial_admission_attempt"; + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final GameSessionCanonicalAdmissionPointerRepository pointerRepository; + private final CanonicalGameInstanceLaunchAssociationRepository launchRepository; + private final GameplayAdmissionPointerEventRepository eventRepository; + + /** One exact current pointer row plus its validated owner result and GS-owned snapshot digest. */ + public record CurrentOpenSnapshot( + CanonicalInitialAdmissionOwnerProof ownerProof, String admissionPointerSnapshotDigest) { + private static final java.util.regex.Pattern SNAPSHOT_DIGEST = + java.util.regex.Pattern.compile("[0-9a-f]{64}"); + + public CurrentOpenSnapshot { + Objects.requireNonNull(ownerProof, "ownerProof"); + if (!ownerProof.provesCommit() + || admissionPointerSnapshotDigest == null + || !SNAPSHOT_DIGEST.matcher(admissionPointerSnapshotDigest).matches()) { + throw new IllegalArgumentException( + "Current OPEN snapshot requires committed owner proof and raw SHA-256 digest"); + } + } + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected owner collaborators are validated before use; construction acquires no resources.") + public CanonicalInitialAdmissionRepository( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameplayAdmissionPointerEventRepository eventRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.pointerRepository = Objects.requireNonNull(pointerRepository, "pointerRepository"); + this.launchRepository = Objects.requireNonNull(launchRepository, "launchRepository"); + this.eventRepository = Objects.requireNonNull(eventRepository, "eventRepository"); + } + + /** Persists the immutable request identity before remote World verification is attempted. */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public void reserve(CanonicalInitialAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + requireWritableReadCommittedOwnerTransaction(); + lockTarget(request); + Attempt existing = + findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); + if (existing != null && !PENDING.equals(existing.status())) { + requireSameRequestIdentity(existing, request); + return; + } + CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); + CanonicalInitialAdmissionLaunchTarget launchTarget = + lockLaunchTarget(request, existing == null); + requireRequestMatchesCatalogAndLaunch(request, catalog, launchTarget); + + if (existing != null) { + requireSameRequest(existing, request, launchTarget); + return; + } + Attempt otherPending = findPendingForRealm(request, true); + if (otherPending != null) { + throw new CanonicalInitialAdmissionConflictException( + "Another initial-admission request already owns the pending realm attempt"); + } + + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (target_namespace, initial_admission_request_id, request_digest, " + + "canonical_tenant_id, world_slug, realm_id, playable_state_namespace_id, " + + "playable_state_scope, canonical_game_instance_id, game_session_tenant_id, " + + "game_instance_id, canonical_version_id, runtime_version_id, " + + "expected_catalog_revision, origin_kind, " + + "expected_prior_pointer_version, active_lifecycle_epoch, hold_id, hold_fence, " + + "hold_binding_digest, status, created_at, updated_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', " + + "CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ)) ON CONFLICT DO NOTHING", + request.targetNamespace(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + launchTarget.association().gameSessionTenantId(), + launchTarget.gameInstanceId(), + request.canonicalVersionId(), + launchTarget.runtimeVersionId(), + request.expectedCatalogRevision(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest(), + utc(now), + utc(now)); + Attempt reserved = + findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); + if (reserved == null) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission request reservation conflicted with durable owner state"); + } + requireSameRequest(reserved, request, launchTarget); + if (inserted == 0 && !PENDING.equals(reserved.status())) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission request identity was concurrently terminalized"); + } + } + + /** + * Commits the first pointer, append-only audit and terminal owner result in one short + * transaction. + */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public void commit( + CanonicalInitialAdmissionRequest request, + CanonicalInitialAdmissionWorldProof worldProof, + PreparedExpectedClosed preparedExpectedClosed) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(worldProof, "worldProof"); + worldProof.requireMatches(request); + requireWritableReadCommittedOwnerTransaction(); + lockTarget(request); + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + lockAllAdmissionRepresentationsForNoPrior(); + } + CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); + Attempt attempt = requireAttemptForUpdate(request); + CanonicalInitialAdmissionLaunchTarget launchTarget = lockLaunchTarget(request, true); + requireSameRequest(attempt, request, launchTarget); + requireRequestMatchesCatalogAndLaunch(request, catalog, launchTarget); + if (!PENDING.equals(attempt.status())) { + return; + } + + ExpectedClosedEvidence closedOrigin = lockExpectedClosedOrigin(request, preparedExpectedClosed); + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + pointerRepository.requireNoAdmissionPointerRepresentations( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.worldSlug(), + catalog.realmSlug(), + launchTarget.association().gameSessionTenantId(), + launchTarget.gameInstanceId()); + } + + long pointerVersion = + request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER + ? 1L + : Math.addExact(request.expectedPriorPointerVersion(), 1L); + Instant committedAt = nextTimestamp(attempt.updatedAt()); + long pointerId = writeOpenPointer(request, catalog, launchTarget, pointerVersion, committedAt); + long auditEventId = + eventRepository.appendCanonicalInitialAdmissionOpen( + request, catalog, launchTarget, pointerVersion, catalog.catalogRevision(), committedAt); + String proofDigest = + commitProofDigest( + attempt, + pointerVersion, + auditEventId, + committedAt, + closedOrigin == null ? null : closedOrigin.originalRequestId(), + closedOrigin == null ? null : closedOrigin.requestDigest(), + closedOrigin == null ? null : closedOrigin.auditEventId()); + int updated = + dsl.execute( + "UPDATE " + + OPERATION_TABLE + + " SET status = 'COMMITTED', pointer_id = ?, pointer_version = ?, " + + "audit_event_id = ?, prior_pointer_request_id = ?, " + + "prior_pointer_request_digest = ?, prior_pointer_audit_event_id = ?, " + + "commit_proof_digest = ?, updated_at = CAST(? AS TIMESTAMPTZ), " + + "terminal_at = CAST(? AS TIMESTAMPTZ) " + + "WHERE target_namespace = ? AND initial_admission_request_id = ? AND status = 'PENDING'", + pointerId, + pointerVersion, + auditEventId, + closedOrigin == null ? null : closedOrigin.originalRequestId(), + closedOrigin == null ? null : closedOrigin.requestDigest(), + closedOrigin == null ? null : closedOrigin.auditEventId(), + proofDigest, + utc(committedAt), + utc(committedAt), + request.targetNamespace(), + request.initialAdmissionRequestId()); + if (updated != 1) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission attempt was concurrently terminalized before pointer commit"); + } + } + + /** + * Records a terminal local abort only while the exact expected prior authority is still current. + */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public void abort( + CanonicalInitialAdmissionRequest request, + PreparedExpectedClosed preparedExpectedClosed, + String reason) { + Objects.requireNonNull(request, "request"); + requireText(reason, "reason", 500); + requireWritableReadCommittedOwnerTransaction(); + lockTarget(request); + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + lockAllAdmissionRepresentationsForNoPrior(); + } + CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); + Attempt attempt = requireAttemptForUpdate(request); + CanonicalInitialAdmissionLaunchTarget launchTarget = lockLaunchTarget(request, false); + requireSameRequest(attempt, request, launchTarget); + requireRequestMatchesCatalogAndLaunch(request, catalog, launchTarget); + if (!PENDING.equals(attempt.status())) { + return; + } + + ExpectedClosedEvidence closedOrigin = lockExpectedClosedOrigin(request, preparedExpectedClosed); + if (closedOrigin == null) { + pointerRepository.requireNoAdmissionPointerRepresentations( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.worldSlug(), + catalog.realmSlug(), + launchTarget.association().gameSessionTenantId(), + launchTarget.gameInstanceId()); + } + Instant terminalAt = nextTimestamp(attempt.updatedAt()); + String abortProofDigest = + abortProofDigest( + attempt, + reason, + terminalAt, + closedOrigin == null ? null : closedOrigin.originalRequestId(), + closedOrigin == null ? null : closedOrigin.requestDigest(), + closedOrigin == null ? null : closedOrigin.auditEventId()); + int updated = + dsl.execute( + "UPDATE " + + OPERATION_TABLE + + " SET status = 'ABORTED', prior_pointer_request_id = ?, " + + "prior_pointer_request_digest = ?, prior_pointer_audit_event_id = ?, " + + "abort_proof_digest = ?, abort_reason = ?, updated_at = CAST(? AS TIMESTAMPTZ), " + + "terminal_at = CAST(? AS TIMESTAMPTZ) " + + "WHERE target_namespace = ? AND initial_admission_request_id = ? AND status = 'PENDING'", + closedOrigin == null ? null : closedOrigin.originalRequestId(), + closedOrigin == null ? null : closedOrigin.requestDigest(), + closedOrigin == null ? null : closedOrigin.auditEventId(), + abortProofDigest, + reason, + utc(terminalAt), + utc(terminalAt), + request.targetNamespace(), + request.initialAdmissionRequestId()); + if (updated != 1) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission attempt was concurrently terminalized before abort"); + } + } + + /** Reads the exact durable result only after the owner transaction has committed. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + String targetNamespace, String initialAdmissionRequestId) { + requireOutsideTransaction(); + Record row = findAttemptRecord(targetNamespace, initialAdmissionRequestId, false); + if (row == null) { + return Optional.empty(); + } + Attempt attempt = toAttempt(row); + if (PENDING.equals(attempt.status())) { + return Optional.of(toProof(attempt, CanonicalInitialAdmissionOwnerProof.Outcome.PENDING)); + } + if (COMMITTED.equals(attempt.status())) { + verifyCommittedReadback(attempt); + return Optional.of(toProof(attempt, CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + } + if (ABORTED.equals(attempt.status())) { + verifyAbortReadback(attempt); + return Optional.of(toProof(attempt, CanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)); + } + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Persisted initial-admission attempt has an unsupported owner outcome"); + } + + /** + * Reads the current canonical OPEN pointer and its exact committed initial-admission proof. This + * is a point-in-time owner read, not an authorization held through a later mutation. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public CanonicalInitialAdmissionOwnerProof readCurrentOpenForRealm( + String targetNamespace, UUID canonicalTenantUuid, UUID realmUuid) { + return readCurrentOpenSnapshotForRealm(targetNamespace, canonicalTenantUuid, realmUuid) + .ownerProof(); + } + + /** + * Reads the exact current canonical OPEN pointer and its committed proof as one owner snapshot. + * The digest commits to the validated current pointer projection, not the owner's commit-proof + * digest or a caller-provided echo. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public CurrentOpenSnapshot readCurrentOpenSnapshotForRealm( + String targetNamespace, UUID canonicalTenantUuid, UUID realmUuid) { + requireOutsideTransaction(); + requireCurrentOpenReadSelector(targetNamespace, canonicalTenantUuid, realmUuid); + + CurrentOpenPointer before = + readCurrentOpenPointer(targetNamespace, canonicalTenantUuid, realmUuid); + before.requireCanonicalOpen(targetNamespace, canonicalTenantUuid, realmUuid); + String requestId = before.initialAdmissionRequestId(); + if (requestId == null || requestId.isBlank()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer has no initial-admission request identity"); + } + + CanonicalInitialAdmissionOwnerProof proof = + read(targetNamespace, requestId) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer has no durable owner attempt")); + if (!proof.provesCommit() || !before.matches(proof)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer does not match its exact committed owner proof"); + } + + CurrentOpenPointer after = + readCurrentOpenPointer(targetNamespace, canonicalTenantUuid, realmUuid); + if (!before.equals(after)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer changed during owner readback"); + } + return new CurrentOpenSnapshot(proof, before.snapshotDigest(proof)); + } + + private CurrentOpenPointer readCurrentOpenPointer( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + List rows = + dsl.fetch( + "SELECT * FROM gameplay_admission_pointer " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "AND representation_version = 3 AND admission_state = 'OPEN'", + targetNamespace, + canonicalTenantId, + realmId); + if (rows.size() != 1) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Canonical realm must have exactly one current representation-version-3 OPEN pointer"); + } + return CurrentOpenPointer.from(rows.get(0)); + } + + private static void requireCurrentOpenReadSelector( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + if (targetNamespace == null || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace is not a canonical owner selector"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private ExpectedClosedEvidence lockExpectedClosedOrigin( + CanonicalInitialAdmissionRequest request, PreparedExpectedClosed prepared) { + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + if (prepared != null) { + throw new CanonicalInitialAdmissionConflictException( + "NO_PRIOR_POINTER cannot carry prepared CLOSED-origin evidence"); + } + return null; + } + if (prepared == null) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "EXPECT_CLOSED requires prepared original CLOSED owner evidence"); + } + ExpectedClosedEvidence evidence = pointerRepository.lockExpectedClosed(prepared); + if (!evidence.targetNamespace().equals(request.targetNamespace()) + || !evidence.canonicalTenantId().equals(request.canonicalTenantId()) + || !evidence.realmId().equals(request.realmId()) + || evidence.pointerVersion() != request.expectedPriorPointerVersion() + || evidence.catalogRevision() != request.expectedCatalogRevision()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Locked original CLOSED authority does not match the tagged request origin"); + } + return evidence; + } + + private long writeOpenPointer( + CanonicalInitialAdmissionRequest request, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launchTarget, + long pointerVersion, + Instant updatedAt) { + CanonicalGameInstanceLaunchAssociation association = launchTarget.association(); + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + Record inserted = + dsl.fetchOne( + "INSERT INTO gameplay_admission_pointer (" + + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "created_at, updated_at, public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state, canonical_game_instance_id, " + + "canonical_version_id, runtime_version_id, initial_admission_request_id, " + + "initial_admission_request_digest, initial_admission_origin_kind, " + + "initial_admission_prior_pointer_version, initial_admission_active_epoch, " + + "initial_admission_hold_id, initial_admission_hold_fence, " + + "initial_admission_hold_binding_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 'game-session-canonical-initial-admission', " + + "'World-held initial admission', ?, ?, ?, ?, ?, ?, 3, ?, ?, 'OPEN', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "RETURNING id", + catalog.worldSlug(), + catalog.realmSlug(), + catalog.sourceIntakeReceipt().source().worldDisplayName(), + catalog.realmDisplayName(), + association.gameSessionTenantId(), + launchTarget.gameInstanceId(), + pointerVersion, + catalog.visible(), + catalog.stateScope(), + catalog.characterCreationPolicy(), + toLocalDateTime(updatedAt), + toLocalDateTime(updatedAt), + catalog.publicProduction(), + catalog.catalogRevision(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + launchTarget.runtimeVersionId(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest()); + if (inserted == null || inserted.get("id", Long.class) == null) { + throw new CanonicalInitialAdmissionConflictException( + "Canonical initial OPEN pointer insert returned no owner row"); + } + return inserted.get("id", Long.class); + } + + Record pointer = + dsl.fetchOne( + "UPDATE gameplay_admission_pointer SET world_slug = ?, realm_slug = ?, " + + "world_display_name = ?, realm_display_name = ?, tenant_id = ?, game_instance_id = ?, " + + "pointer_version = ?, visible = ?, requires_character_selection = NULL, " + + "state_scope = ?, character_creation_policy = ?, " + + "last_updated_by = 'game-session-canonical-initial-admission', " + + "last_update_reason = 'World-held initial admission', updated_at = ?, " + + "public_production_realm = ?, catalog_revision = ?, playable_state_namespace_id = ?, " + + "representation_version = 3, admission_state = 'OPEN', canonical_game_instance_id = ?, " + + "canonical_version_id = ?, runtime_version_id = ?, initial_admission_request_id = ?, " + + "initial_admission_request_digest = ?, initial_admission_origin_kind = ?, " + + "initial_admission_prior_pointer_version = ?, initial_admission_active_epoch = ?, " + + "initial_admission_hold_id = ?, initial_admission_hold_fence = ?, " + + "initial_admission_hold_binding_digest = ? " + + "WHERE representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ? AND admission_state = 'CLOSED' " + + "AND pointer_version = ? AND catalog_revision = ? RETURNING id", + catalog.worldSlug(), + catalog.realmSlug(), + catalog.sourceIntakeReceipt().source().worldDisplayName(), + catalog.realmDisplayName(), + association.gameSessionTenantId(), + launchTarget.gameInstanceId(), + pointerVersion, + catalog.visible(), + catalog.stateScope(), + catalog.characterCreationPolicy(), + toLocalDateTime(updatedAt), + catalog.publicProduction(), + catalog.catalogRevision(), + catalog.playableStateNamespaceId(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + launchTarget.runtimeVersionId(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest(), + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.expectedPriorPointerVersion(), + request.expectedCatalogRevision()); + if (pointer == null || pointer.get("id", Long.class) == null) { + throw new CanonicalInitialAdmissionConflictException( + "Original CLOSED pointer changed before the initial OPEN CAS"); + } + return pointer.get("id", Long.class); + } + + private void verifyCommittedReadback(Attempt attempt) { + CanonicalInitialAdmissionRequest request = attempt.asRequest(); + CanonicalRealmCatalogSnapshot catalog = readExactCatalog(request); + Record evidence = + dsl.fetchOne( + "SELECT pointer.*, pointer.updated_at AS pointer_updated_at, " + + "event.id AS committed_audit_event_id, event.occurred_at AS audit_at, " + + "event.actor_principal AS audit_actor, event.reason AS audit_reason, " + + "event.target_namespace AS audit_target_namespace, " + + "event.canonical_tenant_id AS audit_canonical_tenant_id, " + + "event.world_slug AS audit_world_slug, event.realm_id AS audit_realm_id, " + + "event.world_display_name AS audit_world_display_name, " + + "event.realm_slug AS audit_realm_slug, " + + "event.realm_display_name AS audit_realm_display_name, " + + "event.playable_state_namespace_id AS audit_playable_state_namespace_id, " + + "event.state_scope AS audit_state_scope, " + + "event.visible AS audit_visible, " + + "event.public_production_realm AS audit_public_production_realm, " + + "event.character_creation_policy AS audit_character_creation_policy, " + + "event.requires_character_selection AS audit_requires_character_selection, " + + "event.canonical_game_instance_id AS audit_canonical_game_instance_id, " + + "event.initial_admission_request_digest AS audit_request_digest, " + + "event.initial_admission_request_id AS audit_request_id, " + + "event.canonical_version_id AS audit_canonical_version_id, " + + "event.runtime_version_id AS audit_runtime_version_id, " + + "event.initial_admission_origin_kind AS audit_origin_kind, " + + "event.initial_admission_prior_pointer_version AS audit_prior_pointer_version, " + + "event.initial_admission_active_epoch AS audit_active_epoch, " + + "event.initial_admission_hold_id AS audit_hold_id, " + + "event.initial_admission_hold_fence AS audit_hold_fence, " + + "event.initial_admission_hold_binding_digest AS audit_hold_binding_digest, " + + "event.tenant_id AS audit_game_session_tenant_id, " + + "event.game_instance_id AS audit_game_instance_id, " + + "event.pointer_version AS audit_pointer_version, " + + "event.catalog_revision AS audit_catalog_revision, " + + "event.control_plane_request_id AS audit_control_plane_request_id, " + + "event.admission_state AS audit_admission_state " + + "FROM gameplay_admission_pointer pointer JOIN gameplay_admission_pointer_event event " + + "ON event.id = ? AND event.representation_version = 3 " + + "AND event.target_namespace = pointer.target_namespace " + + "AND event.canonical_tenant_id = pointer.canonical_tenant_id " + + "AND event.realm_id = pointer.realm_id " + + "AND event.pointer_version = pointer.pointer_version " + + "AND event.initial_admission_request_id = pointer.initial_admission_request_id " + + "WHERE pointer.id = ? AND pointer.representation_version = 3", + attempt.auditEventId(), + attempt.pointerId()); + if (evidence == null + || !attempt.targetNamespace().equals(evidence.get("target_namespace", String.class)) + || !attempt.targetNamespace().equals(evidence.get("audit_target_namespace", String.class)) + || !attempt + .initialAdmissionRequestId() + .equals(evidence.get("initial_admission_request_id", String.class)) + || !attempt + .initialAdmissionRequestId() + .equals(evidence.get("audit_request_id", String.class)) + || !attempt + .requestDigest() + .equals(evidence.get("initial_admission_request_digest", String.class)) + || !attempt.requestDigest().equals(evidence.get("audit_request_digest", String.class)) + || !attempt.canonicalTenantId().equals(evidence.get("canonical_tenant_id", UUID.class)) + || !attempt + .canonicalTenantId() + .equals(evidence.get("audit_canonical_tenant_id", UUID.class)) + || !attempt.worldSlug().equals(evidence.get("audit_world_slug", String.class)) + || !attempt.realmId().equals(evidence.get("realm_id", UUID.class)) + || !attempt.realmId().equals(evidence.get("audit_realm_id", UUID.class)) + || !catalog + .sourceIntakeReceipt() + .source() + .worldDisplayName() + .equals(evidence.get("world_display_name", String.class)) + || !catalog + .sourceIntakeReceipt() + .source() + .worldDisplayName() + .equals(evidence.get("audit_world_display_name", String.class)) + || !catalog.realmSlug().equals(evidence.get("audit_realm_slug", String.class)) + || !catalog.realmDisplayName().equals(evidence.get("realm_display_name", String.class)) + || !catalog + .realmDisplayName() + .equals(evidence.get("audit_realm_display_name", String.class)) + || !attempt + .playableStateNamespaceId() + .equals(evidence.get("playable_state_namespace_id", UUID.class)) + || !attempt + .playableStateNamespaceId() + .equals(evidence.get("audit_playable_state_namespace_id", UUID.class)) + || !attempt.playableStateScope().equals(evidence.get("state_scope", String.class)) + || !attempt.playableStateScope().equals(evidence.get("audit_state_scope", String.class)) + || !Boolean.valueOf(catalog.visible()).equals(evidence.get("visible", Boolean.class)) + || !Boolean.valueOf(catalog.visible()).equals(evidence.get("audit_visible", Boolean.class)) + || !Boolean.valueOf(catalog.publicProduction()) + .equals(evidence.get("public_production_realm", Boolean.class)) + || !Boolean.valueOf(catalog.publicProduction()) + .equals(evidence.get("audit_public_production_realm", Boolean.class)) + || !catalog + .characterCreationPolicy() + .equals(evidence.get("character_creation_policy", String.class)) + || !catalog + .characterCreationPolicy() + .equals(evidence.get("audit_character_creation_policy", String.class)) + || evidence.get("requires_character_selection", Boolean.class) != null + || evidence.get("audit_requires_character_selection", Boolean.class) != null + || !attempt + .canonicalGameInstanceId() + .equals(evidence.get("canonical_game_instance_id", UUID.class)) + || !attempt + .canonicalGameInstanceId() + .equals(evidence.get("audit_canonical_game_instance_id", UUID.class)) + || !attempt.canonicalVersionId().equals(evidence.get("canonical_version_id", UUID.class)) + || attempt.runtimeVersionId() != evidence.get("runtime_version_id", Long.class) + || !attempt + .canonicalVersionId() + .equals(evidence.get("audit_canonical_version_id", UUID.class)) + || attempt.runtimeVersionId() != evidence.get("audit_runtime_version_id", Long.class) + || attempt.gameSessionTenantId() != evidence.get("tenant_id", Long.class) + || attempt.gameSessionTenantId() != evidence.get("audit_game_session_tenant_id", Long.class) + || attempt.gameInstanceId() != evidence.get("game_instance_id", Long.class) + || attempt.gameInstanceId() != evidence.get("audit_game_instance_id", Long.class) + || attempt.pointerVersion() != evidence.get("pointer_version", Long.class) + || attempt.pointerVersion() != evidence.get("audit_pointer_version", Long.class) + || attempt.expectedCatalogRevision() != evidence.get("catalog_revision", Long.class) + || attempt.expectedCatalogRevision() != evidence.get("audit_catalog_revision", Long.class) + || !"OPEN".equals(evidence.get("admission_state", String.class)) + || !"OPEN".equals(evidence.get("audit_admission_state", String.class)) + || attempt.originKind() + != CanonicalInitialAdmissionRequest.OriginKind.valueOf( + evidence.get("initial_admission_origin_kind", String.class)) + || attempt.originKind() + != CanonicalInitialAdmissionRequest.OriginKind.valueOf( + evidence.get("audit_origin_kind", String.class)) + || !Objects.equals( + attempt.expectedPriorPointerVersion(), + evidence.get("initial_admission_prior_pointer_version", Long.class)) + || !Objects.equals( + attempt.expectedPriorPointerVersion(), + evidence.get("audit_prior_pointer_version", Long.class)) + || attempt.activeLifecycleEpoch() + != evidence.get("initial_admission_active_epoch", Long.class) + || attempt.activeLifecycleEpoch() != evidence.get("audit_active_epoch", Long.class) + || !attempt.holdId().equals(evidence.get("initial_admission_hold_id", UUID.class)) + || !attempt.holdId().equals(evidence.get("audit_hold_id", UUID.class)) + || !attempt.holdFence().equals(evidence.get("initial_admission_hold_fence", UUID.class)) + || !attempt.holdFence().equals(evidence.get("audit_hold_fence", UUID.class)) + || !attempt + .holdBindingDigest() + .equals(evidence.get("initial_admission_hold_binding_digest", String.class)) + || !AUDIT_ACTOR.equals(evidence.get("audit_actor", String.class)) + || !AUDIT_REASON.equals(evidence.get("audit_reason", String.class)) + || !attempt + .holdBindingDigest() + .equals(evidence.get("audit_hold_binding_digest", String.class)) + || !attempt + .initialAdmissionRequestId() + .equals(evidence.get("audit_control_plane_request_id", String.class)) + || !attempt + .terminalAt() + .equals(toInstant(evidence.get("pointer_updated_at", java.time.LocalDateTime.class))) + || !attempt + .terminalAt() + .equals(toInstant(evidence.get("audit_at", java.time.LocalDateTime.class))) + || !catalog.worldSlug().equals(evidence.get("world_slug", String.class)) + || !catalog.realmSlug().equals(evidence.get("realm_slug", String.class)) + || !catalog + .playableStateNamespaceId() + .equals(evidence.get("playable_state_namespace_id", UUID.class))) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Committed initial-admission pointer, audit, request and catalog readback disagree"); + } + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED) { + verifyOriginalClosedOrigin(attempt, false); + } + String expectedProof = + commitProofDigest( + attempt, + attempt.pointerVersion(), + attempt.auditEventId(), + attempt.terminalAt(), + attempt.priorPointerRequestId(), + attempt.priorPointerRequestDigest(), + attempt.priorPointerAuditEventId()); + if (!expectedProof.equals(attempt.commitProofDigest())) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Committed initial-admission proof digest does not match the durable result"); + } + } + + private void verifyAbortReadback(Attempt attempt) { + readExactCatalog(attempt.asRequest()); + if (attempt.pointerId() != null + || attempt.pointerVersion() != null + || attempt.auditEventId() != null + || attempt.abortProofDigest() == null + || attempt.commitProofDigest() != null) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Durable ABORTED attempt contains contradictory pointer evidence"); + } + if (hasAttemptPointerEvidence(attempt)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "ABORTED initial-admission request unexpectedly has pointer or audit evidence"); + } + if (attempt.originKind() == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED) { + // The ABORTED terminal result is historical. A later distinct request may legitimately open + // this route; retain and verify the original CLOSED request/event without mistaking the later + // OPEN row for the terminal result of this aborted request. + verifyOriginalClosedOrigin(attempt, false); + } + String expectedProof = + abortProofDigest( + attempt, + attempt.abortReason(), + attempt.terminalAt(), + attempt.priorPointerRequestId(), + attempt.priorPointerRequestDigest(), + attempt.priorPointerAuditEventId()); + if (!expectedProof.equals(attempt.abortProofDigest())) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Durable ABORTED proof digest does not match the fenced result"); + } + } + + private void verifyOriginalClosedOrigin(Attempt attempt, boolean requireCurrent) { + if (attempt.priorPointerRequestId() == null + || attempt.priorPointerRequestDigest() == null + || attempt.priorPointerAuditEventId() == null + || !Long.valueOf(1L).equals(attempt.expectedPriorPointerVersion())) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "EXPECT_CLOSED terminal result has no exact original CLOSED origin identity"); + } + CanonicalClosedAdmissionPointerSnapshot origin = + (requireCurrent + ? pointerRepository.readByRequest( + attempt.targetNamespace(), attempt.priorPointerRequestId()) + : pointerRepository.readOriginalClosedOrigin( + attempt.targetNamespace(), attempt.priorPointerRequestId())) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + requireCurrent + ? "Original CLOSED route is no longer current owner authority" + : "Immutable original CLOSED request/event evidence is unavailable")); + if (!origin.canonicalTenantId().equals(attempt.canonicalTenantId()) + || !origin.realmId().equals(attempt.realmId()) + || !origin.requestDigest().equals(attempt.priorPointerRequestDigest()) + || origin.auditEventId() != attempt.priorPointerAuditEventId() + || origin.pointerVersion() != attempt.expectedPriorPointerVersion() + || origin.catalogRevision() != attempt.expectedCatalogRevision()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Original CLOSED request/event proof changed or no longer matches the attempt"); + } + } + + private boolean hasAttemptPointerEvidence(Attempt attempt) { + Record exists = + dsl.fetchOne( + "SELECT EXISTS (" + + "SELECT 1 FROM gameplay_admission_pointer WHERE representation_version = 3 " + + "AND target_namespace = ? AND initial_admission_request_id = ? " + + "UNION ALL SELECT 1 FROM gameplay_admission_pointer_event " + + "WHERE representation_version = 3 AND target_namespace = ? " + + "AND initial_admission_request_id = ?) AS represented", + attempt.targetNamespace(), + attempt.initialAdmissionRequestId(), + attempt.targetNamespace(), + attempt.initialAdmissionRequestId()); + return exists == null || !Boolean.FALSE.equals(exists.get("represented", Boolean.class)); + } + + private CanonicalRealmCatalogSnapshot readExactCatalog(CanonicalInitialAdmissionRequest request) { + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRealm(request.targetNamespace(), request.canonicalTenantId(), request.realmId()) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Exact canonical realm catalog is unavailable for owner readback")); + requireRequestMatchesCatalog(request, catalog); + return catalog; + } + + private CanonicalInitialAdmissionLaunchTarget readExactLaunchTarget( + CanonicalInitialAdmissionRequest request) { + CanonicalInitialAdmissionLaunchTarget target = + launchRepository + .readForInitialAdmission( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId()) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Exact canonical launch association is unavailable for owner readback")); + requireRequestMatchesLaunch(request, target); + return target; + } + + private CanonicalRealmCatalogSnapshot lockCatalog(CanonicalInitialAdmissionRequest request) { + CanonicalRealmCatalogSnapshot catalog = + catalogRepository.lockInitialAdmissionTarget( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.expectedCatalogRevision()); + requireRequestMatchesCatalog(request, catalog); + return catalog; + } + + private CanonicalInitialAdmissionLaunchTarget lockLaunchTarget( + CanonicalInitialAdmissionRequest request, boolean requireRunning) { + CanonicalInitialAdmissionLaunchTarget launchTarget = + launchRepository.lockForInitialAdmission( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId(), + requireRunning); + requireRequestMatchesLaunch(request, launchTarget); + return launchTarget; + } + + private static void requireRequestMatchesCatalog( + CanonicalInitialAdmissionRequest request, CanonicalRealmCatalogSnapshot catalog) { + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.worldSlug().equals(catalog.worldSlug()) + || !request.realmId().equals(catalog.realmId()) + || !request.playableStateNamespaceId().equals(catalog.playableStateNamespaceId()) + || !request.playableStateScope().equals(catalog.stateScope()) + || request.expectedCatalogRevision() != catalog.catalogRevision() + || !catalog.visible() + || !catalog.publicProduction()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Canonical realm catalog does not match the exact initial-admission request"); + } + } + + private static void requireRequestMatchesLaunch( + CanonicalInitialAdmissionRequest request, + CanonicalInitialAdmissionLaunchTarget launchTarget) { + CanonicalGameInstanceLaunchAssociation association = launchTarget.association(); + if (!request.targetNamespace().equals(association.targetNamespace()) + || !request.canonicalTenantId().equals(association.canonicalTenantId()) + || !request.worldSlug().equals(association.worldSlug()) + || !request.realmId().equals(launchTarget.realmId()) + || !request.playableStateNamespaceId().equals(association.playableStateNamespaceId()) + || !request.playableStateScope().equals(association.playableStateScope().name()) + || !request.canonicalGameInstanceId().equals(association.gameInstanceUuid()) + || !request.canonicalVersionId().equals(launchTarget.canonicalVersionId()) + || !association.publicProduction()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Canonical launch association does not match the exact initial-admission target tuple"); + } + } + + private static void requireRequestMatchesCatalogAndLaunch( + CanonicalInitialAdmissionRequest request, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launchTarget) { + requireRequestMatchesCatalog(request, catalog); + requireRequestMatchesLaunch(request, launchTarget); + } + + private void lockTarget(CanonicalInitialAdmissionRequest request) { + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ? || ':' || ?, 0))", + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString()); + } + + /** + * Existing pointer and legacy writers do not participate in this canonical target lock. Briefly + * excluding every representation table closes the otherwise-open absence-check gap; V9 numeric + * identifiers are used only to find collisions, never as canonical proof. + */ + private void lockAllAdmissionRepresentationsForNoPrior() { + dsl.execute( + "LOCK TABLE gameplay_admission_pointer, gameplay_admission_pointer_event, " + + "game_session_canonical_closed_admission_pointer_request, " + + "gameplay_initial_admission_bind_catalog, gameplay_initial_admission_bind_attempt " + + "IN SHARE ROW EXCLUSIVE MODE"); + } + + private Attempt requireAttemptForUpdate(CanonicalInitialAdmissionRequest request) { + Attempt attempt = + findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); + if (attempt == null) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Initial-admission request was not durably reserved before owner proof or commit"); + } + return attempt; + } + + private void requireSameRequest( + Attempt attempt, + CanonicalInitialAdmissionRequest request, + CanonicalInitialAdmissionLaunchTarget launchTarget) { + requireSameRequestIdentity(attempt, request); + if (attempt.runtimeVersionId() != launchTarget.runtimeVersionId() + || attempt.gameSessionTenantId() != launchTarget.association().gameSessionTenantId() + || attempt.gameInstanceId() != launchTarget.gameInstanceId()) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission request identity was reused with a changed canonical tuple or digest"); + } + } + + private void requireSameRequestIdentity( + Attempt attempt, CanonicalInitialAdmissionRequest request) { + if (!attempt.targetNamespace().equals(request.targetNamespace()) + || !attempt.initialAdmissionRequestId().equals(request.initialAdmissionRequestId()) + || !attempt.requestDigest().equals(request.requestDigest()) + || !attempt.canonicalTenantId().equals(request.canonicalTenantId()) + || !attempt.worldSlug().equals(request.worldSlug()) + || !attempt.realmId().equals(request.realmId()) + || !attempt.playableStateNamespaceId().equals(request.playableStateNamespaceId()) + || !attempt.playableStateScope().equals(request.playableStateScope()) + || !attempt.canonicalGameInstanceId().equals(request.canonicalGameInstanceId()) + || !attempt.canonicalVersionId().equals(request.canonicalVersionId()) + || !attempt.holdBindingDigest().equals(request.holdBindingDigest()) + || attempt.expectedCatalogRevision() != request.expectedCatalogRevision() + || attempt.originKind() != request.originKind() + || !Objects.equals( + attempt.expectedPriorPointerVersion(), request.expectedPriorPointerVersion()) + || attempt.activeLifecycleEpoch() != request.activeLifecycleEpoch() + || !attempt.holdId().equals(request.holdId()) + || !attempt.holdFence().equals(request.holdFence())) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission request identity was reused with a changed canonical tuple or digest"); + } + } + + private Attempt findPendingForRealm(CanonicalInitialAdmissionRequest request, boolean forUpdate) { + String sql = + "SELECT * FROM " + + OPERATION_TABLE + + " WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "AND status = 'PENDING'" + + (forUpdate ? " FOR UPDATE" : ""); + return Optional.ofNullable( + dsl.fetchOne( + sql, request.targetNamespace(), request.canonicalTenantId(), request.realmId())) + .map(CanonicalInitialAdmissionRepository::toAttempt) + .orElse(null); + } + + private Attempt findAttempt(String targetNamespace, String requestId, boolean forUpdate) { + return Optional.ofNullable(findAttemptRecord(targetNamespace, requestId, forUpdate)) + .map(CanonicalInitialAdmissionRepository::toAttempt) + .orElse(null); + } + + private Record findAttemptRecord(String targetNamespace, String requestId, boolean forUpdate) { + if (targetNamespace == null || requestId == null || requestId.isBlank()) { + throw new IllegalArgumentException("Initial-admission read selector is incomplete"); + } + return dsl.fetchOne( + "SELECT * FROM " + + OPERATION_TABLE + + " WHERE target_namespace = ? AND initial_admission_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + targetNamespace, + requestId); + } + + private static Attempt toAttempt(Record row) { + return new Attempt( + row.get("target_namespace", String.class), + row.get("initial_admission_request_id", String.class), + row.get("request_digest", String.class), + row.get("canonical_tenant_id", UUID.class), + row.get("world_slug", String.class), + row.get("realm_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class), + row.get("playable_state_scope", String.class), + row.get("canonical_game_instance_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("game_session_tenant_id", Long.class), + row.get("game_instance_id", Long.class), + row.get("runtime_version_id", Long.class), + row.get("hold_binding_digest", String.class), + row.get("expected_catalog_revision", Long.class), + CanonicalInitialAdmissionRequest.OriginKind.valueOf(row.get("origin_kind", String.class)), + row.get("expected_prior_pointer_version", Long.class), + row.get("active_lifecycle_epoch", Long.class), + row.get("hold_id", UUID.class), + row.get("hold_fence", UUID.class), + row.get("status", String.class), + row.get("pointer_id", Long.class), + row.get("pointer_version", Long.class), + row.get("audit_event_id", Long.class), + row.get("prior_pointer_request_id", UUID.class), + row.get("prior_pointer_request_digest", String.class), + row.get("prior_pointer_audit_event_id", Long.class), + row.get("commit_proof_digest", String.class), + row.get("abort_proof_digest", String.class), + row.get("abort_reason", String.class), + row.get("created_at", OffsetDateTime.class).toInstant(), + row.get("updated_at", OffsetDateTime.class).toInstant(), + row.get("terminal_at", OffsetDateTime.class) == null + ? null + : row.get("terminal_at", OffsetDateTime.class).toInstant()); + } + + private static CanonicalInitialAdmissionOwnerProof toProof( + Attempt attempt, CanonicalInitialAdmissionOwnerProof.Outcome outcome) { + return new CanonicalInitialAdmissionOwnerProof( + outcome, + attempt.initialAdmissionRequestId(), + attempt.requestDigest(), + attempt.targetNamespace(), + attempt.canonicalTenantId(), + attempt.worldSlug(), + attempt.realmId(), + attempt.playableStateNamespaceId(), + attempt.playableStateScope(), + attempt.canonicalGameInstanceId(), + attempt.canonicalVersionId(), + attempt.activeLifecycleEpoch(), + attempt.expectedCatalogRevision(), + attempt.originKind(), + attempt.expectedPriorPointerVersion(), + attempt.holdId(), + attempt.holdFence(), + attempt.holdBindingDigest(), + attempt.pointerVersion(), + attempt.auditEventId(), + COMMITTED.equals(attempt.status()) + ? attempt.commitProofDigest() + : ABORTED.equals(attempt.status()) ? attempt.abortProofDigest() : null, + ABORTED.equals(attempt.status()), + attempt.terminalAt()); + } + + private static String commitProofDigest( + Attempt attempt, + long pointerVersion, + long auditEventId, + Instant terminalAt, + UUID priorRequestId, + String priorRequestDigest, + Long priorAuditEventId) { + return digest( + List.of( + COMMIT_PROOF_DOMAIN, + attempt.requestDigest(), + attempt.initialAdmissionRequestId(), + attempt.targetNamespace(), + attempt.canonicalTenantId().toString(), + attempt.worldSlug(), + attempt.realmId().toString(), + attempt.playableStateNamespaceId().toString(), + attempt.playableStateScope(), + attempt.canonicalGameInstanceId().toString(), + attempt.canonicalVersionId().toString(), + Long.toString(attempt.runtimeVersionId()), + Long.toString(attempt.activeLifecycleEpoch()), + Long.toString(attempt.expectedCatalogRevision()), + attempt.originKind().name(), + attempt.expectedPriorPointerVersion() == null + ? "" + : attempt.expectedPriorPointerVersion().toString(), + attempt.holdId().toString(), + attempt.holdFence().toString(), + attempt.holdBindingDigest(), + Long.toString(pointerVersion), + Long.toString(auditEventId), + priorRequestId == null ? "" : priorRequestId.toString(), + priorRequestDigest == null ? "" : priorRequestDigest, + priorAuditEventId == null ? "" : priorAuditEventId.toString(), + terminalAt.toString())); + } + + private static String abortProofDigest( + Attempt attempt, + String reason, + Instant terminalAt, + UUID priorRequestId, + String priorRequestDigest, + Long priorAuditEventId) { + return digest( + List.of( + ABORT_PROOF_DOMAIN, + attempt.requestDigest(), + attempt.initialAdmissionRequestId(), + attempt.targetNamespace(), + attempt.canonicalTenantId().toString(), + attempt.worldSlug(), + attempt.realmId().toString(), + attempt.playableStateNamespaceId().toString(), + attempt.playableStateScope(), + attempt.canonicalGameInstanceId().toString(), + attempt.canonicalVersionId().toString(), + Long.toString(attempt.runtimeVersionId()), + Long.toString(attempt.activeLifecycleEpoch()), + Long.toString(attempt.expectedCatalogRevision()), + attempt.originKind().name(), + attempt.expectedPriorPointerVersion() == null + ? "" + : attempt.expectedPriorPointerVersion().toString(), + attempt.holdId().toString(), + attempt.holdFence().toString(), + attempt.holdBindingDigest(), + reason, + priorRequestId == null ? "" : priorRequestId.toString(), + priorRequestDigest == null ? "" : priorRequestDigest, + priorAuditEventId == null ? "" : priorAuditEventId.toString(), + terminalAt.toString())); + } + + private static String digest(List fields) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (String field : fields) { + byte[] bytes = field.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + digest.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static Instant nextTimestamp(Instant previous) { + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + if (previous != null && !now.isAfter(previous)) { + return previous.plus(1, ChronoUnit.MICROS); + } + return now; + } + + private static OffsetDateTime utc(Instant instant) { + return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical initial-admission owner mutation requires a writable transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical initial-admission owner mutation requires READ COMMITTED isolation"); + } + return null; + }); + Record isolation = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + if (isolation == null + || !"read committed".equals(isolation.get("isolation", String.class)) + || !"off".equals(isolation.get("read_only", String.class))) { + throw new IllegalStateException( + "Canonical initial-admission owner mutation requires writable READ COMMITTED isolation"); + } + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical initial-admission owner proof requires a committed readback"); + } + } + + private static void requireText(String value, String label, int maxLength) { + Objects.requireNonNull(value, label); + if (value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(label + " must contain 1.." + maxLength + " characters"); + } + } + + /** Full persisted pointer-row identity used to detect any before/after read drift. */ + private record CurrentOpenPointer(Map fields) { + private CurrentOpenPointer { + fields = Collections.unmodifiableMap(new LinkedHashMap<>(fields)); + } + + private static CurrentOpenPointer from(Record row) { + return new CurrentOpenPointer(row.intoMap()); + } + + private String initialAdmissionRequestId() { + return value("initial_admission_request_id", String.class); + } + + private void requireCanonicalOpen( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + if (!Integer.valueOf(3).equals(value("representation_version", Integer.class)) + || !"OPEN".equals(value("admission_state", String.class)) + || !targetNamespace.equals(value("target_namespace", String.class)) + || !canonicalTenantId.equals(value("canonical_tenant_id", UUID.class)) + || !realmId.equals(value("realm_id", UUID.class)) + || !Boolean.TRUE.equals(value("visible", Boolean.class)) + || !Boolean.TRUE.equals(value("public_production_realm", Boolean.class)) + || value("requires_character_selection", Boolean.class) != null + || !"SHARED".equals(value("state_scope", String.class)) + || !AUDIT_ACTOR.equals(value("last_updated_by", String.class)) + || !AUDIT_REASON.equals(value("last_update_reason", String.class)) + || value("prepared_version_upgrade_id", String.class) != null + || !text(value("character_creation_policy", String.class)) + || !positive(value("id", Long.class)) + || !positive(value("pointer_version", Long.class)) + || !positive(value("catalog_revision", Long.class)) + || !positive(value("tenant_id", Long.class)) + || !positive(value("game_instance_id", Long.class)) + || !positive(value("runtime_version_id", Long.class)) + || !positive(value("initial_admission_active_epoch", Long.class)) + || !nonNil(value("playable_state_namespace_id", UUID.class)) + || !nonNil(value("canonical_game_instance_id", UUID.class)) + || !nonNil(value("canonical_version_id", UUID.class)) + || !nonNil(value("initial_admission_hold_id", UUID.class)) + || !nonNil(value("initial_admission_hold_fence", UUID.class)) + || !text(value("world_slug", String.class)) + || !text(value("realm_slug", String.class)) + || !text(value("initial_admission_request_id", String.class)) + || !matchesDigest(value("initial_admission_request_digest", String.class)) + || !text(value("initial_admission_origin_kind", String.class)) + || !matchesProofDigest(value("initial_admission_hold_binding_digest", String.class))) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current realm pointer is not a complete canonical OPEN representation"); + } + } + + private boolean matches(CanonicalInitialAdmissionOwnerProof proof) { + return proof.provesCommit() + && proof.targetNamespace().equals(value("target_namespace", String.class)) + && proof.canonicalTenantId().equals(value("canonical_tenant_id", UUID.class)) + && proof.worldSlug().equals(value("world_slug", String.class)) + && proof.realmId().equals(value("realm_id", UUID.class)) + && proof + .playableStateNamespaceId() + .equals(value("playable_state_namespace_id", UUID.class)) + && proof.playableStateScope().equals(value("state_scope", String.class)) + && proof.canonicalGameInstanceId().equals(value("canonical_game_instance_id", UUID.class)) + && proof.canonicalVersionId().equals(value("canonical_version_id", UUID.class)) + && proof.expectedCatalogRevision() == value("catalog_revision", Long.class) + && proof.committedPointerVersion().equals(value("pointer_version", Long.class)) + && proof + .initialAdmissionRequestId() + .equals(value("initial_admission_request_id", String.class)) + && proof.requestDigest().equals(value("initial_admission_request_digest", String.class)) + && proof.originKind().name().equals(value("initial_admission_origin_kind", String.class)) + && Objects.equals( + proof.expectedPriorPointerVersion(), + value("initial_admission_prior_pointer_version", Long.class)) + && proof.activeLifecycleEpoch() == value("initial_admission_active_epoch", Long.class) + && proof.holdId().equals(value("initial_admission_hold_id", UUID.class)) + && proof.holdFence().equals(value("initial_admission_hold_fence", UUID.class)) + && proof + .holdBindingDigest() + .equals(value("initial_admission_hold_binding_digest", String.class)) + && proof.auditEventId() != null + && proof.auditEventId() > 0L; + } + + private String snapshotDigest(CanonicalInitialAdmissionOwnerProof proof) { + return CanonicalCurrentOpenPointerSnapshotDigest.digest( + new CanonicalCurrentOpenPointerSnapshotDigest.Projection( + value("representation_version", Integer.class), + value("target_namespace", String.class), + value("canonical_tenant_id", UUID.class), + value("world_slug", String.class), + value("world_display_name", String.class), + value("realm_id", UUID.class), + value("realm_slug", String.class), + value("realm_display_name", String.class), + value("playable_state_namespace_id", UUID.class), + value("state_scope", String.class), + value("catalog_revision", Long.class), + value("pointer_version", Long.class), + value("admission_state", String.class), + value("visible", Boolean.class), + value("public_production_realm", Boolean.class), + value("requires_character_selection", Boolean.class), + value("character_creation_policy", String.class), + value("canonical_game_instance_id", UUID.class), + value("canonical_version_id", UUID.class), + value("initial_admission_request_id", String.class), + value("initial_admission_request_digest", String.class), + CanonicalInitialAdmissionRequest.OriginKind.valueOf( + value("initial_admission_origin_kind", String.class)), + value("initial_admission_prior_pointer_version", Long.class), + value("initial_admission_active_epoch", Long.class), + value("initial_admission_hold_id", UUID.class), + value("initial_admission_hold_fence", UUID.class), + value("initial_admission_hold_binding_digest", String.class), + value("last_updated_by", String.class), + value("last_update_reason", String.class), + value("prepared_version_upgrade_id", String.class), + proof.proofDigest(), + proof.auditEventId(), + proof.terminalAt())); + } + + private T value(String key, Class type) { + Object value = fields.get(key); + if (value == null) { + return null; + } + if (!type.isInstance(value)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current realm pointer contains an invalid persisted field type: " + key); + } + return type.cast(value); + } + + private static boolean positive(Long value) { + return value != null && value > 0L; + } + + private static boolean nonNil(UUID value) { + return value != null && !new UUID(0L, 0L).equals(value); + } + + private static boolean text(String value) { + return value != null && !value.isBlank() && value.equals(value.trim()); + } + + private static boolean matchesDigest(String value) { + return value != null && value.matches("[0-9a-f]{64}"); + } + + private static boolean matchesProofDigest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + } + + private record Attempt( + String targetNamespace, + String initialAdmissionRequestId, + String requestDigest, + UUID canonicalTenantId, + String worldSlug, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + long gameSessionTenantId, + long gameInstanceId, + long runtimeVersionId, + String holdBindingDigest, + long expectedCatalogRevision, + CanonicalInitialAdmissionRequest.OriginKind originKind, + Long expectedPriorPointerVersion, + long activeLifecycleEpoch, + UUID holdId, + UUID holdFence, + String status, + Long pointerId, + Long pointerVersion, + Long auditEventId, + UUID priorPointerRequestId, + String priorPointerRequestDigest, + Long priorPointerAuditEventId, + String commitProofDigest, + String abortProofDigest, + String abortReason, + Instant createdAt, + Instant updatedAt, + Instant terminalAt) { + private CanonicalInitialAdmissionRequest asRequest() { + return new CanonicalInitialAdmissionRequest( + targetNamespace, + canonicalTenantId, + worldSlug, + realmId, + playableStateNamespaceId, + playableStateScope, + canonicalGameInstanceId, + canonicalVersionId, + activeLifecycleEpoch, + expectedCatalogRevision, + originKind, + expectedPriorPointerVersion, + initialAdmissionRequestId, + requestDigest, + holdId, + holdFence, + holdBindingDigest); + } + } + + public static class CanonicalInitialAdmissionConflictException extends IllegalStateException { + public CanonicalInitialAdmissionConflictException(String message) { + super(message); + } + } + + public static class CanonicalInitialAdmissionReconciliationRequiredException + extends IllegalStateException { + public CanonicalInitialAdmissionReconciliationRequiredException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java new file mode 100644 index 0000000000..1d62abf2e4 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java @@ -0,0 +1,1074 @@ +package net.firedevops.firemud.gamesession.repository; + +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalClosedAdmissionPointerRequest; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local persistence for one initial canonical CLOSED admission pointer per realm. */ +public class GameSessionCanonicalAdmissionPointerRepository { + private static final int SCHEMA_VERSION = 1; + private static final int CANONICAL_REPRESENTATION_VERSION = 2; + private static final long INITIAL_POINTER_VERSION = 1L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String CLOSED = "CLOSED"; + private static final String ABSENT = "ABSENT"; + private static final String REQUEST_DOMAIN = "game-session-canonical-closed-pointer-request/v1"; + private static final String RECEIPT_DOMAIN = "game-session-canonical-closed-pointer-receipt/v1"; + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final GameplayAdmissionPointerEventRepository eventRepository; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories and DSLContext are internal Spring collaborators.") + public GameSessionCanonicalAdmissionPointerRepository( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameplayAdmissionPointerEventRepository eventRepository) { + this.dsl = dsl; + this.catalogRepository = catalogRepository; + this.eventRepository = eventRepository; + } + + /** + * Prepares from a committed catalog read without retaining an ambient owner transaction. The + * returned value is privately constructed and must be revalidated under the catalog row lock. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedInitialClosed prepareInitialClosed( + CreateCanonicalClosedAdmissionPointerRequest request) { + Objects.requireNonNull(request, "request"); + requireCommittedRead(); + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(request.targetNamespace(), request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Exact committed initial catalog request is missing")); + requireExactInitialCatalog(request, catalog); + return new PreparedInitialClosed(request, catalog, requestDigest(request, catalog)); + } + + /** + * Commits the CLOSED route, one append-only event, and its immutable request outcome atomically. + * The caller must perform a separate committed {@link #readByRequest} before returning evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void createInitialClosed(PreparedInitialClosed prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireWritableOwnerTransaction(); + CreateCanonicalClosedAdmissionPointerRequest request = prepared.request(); + CanonicalRealmCatalogSnapshot catalog = + catalogRepository.lockExactInitialPublicProduction( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision()); + requireExactInitialCatalog(request, catalog); + if (!prepared.catalogSnapshot().equals(catalog)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Locked catalog snapshot changed after canonical CLOSED pointer preparation"); + } + + String requestDigest = requestDigest(request, catalog); + if (!prepared.requestDigest().equals(requestDigest)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Prepared canonical CLOSED pointer digest does not match its exact inputs"); + } + + Record priorRequest = findRequest(request.targetNamespace(), request.requestId()); + if (priorRequest != null) { + requireSameRequest(priorRequest, request, catalog, requestDigest); + return; + } + if (pointerExistsForRealm(request.realmId())) { + throw new CanonicalClosedPointerConflictException( + "Canonical realm already has an admission-pointer representation"); + } + + Instant updatedAt = Instant.now().truncatedTo(ChronoUnit.MICROS); + Long pointerId; + long auditEventId; + String receiptDigest; + try { + Record insertedPointer = + dsl.fetchOne( + "INSERT INTO gameplay_admission_pointer (" + + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "created_at, updated_at, public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state) " + + "VALUES (?, ?, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, " + + "?, ?, NULL, ?, ?, NULL, 2, ?, ?, 'CLOSED') RETURNING id", + catalog.worldSlug(), + catalog.realmSlug(), + toLocalDateTime(updatedAt), + toLocalDateTime(updatedAt), + catalog.catalogRevision(), + catalog.realmId(), + catalog.targetNamespace(), + catalog.tenantId()); + if (insertedPointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer insert returned no owner row"); + } + pointerId = insertedPointer.get("id", Long.class); + if (pointerId == null || pointerId <= 0L) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer row id is invalid"); + } + + auditEventId = + eventRepository.appendCanonicalClosed( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + catalog.catalogRevision(), + request.actorPrincipal(), + request.reason(), + request.requestId(), + updatedAt); + receiptDigest = receiptDigest(request, catalog, requestDigest, auditEventId, updatedAt); + dsl.execute( + "INSERT INTO game_session_canonical_closed_admission_pointer_request (" + + "target_namespace, request_id, request_digest, canonical_tenant_id, realm_id, " + + "catalog_creation_request_id, catalog_revision, catalog_request_digest, " + + "catalog_receipt_digest, actor_principal, reason, admission_state, pointer_version, " + + "audit_event_id, receipt_digest, updated_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'CLOSED', 1, ?, ?, CAST(? AS TIMESTAMPTZ))", + request.targetNamespace(), + request.requestId(), + requestDigest, + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision(), + catalog.requestDigest(), + catalog.receiptDigest(), + request.actorPrincipal(), + request.reason(), + auditEventId, + receiptDigest, + OffsetDateTime.ofInstant(updatedAt, ZoneOffset.UTC)); + } catch (org.jooq.exception.IntegrityConstraintViolationException exception) { + throw new CanonicalClosedPointerConflictException( + "Canonical CLOSED pointer creation conflicts with committed realm or request authority", + exception); + } + } + + /** + * Prepares an explicit expected-closed check from the exact original committed CLOSED request. + * Missing request, pointer, event, or catalog history is invalid evidence and never establishes a + * never-open origin. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedExpectedClosed prepareExpectedClosed( + String targetNamespace, + UUID originalRequestId, + long expectedPointerVersion, + long expectedCatalogRevision) { + requireReadSelector(targetNamespace, originalRequestId); + requirePositive(expectedPointerVersion, "expectedPointerVersion"); + requirePositive(expectedCatalogRevision, "expectedCatalogRevision"); + requireCommittedRead(); + + CanonicalClosedAdmissionPointerSnapshot origin = + readByRequest(targetNamespace, originalRequestId) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Exact original committed canonical CLOSED origin is missing")); + requireExpectedVersions(origin, expectedPointerVersion, expectedCatalogRevision); + return new PreparedExpectedClosed(origin, expectedPointerVersion, expectedCatalogRevision); + } + + /** + * Prepares the exact original CLOSED origin for a realm without accepting a caller-supplied + * origin request identity. The canonical CLOSED owner table is the source of that identity. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedExpectedClosed prepareExpectedClosedForRealm( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + long expectedPointerVersion, + long expectedCatalogRevision) { + requireReadSelector(targetNamespace, canonicalTenantId); + requireReadSelector(targetNamespace, realmId); + requirePositive(expectedPointerVersion, "expectedPointerVersion"); + requirePositive(expectedCatalogRevision, "expectedCatalogRevision"); + requireCommittedRead(); + var outcomes = + dsl.fetch( + "SELECT request_id FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "ORDER BY request_id LIMIT 2", + targetNamespace, + canonicalTenantId, + realmId); + if (outcomes.size() != 1) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Realm does not have one exact original canonical CLOSED request outcome"); + } + UUID originalRequestId = required(outcomes.getFirst(), "request_id", UUID.class); + return prepareExpectedClosed( + targetNamespace, originalRequestId, expectedPointerVersion, expectedCatalogRevision); + } + + /** + * Reads the immutable original CLOSED request/event after the current pointer has opened. This is + * historical origin evidence only; it does not claim that CLOSED remains the current route. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readOriginalClosedOrigin( + String targetNamespace, UUID originalRequestId) { + requireReadSelector(targetNamespace, originalRequestId); + requireCommittedRead(); + Record outcome = findRequest(targetNamespace, originalRequestId); + if (outcome == null) { + return Optional.empty(); + } + try { + CreateCanonicalClosedAdmissionPointerRequest request = requestFromOutcome(outcome); + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(targetNamespace, request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED origin lost its exact catalog evidence")); + return Optional.of( + verifyOrigin(targetNamespace, originalRequestId, outcome, catalog, null, false)); + } catch (InvalidCanonicalClosedPointerEvidenceException + | GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException + | GameSessionCanonicalRealmCatalogRepository.CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted original canonical CLOSED evidence is invalid", exception); + } + } + + /** + * Requires absence across every persisted pointer/audit representation that can name this + * canonical realm or its exactly associated legacy runtime selector. The caller must hold the + * catalog/target serialization locks in its writable READ COMMITTED transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void requireNoAdmissionPointerRepresentations( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + String worldSlug, + String realmSlug, + long gameSessionTenantId, + long gameInstanceId) { + requireWritableOwnerTransaction(); + requireReadSelector(targetNamespace, canonicalTenantId); + requireReadSelector(targetNamespace, realmId); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + requirePositive(gameSessionTenantId, "gameSessionTenantId"); + requirePositive(gameInstanceId, "gameInstanceId"); + Record exists = + dsl.fetchOne( + "SELECT EXISTS (" + + "SELECT 1 FROM gameplay_admission_pointer WHERE realm_id = ? " + + "OR (target_namespace = ? AND canonical_tenant_id = ?) " + + "OR (world_slug = ? AND realm_slug = ?) " + + "OR (tenant_id = ? AND game_instance_id = ?) " + + "UNION ALL SELECT 1 FROM gameplay_admission_pointer_event WHERE realm_id = ? " + + "OR (target_namespace = ? AND canonical_tenant_id = ?) " + + "OR (world_slug = ? AND realm_slug = ?) " + + "OR (tenant_id = ? AND game_instance_id = ?) " + + "UNION ALL SELECT 1 FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "UNION ALL SELECT 1 FROM gameplay_initial_admission_bind_catalog " + + "WHERE tenant_id = ? AND (realm_id = ? OR (world_slug = ? AND realm_slug = ?)) " + + "UNION ALL SELECT 1 FROM gameplay_initial_admission_bind_attempt " + + "WHERE tenant_id = ? AND (realm_id = ? OR game_instance_id = ?)" + + ") AS represented", + realmId, + targetNamespace, + canonicalTenantId, + worldSlug, + realmSlug, + gameSessionTenantId, + gameInstanceId, + realmId, + targetNamespace, + canonicalTenantId, + worldSlug, + realmSlug, + gameSessionTenantId, + gameInstanceId, + targetNamespace, + canonicalTenantId, + realmId, + gameSessionTenantId, + realmId, + worldSlug, + realmSlug, + gameSessionTenantId, + realmId, + gameInstanceId); + if (exists == null || !Boolean.FALSE.equals(exists.get("represented", Boolean.class))) { + throw new CanonicalClosedPointerConflictException( + "A pointer, audit, or prior initial-admission representation already names this target"); + } + } + + /** + * Locks and revalidates one prepared original CLOSED origin in the caller's read-write READ + * COMMITTED owner transaction. The returned token is local repository evidence only; it is not + * World hold/readback, caller authentication, or authorization to transition the pointer. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ExpectedClosedEvidence lockExpectedClosed(PreparedExpectedClosed prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireWritableOwnerTransaction(); + CanonicalClosedAdmissionPointerSnapshot committedOrigin = prepared.committedOrigin(); + CreateCanonicalClosedAdmissionPointerRequest originRequest = + requestFromSnapshot(committedOrigin); + + CanonicalRealmCatalogSnapshot lockedCatalog = + catalogRepository.lockExactInitialPublicProduction( + originRequest.targetNamespace(), + originRequest.canonicalTenantId(), + originRequest.realmId(), + originRequest.catalogCreationRequestId(), + prepared.expectedCatalogRevision()); + if (!committedOrigin.catalogSnapshot().equals(lockedCatalog)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact catalog origin changed after expected-CLOSED preparation"); + } + + Record lockedPointer = lockCanonicalPointer(originRequest); + if (lockedPointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED pointer row is missing"); + } + Record outcome = findRequest(originRequest.targetNamespace(), originRequest.requestId()); + if (outcome == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED request outcome is missing"); + } + + CanonicalClosedAdmissionPointerSnapshot lockedOrigin = + verifyOrigin( + originRequest.targetNamespace(), + originRequest.requestId(), + outcome, + lockedCatalog, + lockedPointer); + requireExpectedVersions( + lockedOrigin, prepared.expectedPointerVersion(), prepared.expectedCatalogRevision()); + if (!committedOrigin.equals(lockedOrigin)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED origin changed after preparation"); + } + return new ExpectedClosedEvidence(lockedOrigin); + } + + /** Reads and verifies the immutable request outcome from committed owner rows. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByRequest( + String targetNamespace, UUID requestId) { + requireReadSelector(targetNamespace, requestId); + requireCommittedRead(); + Record outcome = findRequest(targetNamespace, requestId); + if (outcome == null) { + return Optional.empty(); + } + try { + CreateCanonicalClosedAdmissionPointerRequest request = requestFromOutcome(outcome); + if (!targetNamespace.equals(request.targetNamespace()) + || !requestId.equals(request.requestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its read selector"); + } + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(targetNamespace, request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome lost its catalog reference")); + Record pointer = findCanonicalPointer(request); + return Optional.of(verifyOrigin(targetNamespace, requestId, outcome, catalog, pointer)); + } catch (InvalidCanonicalClosedPointerEvidenceException + | GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException + | GameSessionCanonicalRealmCatalogRepository.CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer evidence is invalid", exception); + } + } + + private Record findRequest(String targetNamespace, UUID requestId) { + return dsl.fetchOne( + "SELECT * FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND request_id = ?", + targetNamespace, + requestId); + } + + private Record lockCanonicalPointer(CreateCanonicalClosedAdmissionPointerRequest request) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer " + + "WHERE representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ? FOR UPDATE", + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId()); + } + + private CanonicalClosedAdmissionPointerSnapshot verifyOrigin( + String targetNamespace, + UUID requestId, + Record outcome, + CanonicalRealmCatalogSnapshot catalog, + Record pointer) { + return verifyOrigin(targetNamespace, requestId, outcome, catalog, pointer, true); + } + + private CanonicalClosedAdmissionPointerSnapshot verifyOrigin( + String targetNamespace, + UUID requestId, + Record outcome, + CanonicalRealmCatalogSnapshot catalog, + Record pointer, + boolean requireCurrentPointer) { + try { + CreateCanonicalClosedAdmissionPointerRequest request = requestFromOutcome(outcome); + if (!targetNamespace.equals(request.targetNamespace()) + || !requestId.equals(request.requestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its read selector"); + } + requireExactInitialCatalog(request, catalog); + String computedRequestDigest = requestDigest(request, catalog); + if (!computedRequestDigest.equals(required(outcome, "request_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer request digest does not match committed request inputs"); + } + if (!catalog.requestDigest().equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its exact catalog digests"); + } + + long eventId = required(outcome, "audit_event_id", Long.class); + Instant updatedAt = outcomeTimestamp(outcome); + String computedReceiptDigest = + receiptDigest(request, catalog, computedRequestDigest, eventId, updatedAt); + if (!computedReceiptDigest.equals(required(outcome, "receipt_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer receipt digest does not match its committed result"); + } + requireOutcomeMatches( + outcome, + request, + catalog, + computedRequestDigest, + computedReceiptDigest, + eventId, + updatedAt); + + if (requireCurrentPointer && pointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome has no committed routing row"); + } + if (requireCurrentPointer) { + requirePointerMatches(pointer, request, catalog, updatedAt); + } + + Record event = findCanonicalEvent(eventId); + if (event == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome has no committed audit event"); + } + requireEventMatches(event, request, catalog, eventId, updatedAt); + + return new CanonicalClosedAdmissionPointerSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + INITIAL_POINTER_VERSION, + catalog.catalogRevision(), + CLOSED, + null, + request.requestId(), + computedRequestDigest, + computedReceiptDigest, + request.actorPrincipal(), + request.reason(), + eventId, + updatedAt, + catalog); + } catch (InvalidCanonicalClosedPointerEvidenceException + | GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException + | GameSessionCanonicalRealmCatalogRepository.CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer evidence is invalid", exception); + } + } + + private static CreateCanonicalClosedAdmissionPointerRequest requestFromSnapshot( + CanonicalClosedAdmissionPointerSnapshot snapshot) { + return new CreateCanonicalClosedAdmissionPointerRequest( + snapshot.requestId(), + snapshot.targetNamespace(), + snapshot.canonicalTenantId(), + snapshot.realmId(), + snapshot.catalogSnapshot().creationRequestId(), + snapshot.catalogRevision(), + snapshot.actorPrincipal(), + snapshot.reason()); + } + + static void requireExpectedVersions( + CanonicalClosedAdmissionPointerSnapshot origin, + long expectedPointerVersion, + long expectedCatalogRevision) { + if (origin.pointerVersion() != expectedPointerVersion + || origin.catalogRevision() != expectedCatalogRevision) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Expected pointer and catalog versions do not match the exact original CLOSED origin"); + } + } + + private boolean pointerExistsForRealm(UUID realmId) { + return dsl.fetchExists( + dsl.selectOne() + .from(org.jooq.impl.DSL.table("gameplay_admission_pointer")) + .where(org.jooq.impl.DSL.field("realm_id", UUID.class).eq(realmId))); + } + + private Record findCanonicalPointer(CreateCanonicalClosedAdmissionPointerRequest request) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer " + + "WHERE representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ?", + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId()); + } + + private Record findCanonicalEvent(long eventId) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer_event " + + "WHERE representation_version = 2 AND id = ?", + eventId); + } + + private static CreateCanonicalClosedAdmissionPointerRequest requestFromOutcome(Record outcome) { + return new CreateCanonicalClosedAdmissionPointerRequest( + required(outcome, "request_id", UUID.class), + required(outcome, "target_namespace", String.class), + required(outcome, "canonical_tenant_id", UUID.class), + required(outcome, "realm_id", UUID.class), + required(outcome, "catalog_creation_request_id", UUID.class), + required(outcome, "catalog_revision", Long.class), + required(outcome, "actor_principal", String.class), + required(outcome, "reason", String.class)); + } + + private static void requireSameRequest( + Record outcome, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest) { + if (!request.requestId().equals(required(outcome, "request_id", UUID.class)) + || !requestDigest.equals(required(outcome, "request_digest", String.class)) + || !request.targetNamespace().equals(required(outcome, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(outcome, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(outcome, "realm_id", UUID.class)) + || !request + .catalogCreationRequestId() + .equals(required(outcome, "catalog_creation_request_id", UUID.class)) + || request.catalogRevision() != required(outcome, "catalog_revision", Long.class) + || !catalog + .requestDigest() + .equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class)) + || !request.actorPrincipal().equals(required(outcome, "actor_principal", String.class)) + || !request.reason().equals(required(outcome, "reason", String.class))) { + throw new CanonicalClosedPointerConflictException( + "Canonical CLOSED pointer request identity was reused with changed input"); + } + } + + private static void requireExactInitialCatalog( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + if (!catalog.visible() + || !catalog.publicProduction() + || catalog.catalogRevision() != request.catalogRevision() + || catalog.catalogRevision() != INITIAL_POINTER_VERSION + || !request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer request does not identify the exact initial public catalog"); + } + } + + private static void requireOutcomeMatches( + Record outcome, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + String receiptDigest, + long eventId, + Instant updatedAt) { + if (!CLOSED.equals(required(outcome, "admission_state", String.class)) + || required(outcome, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(outcome, "audit_event_id", Long.class) != eventId + || !request.requestId().equals(required(outcome, "request_id", UUID.class)) + || !request.targetNamespace().equals(required(outcome, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(outcome, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(outcome, "realm_id", UUID.class)) + || !request + .catalogCreationRequestId() + .equals(required(outcome, "catalog_creation_request_id", UUID.class)) + || request.catalogRevision() != required(outcome, "catalog_revision", Long.class) + || !requestDigest.equals(required(outcome, "request_digest", String.class)) + || !receiptDigest.equals(required(outcome, "receipt_digest", String.class)) + || !catalog + .requestDigest() + .equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class)) + || !request.actorPrincipal().equals(required(outcome, "actor_principal", String.class)) + || !request.reason().equals(required(outcome, "reason", String.class)) + || !updatedAt.equals(outcomeTimestamp(outcome))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome conflicts with its request or catalog authority"); + } + } + + private static void requirePointerMatches( + Record pointer, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + Instant updatedAt) { + if (required(pointer, "representation_version", Integer.class) + != CANONICAL_REPRESENTATION_VERSION + || !request.targetNamespace().equals(required(pointer, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(pointer, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(pointer, "realm_id", UUID.class)) + || !catalog.worldSlug().equals(required(pointer, "world_slug", String.class)) + || !catalog.realmSlug().equals(required(pointer, "realm_slug", String.class)) + || required(pointer, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(pointer, "catalog_revision", Long.class) != request.catalogRevision() + || !CLOSED.equals(required(pointer, "admission_state", String.class)) + || pointer.get("tenant_id", Long.class) != null + || pointer.get("game_instance_id", Long.class) != null + || pointer.get("playable_state_namespace_id", UUID.class) != null + || hasLegacyPointerCatalogCopy(pointer) + || !updatedAt.equals(toInstant(pointer.get("created_at", java.time.LocalDateTime.class))) + || !updatedAt.equals(toInstant(pointer.get("updated_at", java.time.LocalDateTime.class)))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer row is aliased, policy-copied or inconsistent with its catalog"); + } + } + + private static boolean hasLegacyPointerCatalogCopy(Record pointer) { + return pointer.get("world_display_name", String.class) != null + || pointer.get("realm_display_name", String.class) != null + || pointer.get("visible", Boolean.class) != null + || pointer.get("public_production_realm", Boolean.class) != null + || pointer.get("requires_character_selection", Boolean.class) != null + || pointer.get("state_scope", String.class) != null + || pointer.get("character_creation_policy", String.class) != null + || pointer.get("last_updated_by", String.class) != null + || pointer.get("last_update_reason", String.class) != null; + } + + private static void requireEventMatches( + Record event, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + long eventId, + Instant updatedAt) { + if (required(event, "id", Long.class) != eventId + || required(event, "representation_version", Integer.class) + != CANONICAL_REPRESENTATION_VERSION + || !request.targetNamespace().equals(required(event, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(event, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(event, "realm_id", UUID.class)) + || !catalog.worldSlug().equals(required(event, "world_slug", String.class)) + || !catalog.realmSlug().equals(required(event, "realm_slug", String.class)) + || required(event, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(event, "catalog_revision", Long.class) != request.catalogRevision() + || !CLOSED.equals(required(event, "admission_state", String.class)) + || !request + .requestId() + .toString() + .equals(required(event, "control_plane_request_id", String.class)) + || !request.actorPrincipal().equals(required(event, "actor_principal", String.class)) + || !request.reason().equals(required(event, "reason", String.class)) + || event.get("tenant_id", Long.class) != null + || event.get("game_instance_id", Long.class) != null + || event.get("prepared_version_upgrade_id", String.class) != null + || hasLegacyEventCatalogCopy(event) + || !updatedAt.equals(toInstant(event.get("occurred_at", java.time.LocalDateTime.class)))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer audit event conflicts with its pointer or catalog authority"); + } + } + + private static boolean hasLegacyEventCatalogCopy(Record event) { + return event.get("world_display_name", String.class) != null + || event.get("realm_display_name", String.class) != null + || event.get("visible", Boolean.class) != null + || event.get("public_production_realm", Boolean.class) != null + || event.get("requires_character_selection", Boolean.class) != null + || event.get("state_scope", String.class) != null + || event.get("character_creation_policy", String.class) != null; + } + + private static Instant outcomeTimestamp(Record outcome) { + OffsetDateTime updatedAt = required(outcome, "updated_at", OffsetDateTime.class); + return updatedAt.toInstant(); + } + + static String requestDigest( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + return digest(requestDigestFields(request, catalog)); + } + + private static List requestDigestFields( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + return List.of( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.requestId().toString(), + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + catalog.requestDigest(), + catalog.receiptDigest(), + request.actorPrincipal(), + request.reason(), + CLOSED, + ABSENT); + } + + static String receiptDigest( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + long auditEventId, + Instant updatedAt) { + return digest(receiptDigestFields(request, catalog, requestDigest, auditEventId, updatedAt)); + } + + private static List receiptDigestFields( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + long auditEventId, + Instant updatedAt) { + requirePositive(auditEventId, "auditEventId"); + return List.of( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.requestId().toString(), + requestDigest, + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + catalog.worldSlug(), + catalog.realmSlug(), + Long.toString(INITIAL_POINTER_VERSION), + Long.toString(request.catalogRevision()), + Long.toString(auditEventId), + Objects.requireNonNull(updatedAt, "updatedAt").toString(), + CLOSED, + ABSENT); + } + + private static String digest(List fields) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String value : fields) { + byte[] bytes = strictUtf8(value); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must be well-formed UTF-8 text", exception); + } + } + + private static void requireReadSelector(String targetNamespace, UUID requestId) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) { + throw new InvalidCanonicalClosedPointerEvidenceException(name + " must be positive"); + } + } + + private static T required(Record record, String fieldName, Class type) { + T value = record.get(fieldName, type); + if (value == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer " + fieldName + " is missing"); + } + return value; + } + + private void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires a read-write transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical CLOSED pointer DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires READ COMMITTED isolation"); + } + return null; + }); + Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); + if (isolationRow == null + || !"read committed".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires READ COMMITTED isolation"); + } + Record readOnlyRow = dsl.fetchOne("SHOW transaction_read_only"); + if (readOnlyRow == null || !"off".equalsIgnoreCase(readOnlyRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires a read-write transaction"); + } + } + + private void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical CLOSED pointer operation requires a committed-outcome owner read"); + } + } + + /** + * Opaque preflight result; callers cannot construct a preparation or change its catalog proof. + */ + public static final class PreparedInitialClosed { + private final CreateCanonicalClosedAdmissionPointerRequest request; + private final CanonicalRealmCatalogSnapshot catalogSnapshot; + private final String requestDigest; + + private PreparedInitialClosed( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalogSnapshot, + String requestDigest) { + this.request = Objects.requireNonNull(request, "request"); + this.catalogSnapshot = Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + this.requestDigest = Objects.requireNonNull(requestDigest, "requestDigest"); + } + + private CreateCanonicalClosedAdmissionPointerRequest request() { + return request; + } + + private CanonicalRealmCatalogSnapshot catalogSnapshot() { + return catalogSnapshot; + } + + private String requestDigest() { + return requestDigest; + } + } + + /** Opaque committed-origin preflight; callers cannot construct it or replace its exact origin. */ + public static final class PreparedExpectedClosed { + private final CanonicalClosedAdmissionPointerSnapshot committedOrigin; + private final long expectedPointerVersion; + private final long expectedCatalogRevision; + + private PreparedExpectedClosed( + CanonicalClosedAdmissionPointerSnapshot committedOrigin, + long expectedPointerVersion, + long expectedCatalogRevision) { + this.committedOrigin = Objects.requireNonNull(committedOrigin, "committedOrigin"); + this.expectedPointerVersion = expectedPointerVersion; + this.expectedCatalogRevision = expectedCatalogRevision; + } + + private CanonicalClosedAdmissionPointerSnapshot committedOrigin() { + return committedOrigin; + } + + private long expectedPointerVersion() { + return expectedPointerVersion; + } + + private long expectedCatalogRevision() { + return expectedCatalogRevision; + } + } + + /** + * Opaque local evidence that the exact original canonical CLOSED v1 pointer, its creation event, + * immutable request outcome, and initial catalog were positively verified under owner locks. This + * evidence is not caller authentication, World lifecycle or hold evidence, or OPEN authority. + */ + public static final class ExpectedClosedEvidence { + private final CanonicalClosedAdmissionPointerSnapshot verifiedOrigin; + + private ExpectedClosedEvidence(CanonicalClosedAdmissionPointerSnapshot verifiedOrigin) { + this.verifiedOrigin = Objects.requireNonNull(verifiedOrigin, "verifiedOrigin"); + } + + public String targetNamespace() { + return verifiedOrigin.targetNamespace(); + } + + public UUID originalRequestId() { + return verifiedOrigin.requestId(); + } + + public UUID canonicalTenantId() { + return verifiedOrigin.canonicalTenantId(); + } + + public UUID realmId() { + return verifiedOrigin.realmId(); + } + + public long pointerVersion() { + return verifiedOrigin.pointerVersion(); + } + + public long catalogRevision() { + return verifiedOrigin.catalogRevision(); + } + + public String requestDigest() { + return verifiedOrigin.requestDigest(); + } + + public String receiptDigest() { + return verifiedOrigin.receiptDigest(); + } + + public long auditEventId() { + return verifiedOrigin.auditEventId(); + } + + public boolean isNeverOpenOrigin() { + return CLOSED.equals(verifiedOrigin.admissionState()) + && verifiedOrigin.pointerVersion() == INITIAL_POINTER_VERSION + && verifiedOrigin.admissibleGameInstanceId() == null; + } + } + + public static class CanonicalClosedPointerConflictException extends IllegalStateException { + public CanonicalClosedPointerConflictException(String message) { + super(message); + } + + public CanonicalClosedPointerConflictException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class InvalidCanonicalClosedPointerEvidenceException extends IllegalStateException { + public InvalidCanonicalClosedPointerEvidenceException(String message) { + super(message); + } + + public InvalidCanonicalClosedPointerEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java new file mode 100644 index 0000000000..726ccc4196 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java @@ -0,0 +1,654 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.JSONB; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Game Session-owned immutable persistence for source-qualified launch preparation evidence. */ +public class GameSessionCanonicalLaunchPreparationRepository { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final String REQUEST_DOMAIN = + "game-session-canonical-launch-preparation-request/v1"; + private static final String RECEIPT_DOMAIN = + "game-session-canonical-launch-preparation-receipt/v1"; + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + + private static final Table PREPARATION = + DSL.table(DSL.name("game_session_canonical_launch_preparation")); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field ACTING_ACCOUNT_UUID = + DSL.field(DSL.name("acting_account_uuid"), UUID.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field REALM_ID = DSL.field(DSL.name("realm_id"), UUID.class); + private static final Field CATALOG_CREATION_REQUEST_ID = + DSL.field(DSL.name("catalog_creation_request_id"), UUID.class); + private static final Field CATALOG_REVISION = + DSL.field(DSL.name("catalog_revision"), Long.class); + private static final Field SOURCE_INTAKE_OPERATION_ID = + DSL.field(DSL.name("source_intake_operation_id"), UUID.class); + private static final Field SOURCE_INTAKE_REQUEST_ID = + DSL.field(DSL.name("source_intake_request_id"), UUID.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("source_registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field CATALOG_REQUEST_DIGEST = + DSL.field(DSL.name("catalog_request_digest"), String.class); + private static final Field CATALOG_RECEIPT_DIGEST = + DSL.field(DSL.name("catalog_receipt_digest"), String.class); + private static final Field SOURCE_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("source_intake_request_digest"), String.class); + private static final Field SOURCE_INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("source_intake_receipt_digest"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field DESCRIPTOR_REQUEST_DIGEST = + DSL.field(DSL.name("descriptor_request_digest"), String.class); + private static final Field DESCRIPTOR_RESULT_DIGEST = + DSL.field(DSL.name("descriptor_result_digest"), String.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + private static final Field REQUEST_EVIDENCE_JSON = + DSL.field(DSL.name("request_evidence_json"), JSONB.class); + private static final Field CATALOG_EVIDENCE_JSON = + DSL.field(DSL.name("catalog_evidence_json"), JSONB.class); + private static final Field SOURCE_INTAKE_EVIDENCE_JSON = + DSL.field(DSL.name("source_intake_evidence_json"), JSONB.class); + private static final Field LAUNCH_DESCRIPTOR_EVIDENCE_JSON = + DSL.field(DSL.name("launch_descriptor_evidence_json"), JSONB.class); + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected owner collaborators are validated before use; construction acquires no resources.") + public GameSessionCanonicalLaunchPreparationRepository( + DSLContext dsl, GameSessionCanonicalRealmCatalogRepository catalogRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + } + + /** Reads one complete committed preparation without repairing or re-resolving evidence. */ + @Transactional(propagation = Propagation.NEVER, readOnly = true) + public Optional readByControlPlaneRequestId( + String targetNamespace, String controlPlaneRequestId) { + requireSelector(targetNamespace, controlPlaneRequestId); + requireCommittedRead(); + Record row = find(targetNamespace, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(toSnapshot(row)); + } + + /** + * Persists one exact immutable source/catalog/descriptor composition under a caller-owned + * writable READ COMMITTED transaction. No network operation is performed while owner rows are + * locked. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalLaunchPreparationSnapshot persistPrepared( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot committedCatalog, + IntakeReceipt committedSource, + AuthoredWorldLaunchDescriptorEvidence descriptorEvidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(committedCatalog, "committedCatalog"); + Objects.requireNonNull(committedSource, "committedSource"); + Objects.requireNonNull(descriptorEvidence, "descriptorEvidence"); + requireWritableReadCommittedOwnerTransaction(); + requireEvidenceMatchesRequest(request, committedCatalog, committedSource, descriptorEvidence); + + Record existing = find(request.targetNamespace(), request.controlPlaneRequestId()); + if (existing != null) { + return requireExactPrepared( + existing, request, committedCatalog, committedSource, descriptorEvidence); + } + + CanonicalRealmCatalogSnapshot lockedCatalog = + catalogRepository.lockExactInitialPublicProduction( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision()); + if (!committedCatalog.equals(lockedCatalog)) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical catalog changed after launch preparation readback"); + } + IntakeReceipt lockedSource = lockExactSource(committedSource); + if (!committedSource.equals(lockedSource) + || !committedCatalog.sourceIntakeReceipt().equals(lockedSource)) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed authored-world source changed before launch preparation persistence"); + } + + UUID operationId = UUID.randomUUID(); + requireNonNil(operationId, "operationId"); + String requestDigest = + requestDigest(request, committedCatalog, committedSource, descriptorEvidence); + String receiptDigest = + receiptDigest( + operationId, + request, + committedCatalog, + committedSource, + descriptorEvidence, + requestDigest); + dsl.insertInto(PREPARATION) + .set(TARGET_NAMESPACE, request.targetNamespace()) + .set(CONTROL_PLANE_REQUEST_ID, request.controlPlaneRequestId()) + .set(OPERATION_ID, operationId) + .set(ACTING_ACCOUNT_UUID, request.actingAccountUuid()) + .set(CANONICAL_TENANT_ID, request.canonicalTenantId()) + .set(REALM_ID, request.realmId()) + .set(CATALOG_CREATION_REQUEST_ID, request.catalogCreationRequestId()) + .set(CATALOG_REVISION, request.catalogRevision()) + .set(SOURCE_INTAKE_OPERATION_ID, committedSource.operationId()) + .set(SOURCE_INTAKE_REQUEST_ID, committedSource.intakeRequestId()) + .set(SOURCE_REGISTRATION_REQUEST_ID, committedSource.source().registrationRequestId()) + .set(SOURCE_OPERATION_ID, committedSource.source().operationId()) + .set(CATALOG_REQUEST_DIGEST, committedCatalog.requestDigest()) + .set(CATALOG_RECEIPT_DIGEST, committedCatalog.receiptDigest()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, committedSource.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, committedSource.receiptDigest()) + .set(SOURCE_EVIDENCE_DIGEST, committedSource.source().evidenceDigest()) + .set(DESCRIPTOR_REQUEST_DIGEST, descriptorEvidence.requestDigest()) + .set(DESCRIPTOR_RESULT_DIGEST, descriptorEvidence.resultDigest()) + .set(REQUEST_DIGEST, requestDigest) + .set(RECEIPT_DIGEST, receiptDigest) + .set(REQUEST_EVIDENCE_JSON, toJson(request, "request")) + .set(CATALOG_EVIDENCE_JSON, toJson(committedCatalog, "catalog")) + .set(SOURCE_INTAKE_EVIDENCE_JSON, toJson(committedSource, "source intake")) + .set(LAUNCH_DESCRIPTOR_EVIDENCE_JSON, toJson(descriptorEvidence, "launch descriptor")) + .onConflictDoNothing() + .execute(); + + Record stored = find(request.targetNamespace(), request.controlPlaneRequestId()); + if (stored == null) { + throw new LaunchPreparationConflictException( + "Canonical launch preparation conflicts with existing immutable owner evidence"); + } + return requireExactPrepared( + stored, request, committedCatalog, committedSource, descriptorEvidence); + } + + public static String requestDigest( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + requireEvidenceMatchesRequest(request, catalog, source, descriptor); + AuthoredWorldSourceEvidence authoredSource = source.source(); + return digest( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.controlPlaneRequestId(), + request.actingAccountUuid().toString(), + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + request.sourceIntakeOperationId().toString(), + Long.toString(request.gameTemplateId()), + Boolean.toString(request.requestedScriptPatchVersionPresent()), + optional( + request.requestedScriptPatchVersionPresent(), request.requestedScriptPatchVersion()), + Boolean.toString(request.sourceVersionIdPresent()), + optional(request.sourceVersionIdPresent(), decimal(request.sourceVersionId())), + Boolean.toString(request.targetVersionIdPresent()), + optional(request.targetVersionIdPresent(), decimal(request.targetVersionId())), + Boolean.toString(request.requestedRuntimeFlagsJsonPresent()), + optional(request.requestedRuntimeFlagsJsonPresent(), request.requestedRuntimeFlagsJson()), + catalog.targetNamespace(), + catalog.tenantId().toString(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.realmId().toString(), + catalog.realmSlug(), + catalog.realmDisplayName(), + Boolean.toString(catalog.visible()), + Boolean.toString(catalog.publicProduction()), + catalog.stateScope(), + catalog.playableStateNamespaceId().toString(), + catalog.characterCreationPolicy(), + Long.toString(catalog.catalogRevision()), + catalog.creationRequestId().toString(), + catalog.requestDigest(), + catalog.receiptDigest(), + source.operationId().toString(), + source.intakeRequestId().toString(), + source.requestDigest(), + source.receiptDigest(), + Integer.toString(authoredSource.schemaVersion()), + authoredSource.registrationRequestId().toString(), + authoredSource.operationId().toString(), + authoredSource.requestDigest(), + authoredSource.canonicalTenantId().toString(), + authoredSource.tenantSlug(), + authoredSource.worldSlug(), + authoredSource.worldDisplayName(), + Long.toString(authoredSource.sourceGameRowId()), + authoredSource.sourceGameTenantKey(), + authoredSource.provenanceKind(), + authoredSource.evidenceDigest(), + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + public static String receiptDigest( + UUID operationId, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + String requestDigest) { + requireNonNil(operationId, "operationId"); + requireDigest(requestDigest, "requestDigest"); + return digest( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + operationId.toString(), + requestDigest, + request.targetNamespace(), + request.controlPlaneRequestId(), + request.actingAccountUuid().toString(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + catalog.requestDigest(), + catalog.receiptDigest(), + source.operationId().toString(), + source.intakeRequestId().toString(), + source.requestDigest(), + source.receiptDigest(), + source.source().evidenceDigest(), + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + private CanonicalLaunchPreparationSnapshot requireExactPrepared( + Record row, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + CanonicalLaunchPreparationSnapshot stored = toSnapshot(row); + if (!stored.request().equals(request) + || !stored.catalogSnapshot().equals(catalog) + || !stored.sourceIntakeReceipt().equals(source) + || !stored.launchDescriptorEvidence().equals(descriptor)) { + throw new LaunchPreparationConflictException( + "controlPlaneRequestId was reused with changed launch preparation evidence"); + } + return stored; + } + + private CanonicalLaunchPreparationSnapshot toSnapshot(Record row) { + try { + CreateCanonicalLaunchPreparationRequest request = + fromJson( + row.get(REQUEST_EVIDENCE_JSON, JSONB.class), + CreateCanonicalLaunchPreparationRequest.class); + CanonicalRealmCatalogSnapshot catalog = + fromJson( + row.get(CATALOG_EVIDENCE_JSON, JSONB.class), CanonicalRealmCatalogSnapshot.class); + IntakeReceipt source = + fromJson(row.get(SOURCE_INTAKE_EVIDENCE_JSON, JSONB.class), IntakeReceipt.class); + AuthoredWorldLaunchDescriptorEvidence descriptor = + fromJson( + row.get(LAUNCH_DESCRIPTOR_EVIDENCE_JSON, JSONB.class), + AuthoredWorldLaunchDescriptorEvidence.class); + CanonicalLaunchPreparationSnapshot snapshot = + new CanonicalLaunchPreparationSnapshot( + required(row.get(OPERATION_ID), "operationId"), + request, + catalog, + source, + descriptor, + required(row.get(REQUEST_DIGEST), "requestDigest"), + required(row.get(RECEIPT_DIGEST), "receiptDigest")); + snapshot.requireValid(); + String expectedRequestDigest = requestDigest(request, catalog, source, descriptor); + String expectedReceiptDigest = + receiptDigest( + snapshot.operationId(), request, catalog, source, descriptor, expectedRequestDigest); + if (!request.targetNamespace().equals(required(row.get(TARGET_NAMESPACE), "targetNamespace")) + || !request + .controlPlaneRequestId() + .equals(required(row.get(CONTROL_PLANE_REQUEST_ID), "controlPlaneRequestId")) + || !request + .actingAccountUuid() + .equals(required(row.get(ACTING_ACCOUNT_UUID), "actingAccountUuid")) + || !request + .canonicalTenantId() + .equals(required(row.get(CANONICAL_TENANT_ID), "canonicalTenantId")) + || !request.realmId().equals(required(row.get(REALM_ID), "realmId")) + || !request + .catalogCreationRequestId() + .equals(required(row.get(CATALOG_CREATION_REQUEST_ID), "catalogCreationRequestId")) + || request.catalogRevision() != required(row.get(CATALOG_REVISION), "catalogRevision") + || !source + .operationId() + .equals(required(row.get(SOURCE_INTAKE_OPERATION_ID), "sourceIntakeOperationId")) + || !source + .intakeRequestId() + .equals(required(row.get(SOURCE_INTAKE_REQUEST_ID), "sourceIntakeRequestId")) + || !source + .source() + .registrationRequestId() + .equals( + required(row.get(SOURCE_REGISTRATION_REQUEST_ID), "sourceRegistrationRequestId")) + || !source + .source() + .operationId() + .equals(required(row.get(SOURCE_OPERATION_ID), "sourceOperationId")) + || !catalog + .requestDigest() + .equals(required(row.get(CATALOG_REQUEST_DIGEST), "catalogRequestDigest")) + || !catalog + .receiptDigest() + .equals(required(row.get(CATALOG_RECEIPT_DIGEST), "catalogReceiptDigest")) + || !source + .requestDigest() + .equals(required(row.get(SOURCE_INTAKE_REQUEST_DIGEST), "sourceIntakeRequestDigest")) + || !source + .receiptDigest() + .equals(required(row.get(SOURCE_INTAKE_RECEIPT_DIGEST), "sourceIntakeReceiptDigest")) + || !source + .source() + .evidenceDigest() + .equals(required(row.get(SOURCE_EVIDENCE_DIGEST), "sourceEvidenceDigest")) + || !descriptor + .requestDigest() + .equals(required(row.get(DESCRIPTOR_REQUEST_DIGEST), "descriptorRequestDigest")) + || !descriptor + .resultDigest() + .equals(required(row.get(DESCRIPTOR_RESULT_DIGEST), "descriptorResultDigest")) + || !expectedRequestDigest.equals(snapshot.requestDigest()) + || !expectedReceiptDigest.equals(snapshot.receiptDigest())) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted launch preparation evidence does not match its stored identity and digests"); + } + return snapshot; + } catch (InvalidLaunchPreparationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted canonical launch preparation evidence is invalid", exception); + } + } + + private IntakeReceipt lockExactSource(IntakeReceipt expected) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ? FOR UPDATE", + expected.source().targetNamespace(), + expected.operationId()); + if (row == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Exact committed authored-world source intake is missing at launch preparation commit"); + } + try { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required(row.get("source_schema_version", Integer.class), "sourceSchemaVersion"), + required(row.get("target_namespace", String.class), "sourceTargetNamespace"), + required( + row.get("source_registration_request_id", UUID.class), + "sourceRegistrationRequestId"), + required(row.get("source_operation_id", UUID.class), "sourceOperationId"), + required(row.get("source_request_digest", String.class), "sourceRequestDigest"), + required(row.get("canonical_tenant_id", UUID.class), "sourceCanonicalTenantId"), + required(row.get("tenant_slug", String.class), "sourceTenantSlug"), + required(row.get("world_slug", String.class), "sourceWorldSlug"), + required(row.get("world_display_name", String.class), "sourceWorldDisplayName"), + required(row.get("source_game_row_id", Long.class), "sourceGameRowId"), + required(row.get("source_game_tenant_key", String.class), "sourceGameTenantKey"), + required(row.get("source_provenance_kind", String.class), "sourceProvenanceKind"), + required(row.get("source_evidence_digest", String.class), "sourceEvidenceDigest")); + if (!Integer.valueOf(SCHEMA_VERSION).equals(row.get("schema_version", Integer.class))) { + throw new IllegalArgumentException("Unsupported source intake schema version"); + } + IntakeReceipt locked = + new IntakeReceipt( + required(row.get("operation_id", UUID.class), "sourceIntakeOperationId"), + required(row.get("intake_request_id", UUID.class), "sourceIntakeRequestId"), + required(row.get("request_digest", String.class), "sourceIntakeRequestDigest"), + source, + required(row.get("receipt_digest", String.class), "sourceIntakeReceiptDigest")); + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch preparation requires exact fresh authored-world source evidence"); + } + return locked; + } catch (InvalidLaunchPreparationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted authored-world source evidence is invalid", exception); + } + } + + private Record find(String targetNamespace, String controlPlaneRequestId) { + return dsl.selectFrom(PREPARATION) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) + .fetchOne(); + } + + private static void requireEvidenceMatchesRequest( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(descriptor, "descriptor"); + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !source.equals(catalog.sourceIntakeReceipt()) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !descriptor.request().equals(request.descriptorRequest(catalog, source.source()))) { + throw new InvalidLaunchPreparationEvidenceException( + "Launch preparation does not match exact fresh catalog/source/descriptor evidence"); + } + descriptor.requireValid(); + } + + private static void requireSelector(String namespace, String controlPlaneRequestId) { + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId is required"); + } + strictUtf8(controlPlaneRequestId); + } + + private static void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Launch preparation read requires committed owner evidence"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Launch preparation persistence requires a writable owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Launch preparation persistence requires the owner READ COMMITTED connection"); + } + return null; + }); + Record isolation = dsl.fetchOne("SHOW transaction_isolation"); + if (isolation == null + || !"read committed".equalsIgnoreCase(isolation.get(0, String.class).trim())) { + throw new IllegalStateException("Launch preparation persistence requires READ COMMITTED"); + } + } + + private static JSONB toJson(Object value, String name) { + try { + return JSONB.valueOf(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException("Could not store exact " + name + " evidence", exception); + } + } + + private static T fromJson(JSONB value, Class type) { + if (value == null) { + throw new InvalidLaunchPreparationEvidenceException("Persisted JSON evidence is missing"); + } + try { + return JSON.readValue(value.data(), type); + } catch (IOException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted closed launch preparation evidence cannot be decoded", exception); + } + } + + private static String digest(String domain, String... values) { + try { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + writeSegment(preimage, domain); + for (String value : values) { + writeSegment(preimage, value); + } + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must be well-formed UTF-8", exception); + } + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static String optional(boolean present, String value) { + return present ? Objects.requireNonNull(value, "present optional value") : ""; + } + + private static void requireDigest(String value, String fieldName) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(fieldName + " must be a canonical SHA-256 digest"); + } + } + + private static void requireNonNil(UUID value, String fieldName) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a non-nil UUID"); + } + } + + private static T required(T value, String fieldName) { + if (value == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted launch preparation " + fieldName + " is missing"); + } + return value; + } + + public static final class LaunchPreparationConflictException extends IllegalStateException { + public LaunchPreparationConflictException(String message) { + super(message); + } + } + + public static final class InvalidLaunchPreparationEvidenceException + extends IllegalStateException { + public InvalidLaunchPreparationEvidenceException(String message) { + super(message); + } + + public InvalidLaunchPreparationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index 7210542b41..d536834367 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -5,11 +5,17 @@ import static net.firedevops.firemud.gamesession.jooq.tables.GameplayAdmissionPointerEvent.GAMEPLAY_ADMISSION_POINTER_EVENT; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerEventRecord; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; @@ -18,6 +24,9 @@ import org.jooq.Record; import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; @Repository @SuppressFBWarnings( @@ -161,6 +170,135 @@ public GameplayAdmissionPointerEvent save(GameplayAdmissionPointerEvent entity) return findById(entity.getId()); } + /** Appends the exact canonical first-OPEN event inside the pointer/attempt owner transaction. */ + public long appendCanonicalInitialAdmissionOpen( + CanonicalInitialAdmissionRequest request, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launchTarget, + long pointerVersion, + long auditCatalogRevision, + Instant occurredAt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(launchTarget, "launchTarget"); + Objects.requireNonNull(occurredAt, "occurredAt"); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical initial admission audit requires the writable owner transaction"); + } + var association = launchTarget.association(); + Record inserted = + dsl.fetchOne( + "INSERT INTO gameplay_admission_pointer_event (" + + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, actor_principal, reason, " + + "control_plane_request_id, occurred_at, prepared_version_upgrade_id, " + + "public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state, canonical_game_instance_id, " + + "canonical_version_id, runtime_version_id, initial_admission_request_id, " + + "initial_admission_request_digest, initial_admission_origin_kind, " + + "initial_admission_prior_pointer_version, initial_admission_active_epoch, " + + "initial_admission_hold_id, initial_admission_hold_fence, " + + "initial_admission_hold_binding_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, " + + "'game-session-canonical-initial-admission', " + + "'World-held initial admission', ?, ?, NULL, ?, ?, ?, ?, 3, ?, ?, 'OPEN', ?, ?, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + catalog.worldSlug(), + catalog.realmSlug(), + catalog.sourceIntakeReceipt().source().worldDisplayName(), + catalog.realmDisplayName(), + association.gameSessionTenantId(), + launchTarget.gameInstanceId(), + pointerVersion, + catalog.visible(), + catalog.stateScope(), + catalog.characterCreationPolicy(), + request.initialAdmissionRequestId(), + toLocalDateTime(occurredAt), + catalog.publicProduction(), + auditCatalogRevision, + catalog.realmId(), + catalog.playableStateNamespaceId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + launchTarget.runtimeVersionId(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest()); + if (inserted == null || inserted.get("id", Long.class) == null) { + throw new IllegalStateException("Canonical initial admission audit insert returned no event"); + } + return inserted.get("id", Long.class); + } + + /** Appends the single canonical CLOSED audit event inside its pointer owner transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public long appendCanonicalClosed( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + String worldSlug, + String realmSlug, + long catalogRevision, + String actorPrincipal, + String reason, + UUID requestId, + Instant occurredAt) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(actorPrincipal, "actorPrincipal"); + Objects.requireNonNull(reason, "reason"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(occurredAt, "occurredAt"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + Record inserted = + dsl.fetchOne( + "INSERT INTO gameplay_admission_pointer_event (" + + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, actor_principal, reason, " + + "control_plane_request_id, occurred_at, prepared_version_upgrade_id, " + + "public_production_realm, representation_version, target_namespace, " + + "canonical_tenant_id, realm_id, catalog_revision, admission_state) " + + "VALUES (?, ?, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, ?, ?, ?, ?, " + + "NULL, NULL, 2, ?, ?, ?, ?, 'CLOSED') RETURNING id", + worldSlug, + realmSlug, + actorPrincipal, + reason, + requestId.toString(), + toLocalDateTime(occurredAt), + targetNamespace, + canonicalTenantId, + realmId, + catalogRevision); + if (inserted == null) { + throw new IllegalStateException( + "Canonical CLOSED admission-pointer audit insert returned no id"); + } + Long eventId = inserted.get("id", Long.class); + if (eventId == null || eventId <= 0L) { + throw new IllegalStateException("Canonical CLOSED admission-pointer event id is invalid"); + } + return eventId; + } + public void deleteAllInBatch() { dsl.deleteFrom(GAMEPLAY_ADMISSION_POINTER_EVENT).execute(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java new file mode 100644 index 0000000000..9bd141e8bb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; + +/** Game Session-owned canonical initial OPEN operation and exact owner readback. */ +public interface CanonicalInitialAdmissionService { + CanonicalInitialAdmissionOwnerProof bind(CanonicalInitialAdmissionRequest request); + + CanonicalInitialAdmissionOwnerProof abort( + CanonicalInitialAdmissionRequest request, String reason); + + CanonicalInitialAdmissionOwnerProof read(String targetNamespace, String requestId); +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java new file mode 100644 index 0000000000..448d9e7f74 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; + +/** + * Remote World owner boundary. Implementations must verify the current ACTIVE lifecycle evidence + * and exact immutable {@code WorldCanonicalInitialAdmissionHold.HoldIdentity} outside SQL, then + * return its complete request/hold tuple and World binding digest. A supplied local request or + * caller authentication context is never owner proof. + */ +public interface CanonicalInitialAdmissionWorldVerifier { + CanonicalInitialAdmissionWorldProof verify(CanonicalInitialAdmissionRequest request); +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java new file mode 100644 index 0000000000..63172409b7 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java @@ -0,0 +1,444 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.InvalidLaunchPreparationEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.LaunchPreparationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import org.springframework.lang.Nullable; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired Game Session consumer for exact source-qualified launch preparation. It persists no game + * instance, calls no World API, and does not authorize creator or launch actions. + */ +public class GameSessionCanonicalLaunchPreparationService { + private final AuthoredWorldLaunchDescriptorClient descriptorClient; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final GameSessionAuthoredWorldSourceRepository sourceRepository; + private final GameSessionCanonicalLaunchPreparationRepository preparationRepository; + @Nullable private final GameSessionStartSessionOperatorAttemptRepository attemptRepository; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted owner collaborators and namespace are validated before use; construction acquires no resources.") + public GameSessionCanonicalLaunchPreparationService( + AuthoredWorldLaunchDescriptorClient descriptorClient, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + null, + transactionManager, + workloadNamespace); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted owner collaborators and namespace are validated before use; construction acquires no resources.") + public GameSessionCanonicalLaunchPreparationService( + AuthoredWorldLaunchDescriptorClient descriptorClient, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + GameSessionStartSessionOperatorAttemptRepository attemptRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.descriptorClient = Objects.requireNonNull(descriptorClient, "descriptorClient"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.sourceRepository = Objects.requireNonNull(sourceRepository, "sourceRepository"); + this.preparationRepository = + Objects.requireNonNull(preparationRepository, "preparationRepository"); + this.attemptRepository = attemptRepository; + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Resolves and independently reads back exact immutable Game Design evidence before taking any + * catalog/source owner locks. Exact retries return the original preparation without network I/O. + */ + public CanonicalLaunchPreparationSnapshot prepare( + CreateCanonicalLaunchPreparationRequest request) { + return prepareInternal(request, null); + } + + /** + * Validates a current durable StartSession claim and its exact attached Account projection before + * any Game Design call, then revalidates the same claim in the launch-preparation commit + * transaction. The stored projection is integrity/binding evidence only: it is not a fresh + * Account authority read or a commit gate. This service remains deliberately unwired. + */ + public CanonicalLaunchPreparationSnapshot prepareAuthorized( + AttemptClaim claim, CreateCanonicalLaunchPreparationRequest request) { + Objects.requireNonNull(claim, "current StartSession owner claim is required"); + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + requireWorkloadNamespace(request); + final GameSessionStartSessionOperatorAttemptRepository attempts = attemptRepository; + if (attempts == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Authorized launch preparation is unavailable without the owner-attempt repository"); + } + if (!workloadNamespace.equals(claim.targetNamespace()) + || !request.targetNamespace().equals(claim.targetNamespace()) + || !request.controlPlaneRequestId().equals(claim.controlPlaneRequestId())) { + throw new InvalidLaunchPreparationEvidenceException( + "StartSession claim does not identify the exact launch-preparation request"); + } + + AttemptSnapshot captured = + ownerTransaction.execute(status -> attempts.validateCurrentClaim(claim)); + if (captured == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Current StartSession owner attempt was not read back"); + } + StartSessionPostAuthorizationExecutionTuple tuple = + validateAuthorizedAttempt(claim, request, captured); + return prepareInternal(request, new AuthorizedAttempt(claim, captured, tuple)); + } + + private CanonicalLaunchPreparationSnapshot prepareInternal( + CreateCanonicalLaunchPreparationRequest request, + @Nullable AuthorizedAttempt authorizedAttempt) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + requireWorkloadNamespace(request); + + Optional prior = + preparationRepository.readByControlPlaneRequestId( + workloadNamespace, request.controlPlaneRequestId()); + if (prior.isPresent()) { + CanonicalLaunchPreparationSnapshot stored = prior.orElseThrow(); + stored.requireValid(); + if (!stored.request().equals(request)) { + throw new LaunchPreparationConflictException( + "controlPlaneRequestId was reused with changed launch preparation inputs"); + } + return stored; + } + + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(workloadNamespace, request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Exact committed canonical realm catalog is missing")); + requireCatalogBinding(request, catalog); + IntakeReceipt source = + sourceRepository + .read( + request.sourceIntakeOperationId(), + request.canonicalTenantId(), + catalog.worldSlug(), + workloadNamespace) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Exact committed authored-world source intake is missing")); + requireSourceBinding(request, catalog, source); + + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = + request.descriptorRequest(catalog, source.source()); + AuthoredWorldLaunchDescriptorEvidence resolved = descriptorClient.resolve(descriptorRequest); + if (resolved == null + || !descriptorRequest.equals(resolved.request()) + || !workloadNamespace.equals(resolved.targetNamespace())) { + throw new InvalidLaunchPreparationEvidenceException( + "Resolved Game Design descriptor does not match the exact launch preparation request"); + } + resolved.requireValid(); + + AuthoredWorldLaunchDescriptorEvidence readback = + descriptorClient.get( + new GetRequest(UUID.randomUUID(), descriptorRequest, resolved.resultDigest())); + if (!resolved.equals(readback)) { + throw new InvalidLaunchPreparationEvidenceException( + "Independent Game Design descriptor readback differs from the resolved evidence"); + } + + CanonicalLaunchPreparationSnapshot written = + ownerTransaction.execute( + status -> { + if (authorizedAttempt != null) { + AttemptSnapshot current = + Objects.requireNonNull(attemptRepository, "attempt repository is required") + .validateCurrentClaim(authorizedAttempt.claim()); + StartSessionPostAuthorizationExecutionTuple currentTuple = + validateAuthorizedAttempt(authorizedAttempt.claim(), request, current); + requireSameAuthorizedAttempt( + authorizedAttempt.snapshot(), authorizedAttempt.tuple(), current, currentTuple); + } + return preparationRepository.persistPrepared(request, catalog, source, readback); + }); + if (written == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Game Session owner transaction returned no launch preparation result"); + } + + Optional committed = + preparationRepository.readByControlPlaneRequestId( + workloadNamespace, request.controlPlaneRequestId()); + if (committed.isEmpty()) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation is missing after independent readback"); + } + CanonicalLaunchPreparationSnapshot exact = committed.orElseThrow(); + exact.requireValid(); + if (!written.equals(exact)) { + throw new InvalidLaunchPreparationEvidenceException( + "Launch preparation changed during independent commit readback"); + } + return exact; + } + + private void requireWorkloadNamespace(CreateCanonicalLaunchPreparationRequest request) { + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new SecurityException("Launch preparation namespace does not match this workload"); + } + } + + private static StartSessionPostAuthorizationExecutionTuple validateAuthorizedAttempt( + AttemptClaim claim, + CreateCanonicalLaunchPreparationRequest request, + AttemptSnapshot snapshot) { + if (!claim.controlPlaneRequestId().equals(snapshot.controlPlaneRequestId()) + || !claim.targetNamespace().equals(snapshot.targetNamespace()) + || !claim.ownerAttemptId().equals(snapshot.ownerAttemptId()) + || !claim.ownerMutationId().equals(snapshot.ownerMutationId()) + || claim.ownerFence() != snapshot.ownerFence() + || !"OWNER_EXECUTION_PENDING".equals(snapshot.phaseState())) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted StartSession attempt differs from the exact live owner claim"); + } + + final StartSessionPostAuthorizationExecutionTuple tuple; + try { + tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + snapshot.postAuthorizationExecutionTuple()); + } catch (IllegalArgumentException malformed) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted StartSession attempt tuple is invalid", malformed); + } + var preTuple = tuple.preAuthorizationTuple(); + var action = preTuple.action(); + if (!tuple.controlPlaneRequestId().equals(request.controlPlaneRequestId()) + || !preTuple.controlPlaneRequestId().equals(claim.controlPlaneRequestId()) + || !action.scope().targetNamespace().equals(request.targetNamespace()) + || !snapshot.targetNamespace().equals(request.targetNamespace()) + || !snapshot.canonicalTenantId().equals(request.canonicalTenantId()) + || !action.scope().tenantId().equals(request.canonicalTenantId()) + || !preTuple.actor().accountId().equals(request.actingAccountUuid()) + || action.target().gameTemplateId() != request.gameTemplateId() + || !"game-session-service".equals(action.targetOwner()) + || !"human_operator".equals(tuple.issuanceKind())) { + throw new InvalidLaunchPreparationEvidenceException( + "Launch preparation does not match the authorized StartSession actor, tenant, or template"); + } + if (request.requestedScriptPatchVersionPresent() + || request.sourceVersionIdPresent() + || request.targetVersionIdPresent() + || request.requestedRuntimeFlagsJsonPresent()) { + throw new LaunchPreparationConflictException( + "StartSession action does not authorize launch descriptor overrides"); + } + + byte[] storedProjection = snapshot.accountRedemptionProjection(); + if (storedProjection == null || storedProjection.length == 0) { + throw new InvalidLaunchPreparationEvidenceException( + "Exact Account redemption projection is not attached to the StartSession attempt"); + } + try { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + bundle.requireTupleBinding(preTuple); + bundle.requireReferenceBinding(tuple.bundleReference()); + long issuanceFence = positiveLongFence(tuple.issuanceFence()); + byte[] expectedProjection = + new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + issuanceFence) + .canonicalBytes(); + if (!Arrays.equals(expectedProjection, storedProjection)) { + throw new InvalidLaunchPreparationEvidenceException( + "Attached Account redemption projection differs from the original post-authorization tuple"); + } + } catch (IllegalArgumentException malformed) { + throw new InvalidLaunchPreparationEvidenceException( + "StartSession Account redemption projection binding is invalid", malformed); + } + return tuple; + } + + private static long positiveLongFence(String value) { + try { + long fence = Long.parseLong(value); + if (fence <= 0L) { + throw new NumberFormatException("non-positive fence"); + } + return fence; + } catch (NumberFormatException malformed) { + throw new InvalidLaunchPreparationEvidenceException( + "Account issuance fence is outside the supported positive range", malformed); + } + } + + private static void requireSameAuthorizedAttempt( + AttemptSnapshot first, + StartSessionPostAuthorizationExecutionTuple firstTuple, + AttemptSnapshot second, + StartSessionPostAuthorizationExecutionTuple secondTuple) { + if (!first.ownerAttemptId().equals(second.ownerAttemptId()) + || !first.ownerMutationId().equals(second.ownerMutationId()) + || first.ownerFence() != second.ownerFence() + || !Arrays.equals( + first.postAuthorizationExecutionTuple(), second.postAuthorizationExecutionTuple()) + || !Arrays.equals(first.accountRedemptionProjection(), second.accountRedemptionProjection()) + || !Arrays.equals(firstTuple.canonicalBytes(), secondTuple.canonicalBytes())) { + throw new InvalidLaunchPreparationEvidenceException( + "StartSession owner attempt changed before launch preparation commit"); + } + } + + private record AuthorizedAttempt( + AttemptClaim claim, + AttemptSnapshot snapshot, + StartSessionPostAuthorizationExecutionTuple tuple) {} + + /** + * Reads the complete authenticated Game Design binding for one exact committed preparation. This + * is a non-admitting evidence read: it neither creates nor advances a game instance. + */ + public CompleteLaunchBindingEvidence readCompleteBinding( + CanonicalLaunchPreparationSnapshot snapshot) { + Objects.requireNonNull(snapshot, "snapshot"); + requireNoAmbientTransaction(); + snapshot.requireValid(); + if (!workloadNamespace.equals(snapshot.request().targetNamespace())) { + throw new SecurityException("Launch preparation namespace does not match this workload"); + } + + CanonicalLaunchPreparationSnapshot committed = + preparationRepository + .readByControlPlaneRequestId( + workloadNamespace, snapshot.request().controlPlaneRequestId()) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation is missing before complete binding read")); + committed.requireValid(); + if (!snapshot.equals(committed)) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation changed before complete binding read"); + } + + AuthoredWorldLaunchDescriptorEvidence descriptor = snapshot.launchDescriptorEvidence(); + GetRequest readSelector = + new GetRequest(randomNonNilUuid(), descriptor.request(), descriptor.resultDigest()); + CompleteLaunchBindingEvidence binding = + descriptorClient.getComplete( + AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(readSelector)); + if (binding == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Game Design returned no complete launch binding"); + } + binding.descriptor().requireValid(); + binding.releaseAttestation().requireValid(binding.descriptor()); + if (!descriptor.equals(binding.descriptor()) + || !workloadNamespace.equals(binding.descriptor().targetNamespace())) { + throw new InvalidLaunchPreparationEvidenceException( + "Complete Game Design binding differs from the committed launch descriptor"); + } + return binding; + } + + private static void requireCatalogBinding( + CreateCanonicalLaunchPreparationRequest request, CanonicalRealmCatalogSnapshot catalog) { + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !catalog.visible() + || !catalog.publicProduction()) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch request does not match the exact committed initial catalog"); + } + } + + private static void requireSourceBinding( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source) { + if (!request.targetNamespace().equals(source.source().targetNamespace()) + || !request.canonicalTenantId().equals(source.source().canonicalTenantId()) + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !catalog.sourceIntakeReceipt().equals(source) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !catalog.worldSlug().equals(source.source().worldSlug())) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch request does not match the exact fresh source intake"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical launch preparation cannot enter from an ambient transaction"); + } + } + + private static UUID randomNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (new UUID(0L, 0L).equals(value)); + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java new file mode 100644 index 0000000000..5d1dd541fd --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java @@ -0,0 +1,232 @@ +package net.firedevops.firemud.gamesession.service; + +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClient; +import net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClient.RedemptionResult; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationDisposition; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Disabled-by-default, non-activating composition of the durable owner attempt and Account + * redemption. + * + *

It commits the exact owner claim before making the one Account call. Exact retries only return + * the existing snapshot; an ambiguous Account transport outcome remains pending and is never + * automatically retried or terminalized here. + */ +public final class GameSessionStartSessionOperatorAuthorizationCoordinator { + private static final String LOGGING_ADMIN_SERVICE = "logging-admin-service"; + + private final GameSessionStartSessionOperatorAttemptRepository attemptRepository; + private final StartSessionOperatorRedemptionClient redemptionClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public GameSessionStartSessionOperatorAuthorizationCoordinator( + GameSessionStartSessionOperatorAttemptRepository attemptRepository, + StartSessionOperatorRedemptionClient redemptionClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.attemptRepository = + Objects.requireNonNull(attemptRepository, "owner-attempt repository is required"); + this.redemptionClient = + Objects.requireNonNull(redemptionClient, "redemption client is required"); + Objects.requireNonNull(transactionManager, "transaction manager is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be valid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Reserves one attempt, redeems once only for its newly created claim, then attaches the exact + * Account projection under that same still-current claim. The authorization reference is + * transient input and is never returned or persisted by this coordinator. + */ + public AuthorizationResult authorize( + StartSessionPostAuthorizationExecutionTuple tuple, + String transientOperatorAuthorizationReference) { + Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); + Objects.requireNonNull( + transientOperatorAuthorizationReference, "transient Account reference is required"); + requireNoAmbientTransaction(); + requireAuthenticatedLoggingPeer(tuple); + + ReservationResult reservation = + ownerTransaction.execute(status -> attemptRepository.reserve(tuple)); + if (reservation == null) { + throw new IllegalStateException("Game Session owner reservation returned no result"); + } + requireReservationMatchesTuple(reservation.snapshot(), tuple); + + if (reservation.disposition() == ReservationDisposition.EXACT_REPLAY) { + if (reservation.claim().isPresent()) { + throw new IllegalStateException("Exact owner-attempt replay unexpectedly returned a claim"); + } + return new AuthorizationResult( + reservation.snapshot(), Optional.empty(), Progress.EXACT_REPLAY); + } + + AttemptClaim claim = + reservation + .claim() + .orElseThrow(() -> new IllegalStateException("New owner attempt returned no claim")); + requireClaimMatchesTuple(claim, tuple); + requireSnapshotMatchesClaim(reservation.snapshot(), claim, tuple); + requireNoAmbientTransaction(); + + RedemptionResult redemption; + try { + redemption = redemptionClient.redeem(tuple, transientOperatorAuthorizationReference, claim); + } catch (StatusRuntimeException ambiguousTransportOutcome) { + return new AuthorizationResult( + reservation.snapshot(), Optional.of(claim), Progress.ACCOUNT_OUTCOME_AMBIGUOUS); + } + if (redemption == null || !claim.equals(redemption.gameSessionClaim())) { + throw new IllegalStateException( + "Account redemption result is not bound to the reserved Game Session claim"); + } + AccountRedemptionProjection projection = redemption.projection(); + + AttemptSnapshot attached = + ownerTransaction.execute( + status -> { + AttemptSnapshot current = attemptRepository.validateCurrentClaim(claim); + requireSameCurrentAttempt(reservation.snapshot(), current, claim, tuple); + return attemptRepository.attachAccountRedemptionProjection(claim, projection); + }); + if (attached == null) { + throw new IllegalStateException("Account projection attachment returned no owner snapshot"); + } + requireSnapshotMatchesClaim(attached, claim, tuple); + if (!Arrays.equals(attached.accountRedemptionProjection(), projection.canonicalBytes())) { + throw new IllegalStateException( + "Persisted Account projection differs from the exact redemption response"); + } + return new AuthorizationResult( + attached, Optional.of(claim), Progress.ACCOUNT_PROJECTION_ATTACHED); + } + + private void requireAuthenticatedLoggingPeer(StartSessionPostAuthorizationExecutionTuple tuple) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String tupleNamespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + if (peer == null + || !LOGGING_ADMIN_SERVICE.equals(peer.service()) + || !workloadNamespace.equals(peer.namespace()) + || !workloadNamespace.equals(tupleNamespace) + || !peer.uri().equals(tuple.authenticatedWorkloadIdentity())) { + throw new SecurityException( + "Authenticated peer is not the exact same-namespace Logging and Admin workload"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "StartSession Account redemption cannot run inside an ambient owner transaction"); + } + } + + private static void requireReservationMatchesTuple( + AttemptSnapshot snapshot, StartSessionPostAuthorizationExecutionTuple tuple) { + if (!tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(snapshot.targetNamespace()) + || !tuple.controlPlaneRequestId().equals(snapshot.controlPlaneRequestId()) + || !Arrays.equals(tuple.canonicalBytes(), snapshot.postAuthorizationExecutionTuple())) { + throw new IllegalStateException( + "Durable owner reservation differs from the exact StartSession tuple"); + } + } + + private static void requireClaimMatchesTuple( + AttemptClaim claim, StartSessionPostAuthorizationExecutionTuple tuple) { + if (!tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(claim.targetNamespace()) + || !tuple.controlPlaneRequestId().equals(claim.controlPlaneRequestId())) { + throw new IllegalStateException("New owner claim differs from the exact StartSession tuple"); + } + } + + private static void requireSnapshotMatchesClaim( + AttemptSnapshot snapshot, + AttemptClaim claim, + StartSessionPostAuthorizationExecutionTuple tuple) { + requireReservationMatchesTuple(snapshot, tuple); + if (!claim.ownerAttemptId().equals(snapshot.ownerAttemptId()) + || !claim.ownerMutationId().equals(snapshot.ownerMutationId()) + || claim.ownerFence() != snapshot.ownerFence()) { + throw new IllegalStateException( + "Durable owner snapshot differs from the exact StartSession claim"); + } + } + + private static void requireSameCurrentAttempt( + AttemptSnapshot reserved, + AttemptSnapshot current, + AttemptClaim claim, + StartSessionPostAuthorizationExecutionTuple tuple) { + requireSnapshotMatchesClaim(current, claim, tuple); + if (!reserved.ownerAttemptId().equals(current.ownerAttemptId()) + || !reserved.ownerMutationId().equals(current.ownerMutationId()) + || reserved.ownerFence() != current.ownerFence() + || !reserved.phaseState().equals(current.phaseState())) { + throw new IllegalStateException( + "Current Game Session claim no longer identifies its original pending attempt"); + } + } + + public enum Progress { + EXACT_REPLAY, + ACCOUNT_OUTCOME_AMBIGUOUS, + ACCOUNT_PROJECTION_ATTACHED + } + + /** Secret-free durable progress result; the raw Account reference is deliberately excluded. */ + public record AuthorizationResult( + AttemptSnapshot snapshot, Optional claim, Progress progress) { + public AuthorizationResult { + Objects.requireNonNull(snapshot, "durable owner-attempt snapshot is required"); + Objects.requireNonNull(claim, "owner claim wrapper is required"); + Objects.requireNonNull(progress, "authorization progress is required"); + if ((progress == Progress.EXACT_REPLAY) != claim.isEmpty()) { + throw new IllegalArgumentException( + "only exact owner-attempt replays may omit the new claim"); + } + if (progress == Progress.ACCOUNT_PROJECTION_ATTACHED + && snapshot.accountRedemptionProjection() == null) { + throw new IllegalArgumentException( + "attached progress requires the exact durable Account projection"); + } + if (progress == Progress.ACCOUNT_OUTCOME_AMBIGUOUS + && snapshot.accountRedemptionProjection() != null) { + throw new IllegalArgumentException( + "ambiguous Account progress cannot contain a redemption projection"); + } + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java new file mode 100644 index 0000000000..6ee3caee75 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.util.Objects; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.PreparedExpectedClosed; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionService; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Durable owner operation; remote World proof is acquired before entering its short SQL + * transaction. + */ +public final class DatabaseCanonicalInitialAdmissionService + implements CanonicalInitialAdmissionService { + private final CanonicalInitialAdmissionRepository repository; + private final GameSessionCanonicalAdmissionPointerRepository pointerRepository; + private final CanonicalInitialAdmissionWorldVerifier worldVerifier; + + public DatabaseCanonicalInitialAdmissionService( + CanonicalInitialAdmissionRepository repository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalInitialAdmissionWorldVerifier worldVerifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.pointerRepository = Objects.requireNonNull(pointerRepository, "pointerRepository"); + this.worldVerifier = Objects.requireNonNull(worldVerifier, "worldVerifier"); + } + + @Override + public CanonicalInitialAdmissionOwnerProof bind(CanonicalInitialAdmissionRequest request) { + requireNoAmbientTransaction(); + Objects.requireNonNull(request, "request"); + repository.reserve(request); + CanonicalInitialAdmissionOwnerProof beforeRemote = + requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); + if (beforeRemote.outcome() != CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + return beforeRemote; + } + + PreparedExpectedClosed preparedOrigin = prepareExpectedClosed(request); + // This owner call is intentionally outside the repository transaction and can be retried by + // the stable durable request identity after an unavailable or ambiguous response. + CanonicalInitialAdmissionWorldProof worldProof = worldVerifier.verify(request); + if (worldProof == null) { + throw new IllegalStateException("World initial-admission verifier returned no owner proof"); + } + worldProof.requireMatches(request); + repository.commit(request, worldProof, preparedOrigin); + + CanonicalInitialAdmissionOwnerProof result = + requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); + if (result.outcome() == CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + throw new CanonicalInitialAdmissionRepository + .CanonicalInitialAdmissionReconciliationRequiredException( + "Initial-admission owner transaction did not produce an exact terminal result readback"); + } + return result; + } + + @Override + public CanonicalInitialAdmissionOwnerProof abort( + CanonicalInitialAdmissionRequest request, String reason) { + requireNoAmbientTransaction(); + Objects.requireNonNull(request, "request"); + repository.reserve(request); + CanonicalInitialAdmissionOwnerProof beforeAbort = + requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); + if (beforeAbort.outcome() != CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + return beforeAbort; + } + PreparedExpectedClosed preparedOrigin = prepareExpectedClosed(request); + repository.abort(request, preparedOrigin, reason); + return requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); + } + + @Override + public CanonicalInitialAdmissionOwnerProof read(String targetNamespace, String requestId) { + return requireRead(targetNamespace, requestId); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical initial admission owner operation cannot enter from an ambient transaction"); + } + } + + private PreparedExpectedClosed prepareExpectedClosed(CanonicalInitialAdmissionRequest request) { + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + return null; + } + return pointerRepository.prepareExpectedClosedForRealm( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.expectedPriorPointerVersion(), + request.expectedCatalogRevision()); + } + + private CanonicalInitialAdmissionOwnerProof requireRead( + String targetNamespace, String requestId) { + return repository + .read(targetNamespace, requestId) + .orElseThrow( + () -> + new CanonicalInitialAdmissionRepository + .CanonicalInitialAdmissionReconciliationRequiredException( + "Initial-admission attempt has no durable owner result")); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java new file mode 100644 index 0000000000..8bbd9b58b6 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -0,0 +1,830 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +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.when; + +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof for the canonical first-OPEN owner transaction. + * + *

The direct V25 reservation/claim/association inserts below are test-only owner fixtures for + * exercising the migrated constraints. They are not a runtime fresh-tenant mapping producer. The + * World proof is also test data; production remains disabled until the real verifier and Account + * authorization redemption are composed. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalInitialAdmissionRepositoryIntegrationTest { + private static final String NAMESPACE = "canonical-initial-admission-it"; + private static final UUID TENANT = uuid(101); + private static final UUID SOURCE_OPERATION = uuid(102); + private static final UUID INTAKE_REQUEST = uuid(103); + private static final UUID CATALOG_REQUEST = uuid(104); + private static final UUID ACTOR = uuid(105); + private static final UUID GAME_INSTANCE_UUID = uuid(108); + private static final UUID CANONICAL_VERSION = uuid(109); + private static final UUID ASSOCIATION_OPERATION = uuid(110); + private static final String CONTROL_PLANE_REQUEST_ID = "canonical-start-instance-1"; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest preparationRequest = + preparationRequest(source, catalog); + AuthoredWorldLaunchDescriptorClient syntheticGameDesign = + syntheticGameDesignClient(preparationRequest, catalog, source); + GameSessionCanonicalLaunchPreparationService preparationService = + new GameSessionCanonicalLaunchPreparationService( + syntheticGameDesign, + fixture.catalogRepository, + fixture.sourceRepository, + fixture.preparationRepository, + fixture.transactionManager, + NAMESPACE); + CanonicalLaunchPreparationSnapshot preparation = preparationService.prepare(preparationRequest); + CompleteLaunchBindingEvidence completeBinding = + preparationService.readCompleteBinding(preparation); + + FreshGameSessionTenantAssociation tenantAssociation = + fixture.createTestOnlyFreshMappingAndRunningLaunch(source, completeBinding); + CanonicalInitialAdmissionRequest request = initialAdmissionRequest(catalog, completeBinding); + assertThat(tenantAssociation.legacyGameSessionTenantId()) + .isNotEqualTo(source.source().sourceGameRowId()); + assertThat(request.playableStateNamespaceId()).isEqualTo(catalog.playableStateNamespaceId()); + CanonicalInitialAdmissionWorldProof worldProof = testWorldProof(request); + + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(request); + return null; + }); + + CanonicalInitialAdmissionWorldProof changedProof = + new CanonicalInitialAdmissionWorldProof( + worldProof.initialAdmissionRequestId(), + worldProof.requestDigest(), + worldProof.targetNamespace(), + worldProof.canonicalTenantId(), + worldProof.worldSlug(), + worldProof.realmId(), + worldProof.playableStateNamespaceId(), + worldProof.playableStateScope(), + worldProof.canonicalGameInstanceId(), + worldProof.canonicalVersionId(), + worldProof.lifecycleState(), + worldProof.activeLifecycleEpoch(), + worldProof.originKind(), + worldProof.expectedCatalogRevision(), + worldProof.expectedPriorPointerVersion(), + worldProof.holdId(), + uuid(111), + worldProof.holdBindingDigest()); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.commit(request, changedProof, null); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match the exact initial admission request"); + assertThat( + fixture.initialAdmissionRepository.read(NAMESPACE, request.initialAdmissionRequestId())) + .map(CanonicalInitialAdmissionOwnerProof::outcome) + .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + assertThat( + Objects.requireNonNull( + fixture + .dsl + .fetchSingle( + "SELECT count(*) FROM gameplay_admission_pointer " + + "WHERE representation_version = 3") + .get(0, Long.class))) + .isZero(); + + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.commit(request, worldProof, null); + return null; + }); + + CanonicalInitialAdmissionOwnerProof committed = + fixture + .initialAdmissionRepository + .read(NAMESPACE, request.initialAdmissionRequestId()) + .orElseThrow(); + assertThat(committed.outcome()) + .isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(committed.canonicalTenantId()).isEqualTo(TENANT); + assertThat(committed.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_UUID); + assertThat(committed.canonicalVersionId()).isEqualTo(CANONICAL_VERSION); + assertThat(committed.committedPointerVersion()).isEqualTo(1L); + assertThat(committed.auditEventId()).isPositive(); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) + .isEqualTo(1); + + Record pointer = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT id, pointer_version, tenant_id, game_instance_id, " + + "canonical_tenant_id, realm_id, " + + "canonical_game_instance_id, canonical_version_id, initial_admission_request_id, " + + "admission_state, representation_version FROM gameplay_admission_pointer " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ?", + NAMESPACE, + TENANT, + request.realmId())); + assertThat(pointer.get("tenant_id", Long.class)) + .isEqualTo(tenantAssociation.legacyGameSessionTenantId()); + assertThat(pointer.get("canonical_tenant_id", UUID.class)).isEqualTo(TENANT); + assertThat(pointer.get("realm_id", UUID.class)).isEqualTo(request.realmId()); + assertThat(pointer.get("canonical_game_instance_id", UUID.class)).isEqualTo(GAME_INSTANCE_UUID); + assertThat(pointer.get("canonical_version_id", UUID.class)).isEqualTo(CANONICAL_VERSION); + assertThat(pointer.get("initial_admission_request_id", String.class)) + .isEqualTo(request.initialAdmissionRequestId()); + assertThat(pointer.get("admission_state", String.class)).isEqualTo("OPEN"); + assertThat(pointer.get("representation_version", Integer.class)).isEqualTo(3); + + Record audit = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT canonical_tenant_id, realm_id, canonical_game_instance_id, " + + "canonical_version_id, initial_admission_request_id, admission_state " + + "FROM gameplay_admission_pointer_event WHERE id = ?", + committed.auditEventId())); + assertThat(audit.get("canonical_tenant_id", UUID.class)).isEqualTo(TENANT); + assertThat(audit.get("realm_id", UUID.class)).isEqualTo(request.realmId()); + assertThat(audit.get("canonical_game_instance_id", UUID.class)).isEqualTo(GAME_INSTANCE_UUID); + assertThat(audit.get("canonical_version_id", UUID.class)).isEqualTo(CANONICAL_VERSION); + assertThat(audit.get("initial_admission_request_id", String.class)) + .isEqualTo(request.initialAdmissionRequestId()); + assertThat(audit.get("admission_state", String.class)).isEqualTo("OPEN"); + + CanonicalInitialAdmissionRequest replayRequest = + initialAdmissionRequest(catalog, completeBinding); + CanonicalInitialAdmissionWorldProof replayWorldProof = testWorldProof(replayRequest); + assertThat(replayRequest).isEqualTo(request); + assertThat(replayWorldProof).isEqualTo(worldProof); + int pointerRowsBeforeReplay = + fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer"))); + int auditRowsBeforeReplay = + fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event"))); + + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(replayRequest); + return null; + }); + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.commit(replayRequest, replayWorldProof, null); + return null; + }); + + CanonicalInitialAdmissionOwnerProof replayed = + fixture + .initialAdmissionRepository + .read(NAMESPACE, replayRequest.initialAdmissionRequestId()) + .orElseThrow(); + assertThat(replayed).isEqualTo(committed); + Record pointerAfterReplay = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT id, pointer_version, tenant_id, game_instance_id, canonical_tenant_id, " + + "realm_id, canonical_game_instance_id, canonical_version_id, " + + "initial_admission_request_id, admission_state, representation_version " + + "FROM gameplay_admission_pointer WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ?", + NAMESPACE, + TENANT, + replayRequest.realmId())); + assertThat(pointerAfterReplay.get("id", Long.class)).isEqualTo(pointer.get("id", Long.class)); + assertThat(pointerAfterReplay.get("pointer_version", Long.class)) + .isEqualTo(pointer.get("pointer_version", Long.class)); + assertThat(pointerAfterReplay.get("tenant_id", Long.class)) + .isEqualTo(pointer.get("tenant_id", Long.class)); + assertThat(pointerAfterReplay.get("game_instance_id", Long.class)) + .isEqualTo(pointer.get("game_instance_id", Long.class)); + assertThat(pointerAfterReplay.get("canonical_tenant_id", UUID.class)) + .isEqualTo(pointer.get("canonical_tenant_id", UUID.class)); + assertThat(pointerAfterReplay.get("realm_id", UUID.class)) + .isEqualTo(pointer.get("realm_id", UUID.class)); + assertThat(pointerAfterReplay.get("canonical_game_instance_id", UUID.class)) + .isEqualTo(pointer.get("canonical_game_instance_id", UUID.class)); + assertThat(pointerAfterReplay.get("canonical_version_id", UUID.class)) + .isEqualTo(pointer.get("canonical_version_id", UUID.class)); + assertThat(pointerAfterReplay.get("initial_admission_request_id", String.class)) + .isEqualTo(pointer.get("initial_admission_request_id", String.class)); + assertThat(pointerAfterReplay.get("admission_state", String.class)) + .isEqualTo(pointer.get("admission_state", String.class)); + assertThat(pointerAfterReplay.get("representation_version", Integer.class)) + .isEqualTo(pointer.get("representation_version", Integer.class)); + Record auditAfterReplay = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT canonical_tenant_id, realm_id, canonical_game_instance_id, " + + "canonical_version_id, initial_admission_request_id, admission_state " + + "FROM gameplay_admission_pointer_event WHERE id = ?", + replayed.auditEventId())); + assertThat(auditAfterReplay.get("canonical_tenant_id", UUID.class)) + .isEqualTo(audit.get("canonical_tenant_id", UUID.class)); + assertThat(auditAfterReplay.get("realm_id", UUID.class)) + .isEqualTo(audit.get("realm_id", UUID.class)); + assertThat(auditAfterReplay.get("canonical_game_instance_id", UUID.class)) + .isEqualTo(audit.get("canonical_game_instance_id", UUID.class)); + assertThat(auditAfterReplay.get("canonical_version_id", UUID.class)) + .isEqualTo(audit.get("canonical_version_id", UUID.class)); + assertThat(auditAfterReplay.get("initial_admission_request_id", String.class)) + .isEqualTo(audit.get("initial_admission_request_id", String.class)); + assertThat(auditAfterReplay.get("admission_state", String.class)) + .isEqualTo(audit.get("admission_state", String.class)); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isEqualTo(pointerRowsBeforeReplay); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) + .isEqualTo(auditRowsBeforeReplay); + + assertThatThrownBy( + () -> + fixture.dsl.execute( + "INSERT INTO gameplay_admission_pointer (" + + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm, catalog_revision) " + + "VALUES ('numeric-scope-guard-test', 'numeric-scope-guard-test', " + + "'Numeric Scope Guard', 'Numeric Scope Guard', ?, 1, 1, TRUE, FALSE, " + + "'SHARED', 'owner-mode', 'scope-guard-test', 'numeric-only guard', TRUE, 1)", + tenantAssociation.legacyGameSessionTenantId())) + .hasMessageContaining("Numeric-only tenant scope cannot use a fresh source-bound key"); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_admission_pointer")), + DSL.field(DSL.name("world_slug"), String.class).eq("numeric-scope-guard-test"))) + .isZero(); + + UUID mismatchedTenant = uuid(997); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "INSERT INTO gameplay_admission_pointer (" + + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "created_at, updated_at, public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state, canonical_game_instance_id, " + + "canonical_version_id, runtime_version_id, initial_admission_request_id, " + + "initial_admission_request_digest, initial_admission_origin_kind, " + + "initial_admission_prior_pointer_version, initial_admission_active_epoch, " + + "initial_admission_hold_id, initial_admission_hold_fence, " + + "initial_admission_hold_binding_digest) " + + "SELECT world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version + 1, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "created_at, updated_at, public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, ?, " + + "admission_state, canonical_game_instance_id, canonical_version_id, " + + "runtime_version_id, initial_admission_request_id, initial_admission_request_digest, " + + "initial_admission_origin_kind, initial_admission_prior_pointer_version, " + + "initial_admission_active_epoch, initial_admission_hold_id, " + + "initial_admission_hold_fence, initial_admission_hold_binding_digest " + + "FROM gameplay_admission_pointer WHERE id = ?", + mismatchedTenant, + pointer.get("id", Long.class))) + .hasMessageContaining( + "Canonical OPEN pointer requires exact catalog and launch owner evidence"); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_admission_pointer")), + DSL.field(DSL.name("representation_version"), Integer.class).eq(3))) + .isEqualTo(1); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_admission_pointer")), + DSL.field(DSL.name("canonical_tenant_id"), UUID.class).eq(mismatchedTenant))) + .isZero(); + } + + @Test + void exactDefinitivelyAbortedAttemptCannotBeReopenedByRetry() { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest preparationRequest = + preparationRequest(source, catalog); + AuthoredWorldLaunchDescriptorClient syntheticGameDesign = + syntheticGameDesignClient(preparationRequest, catalog, source); + GameSessionCanonicalLaunchPreparationService preparationService = + new GameSessionCanonicalLaunchPreparationService( + syntheticGameDesign, + fixture.catalogRepository, + fixture.sourceRepository, + fixture.preparationRepository, + fixture.transactionManager, + NAMESPACE); + CanonicalLaunchPreparationSnapshot preparation = preparationService.prepare(preparationRequest); + CompleteLaunchBindingEvidence completeBinding = + preparationService.readCompleteBinding(preparation); + fixture.createTestOnlyFreshMappingAndRunningLaunch(source, completeBinding); + CanonicalInitialAdmissionRequest request = initialAdmissionRequest(catalog, completeBinding); + // Synthetic World proof input exercises the GS owner fence; it is not live World evidence. + CanonicalInitialAdmissionWorldProof worldProof = testWorldProof(request); + + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(request); + return null; + }); + assertThat( + fixture.initialAdmissionRepository.read(NAMESPACE, request.initialAdmissionRequestId())) + .map(CanonicalInitialAdmissionOwnerProof::outcome) + .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + int pointerRowsBeforeAbort = + fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer"))); + int auditRowsBeforeAbort = + fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event"))); + assertThat(pointerRowsBeforeAbort).isZero(); + assertThat(auditRowsBeforeAbort).isZero(); + + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.abort(request, null, "World hold expired"); + return null; + }); + + CanonicalInitialAdmissionOwnerProof aborted = + fixture + .initialAdmissionRepository + .read(NAMESPACE, request.initialAdmissionRequestId()) + .orElseThrow(); + assertThat(aborted.provesAbort()).isTrue(); + assertThat(aborted.outcome()).isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + assertThat(aborted.committedPointerVersion()).isNull(); + assertThat(aborted.auditEventId()).isNull(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isEqualTo(pointerRowsBeforeAbort); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) + .isEqualTo(auditRowsBeforeAbort); + + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(request); + return null; + }); + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.commit(request, worldProof, null); + return null; + }); + + CanonicalInitialAdmissionOwnerProof afterRetry = + fixture + .initialAdmissionRepository + .read(NAMESPACE, request.initialAdmissionRequestId()) + .orElseThrow(); + assertThat(afterRetry).isEqualTo(aborted); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isEqualTo(pointerRowsBeforeAbort); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) + .isEqualTo(auditRowsBeforeAbort); + } + + private Fixture fixture() { + String schema = "gs_canonical_admission_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(dsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(dsl); + GameSessionCanonicalLaunchPreparationRepository preparationRepository = + new GameSessionCanonicalLaunchPreparationRepository(dsl, catalogRepository); + GameplayAdmissionPointerEventRepository eventRepository = + new GameplayAdmissionPointerEventRepository(dsl); + GameSessionCanonicalAdmissionPointerRepository pointerRepository = + new GameSessionCanonicalAdmissionPointerRepository(dsl, catalogRepository, eventRepository); + CanonicalGameInstanceLaunchAssociationRepository launchRepository = + new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + CanonicalInitialAdmissionRepository initialAdmissionRepository = + new CanonicalInitialAdmissionRepository( + dsl, catalogRepository, pointerRepository, launchRepository, eventRepository); + return new Fixture( + dsl, + transactionManager, + transactions, + sourceRepository, + catalogRepository, + preparationRepository, + launchRepository, + initialAdmissionRepository); + } + + private static AuthoredWorldSourceEvidence freshSource() { + String worldSlug = "violet-wilds"; + String tenantSlug = "tenant-canonical-admission"; + String displayName = "Violet Wilds"; + UUID registrationRequestId = uuid(112); + long sourceGameRowId = 821; + String sourceGameTenantKey = "gds-tenant-821"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, TENANT, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static CreateCanonicalLaunchPreparationRequest preparationRequest( + IntakeReceipt source, CanonicalRealmCatalogSnapshot catalog) { + return new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST_ID, + ACTOR, + NAMESPACE, + TENANT, + catalog.realmId(), + CATALOG_REQUEST, + catalog.catalogRevision(), + source.operationId(), + 404, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source) { + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request.descriptorRequest(catalog, source.source()), + "launch-descriptor-canonical-admission", + 72, + false, + null, + "{}", + "generation-1", + 3, + 73, + "published-bundle-73", + false, + null); + CompleteLaunchBindingEvidence binding = completeBinding(descriptor); + when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenReturn(descriptor); + when(client.get(any(GetRequest.class))).thenReturn(descriptor); + when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(binding); + return client; + } + + private static CompleteLaunchBindingEvidence completeBinding( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + String commitId = "publish-commit-canonical-admission"; + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + commitId, + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest("d") : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + CANONICAL_VERSION, + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish-canonical-admission", + commitId, + participants, + digest("b"), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } + + private static CanonicalInitialAdmissionRequest initialAdmissionRequest( + CanonicalRealmCatalogSnapshot catalog, CompleteLaunchBindingEvidence binding) { + String requestId = "canonical-first-open-" + catalog.realmId(); + long activeEpoch = 2L; + UUID canonicalVersionId = binding.releaseAttestation().canonicalVersionId(); + CanonicalInitialAdmissionRequest.OriginKind origin = + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER; + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + NAMESPACE, + TENANT, + catalog.worldSlug(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + "SHARED", + GAME_INSTANCE_UUID, + canonicalVersionId, + activeEpoch, + catalog.catalogRevision(), + origin, + null, + requestId); + return new CanonicalInitialAdmissionRequest( + NAMESPACE, + TENANT, + catalog.worldSlug(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + "SHARED", + GAME_INSTANCE_UUID, + canonicalVersionId, + activeEpoch, + catalog.catalogRevision(), + origin, + null, + requestId, + requestDigest, + uuid(113), + uuid(114), + digest("e")); + } + + private static CanonicalInitialAdmissionWorldProof testWorldProof( + CanonicalInitialAdmissionRequest request) { + return new CanonicalInitialAdmissionWorldProof( + request.initialAdmissionRequestId(), + request.requestDigest(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + "ACTIVE", + request.activeLifecycleEpoch(), + request.originKind(), + request.expectedCatalogRevision(), + request.expectedPriorPointerVersion(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest()); + } + + private static CreateCanonicalRealmCatalogRequest catalogRequest(IntakeReceipt source) { + return new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST, + NAMESPACE, + TENANT, + source.operationId(), + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + } + + private static String digest(String letter) { + return "sha256:" + letter.repeat(64); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + CanonicalInitialAdmissionRepository initialAdmissionRepository) { + IntakeReceipt registerSource() { + return Objects.requireNonNull( + transactions.execute(status -> sourceRepository.register(INTAKE_REQUEST, freshSource()))); + } + + CanonicalRealmCatalogSnapshot createCatalog(IntakeReceipt source) { + var prepared = catalogRepository.prepareInitialPublicProduction(catalogRequest(source)); + return Objects.requireNonNull( + transactions.execute( + status -> catalogRepository.createInitialPublicProduction(prepared))); + } + + FreshGameSessionTenantAssociation createTestOnlyFreshMappingAndRunningLaunch( + IntakeReceipt source, CompleteLaunchBindingEvidence binding) { + RuntimeTenantIdentityEvidence sourceIdentity = + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + source.source().registrationRequestId(), + TENANT, + source.source().sourceGameRowId(), + source.source().sourceGameTenantKey(), + source.source().provenanceKind()); + FreshGameSessionTenantAssociation association = + transactions.execute( + status -> { + Record reservation = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO game_session_tenant_scope_reservation " + + "(reservation_kind) VALUES ('FRESH_SOURCE_BOUND') " + + "RETURNING game_session_tenant_id")); + long allocatedTenantId = reservation.get("game_session_tenant_id", Long.class); + FreshGameSessionTenantAssociation allocatedAssociation = + new FreshGameSessionTenantAssociation( + ASSOCIATION_OPERATION, allocatedTenantId, sourceIdentity); + dsl.execute( + "INSERT INTO game_session_tenant_canonical_claim " + + "(target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, " + + "association_kind, reservation_kind, association_operation_id, " + + "association_request_id) " + + "VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", + NAMESPACE, + TENANT, + allocatedTenantId, + ASSOCIATION_OPERATION, + source.source().registrationRequestId()); + dsl.execute( + "INSERT INTO game_session_fresh_tenant_association " + + "(association_operation_id, target_namespace, association_request_id, " + + "source_schema_version, source_target_namespace, source_request_id, " + + "source_canonical_tenant_id, canonical_tenant_id, " + + "legacy_game_session_tenant_id, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, association_kind) " + + "VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', " + + "'FRESH_SOURCE_BOUND')", + ASSOCIATION_OPERATION, + NAMESPACE, + source.source().registrationRequestId(), + NAMESPACE, + source.source().registrationRequestId(), + TENANT, + TENANT, + allocatedTenantId, + source.source().sourceGameRowId(), + source.source().sourceGameTenantKey()); + Record instance = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO game_instances " + + "(tenant_id, runtime_version, game_template_id, " + + "launch_descriptor_id, version_id, release_bundle_id, " + + "generation_config_revision, version_state_epoch, " + + "owner_account_id, status, row_version, game_instance_uuid, " + + "run_owned_start_request_id, run_owned_start_request_digest, " + + "run_owned_start_published_release_bundle_ref, " + + "run_owned_start_preparing_epoch, run_owned_start_active_epoch) " + + "VALUES (?, '72', 404, ?, 72, 73, 'generation-1', 3, 77, " + + "'STARTING', 1, ?, ?, ?, ?, 1, 2) RETURNING id", + allocatedTenantId, + binding.descriptor().launchDescriptorId(), + GAME_INSTANCE_UUID, + CONTROL_PLANE_REQUEST_ID, + "c".repeat(64), + binding.descriptor().publishedReleaseBundleRef())); + long gameInstanceId = instance.get("id", Long.class); + launchRepository.capture(allocatedAssociation, gameInstanceId, binding); + dsl.execute( + "UPDATE game_instances SET status = 'RUNNING' " + + "WHERE tenant_id = ? AND id = ?", + allocatedTenantId, + gameInstanceId); + return allocatedAssociation; + }); + return Objects.requireNonNull(association, "test fixture tenant association"); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java new file mode 100644 index 0000000000..3ed81c54cf --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java @@ -0,0 +1,590 @@ +package integration.net.firedevops.firemud.gamesession.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.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +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.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +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.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real PostgreSQL source/catalog transactions and immutable preparation storage. Game Design's + * descriptor response is deliberately synthetic here; this is not transport or mTLS proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalLaunchPreparationServiceIntegrationTest { + private static final String NAMESPACE = "canonical-launch-it"; + private static final UUID TENANT = uuid(101); + private static final UUID SOURCE_OPERATION = uuid(102); + private static final UUID INTAKE_REQUEST = uuid(104); + private static final UUID CATALOG_REQUEST = uuid(105); + private static final UUID ACTOR = uuid(106); + private static final UUID REALM = uuid(107); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final long RETAINED_TENANT_ID = 917L; + private static final long RETAINED_GAME_INSTANCE_ID = 901L; + private static final UUID RETAINED_REALM_ID = uuid(108); + private static final UUID RETAINED_PLAYABLE_NAMESPACE_ID = uuid(109); + private static final UUID RETAINED_SHARED_NAMESPACE_ID = uuid(110); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void + commitsExactFreshSourceCatalogAndSyntheticDescriptorThenReplaysWithoutChangingRetainedRows() { + Fixture fixture = fixture(true, true); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + IntakeReceipt source = java.util.Objects.requireNonNull(fixture.preV24Source); + CanonicalRealmCatalogSnapshot catalog = java.util.Objects.requireNonNull(fixture.preV24Catalog); + assertThat( + fixture.sourceRepository.read( + source.operationId(), TENANT, source.source().worldSlug(), NAMESPACE)) + .contains(source); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .contains(catalog); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + AuthoredWorldLaunchDescriptorClient syntheticGameDesign = syntheticGameDesignClient(); + GameSessionCanonicalLaunchPreparationService service = fixture.service(syntheticGameDesign); + + CanonicalLaunchPreparationSnapshot first = service.prepare(request); + // A repeated call models recovery after the caller loses the first successful response. + CanonicalLaunchPreparationSnapshot retry = service.prepare(request); + + assertThat(first).isEqualTo(retry); + assertThat(first.operationId()).isNotEqualTo(NIL_UUID); + assertThat(first.catalogSnapshot()).isEqualTo(catalog); + assertThat(first.sourceIntakeReceipt()).isEqualTo(source); + first.launchDescriptorEvidence().requireValid(); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT game_instance_uuid FROM game_instances WHERE id = ?", + RETAINED_GAME_INSTANCE_ID) + .get("game_instance_uuid", UUID.class)) + .isNull(); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT representation_version, tenant_id, game_instance_id, realm_id, " + + "canonical_tenant_id, playable_state_namespace_id FROM gameplay_admission_pointer " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID)) + .satisfies( + row -> { + assertThat(row.get("representation_version", Integer.class)).isEqualTo(1); + assertThat(row.get("tenant_id", Long.class)).isEqualTo(RETAINED_TENANT_ID); + assertThat(row.get("game_instance_id", Long.class)).isEqualTo(501L); + assertThat(row.get("realm_id", UUID.class)).isEqualTo(RETAINED_REALM_ID); + assertThat(row.get("canonical_tenant_id", UUID.class)).isNull(); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_PLAYABLE_NAMESPACE_ID); + }); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM " + + "gameplay_tenant_shared_playable_state_namespace WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + verify(syntheticGameDesign, times(1)).resolve(any()); + verify(syntheticGameDesign, times(1)).get(any(GetRequest.class)); + } + + @Test + void ownerRollbackLeavesNoPartialPreparationAndImmutableRowsRejectMutation() { + Fixture fixture = fixture(false, false); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + IntakeReceipt source = fixture.registerFreshSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request, catalog, source); + + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> { + fixture.preparationRepository.persistPrepared( + request, catalog, source, descriptor); + throw new IllegalStateException("forced owner rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("forced owner rollback"); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + + CanonicalLaunchPreparationSnapshot committed = + fixture.service(syntheticGameDesignClient()).prepare(request); + assertThat( + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .contains(committed); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_canonical_launch_preparation " + + "SET receipt_digest = ? WHERE target_namespace = ?", + digest("f"), + NAMESPACE)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_launch_preparation " + + "WHERE target_namespace = ?", + NAMESPACE)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE game_session_canonical_launch_preparation")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThat( + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .contains(committed); + + // Simulate privileged storage corruption in this isolated test schema; normal update/delete + // paths remain blocked by the immutable trigger above. + fixture.transactions.execute( + status -> { + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_launch_preparation DISABLE TRIGGER " + + "game_session_canonical_launch_preparation_immutable"); + fixture.dsl.execute( + "UPDATE game_session_canonical_launch_preparation " + + "SET catalog_evidence_json = jsonb_set(catalog_evidence_json, " + + "'{realmDisplayName}', to_jsonb(CAST(? AS text))) " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + "Tampered Realm Display Name", + NAMESPACE, + request.controlPlaneRequestId()); + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_launch_preparation ENABLE TRIGGER " + + "game_session_canonical_launch_preparation_immutable"); + return null; + }); + assertThatThrownBy( + () -> + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .isInstanceOf( + GameSessionCanonicalLaunchPreparationRepository + .InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("stored identity and digests"); + } + + @Test + void concurrentExactPreparationsReturnOneImmutableOperation() throws Exception { + Fixture fixture = fixture(false, false); + IntakeReceipt source = fixture.registerFreshSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + CountDownLatch bothResolved = new CountDownLatch(2); + AuthoredWorldLaunchDescriptorClient concurrentGameDesign = + concurrentSyntheticGameDesignClient(bothResolved); + GameSessionCanonicalLaunchPreparationService service = fixture.service(concurrentGameDesign); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> service.prepare(request)); + Future second = + executor.submit(() -> service.prepare(request)); + + assertThat(bothResolved.await(15, TimeUnit.SECONDS)).isTrue(); + CanonicalLaunchPreparationSnapshot firstResult = first.get(15, TimeUnit.SECONDS); + CanonicalLaunchPreparationSnapshot secondResult = second.get(15, TimeUnit.SECONDS); + + assertThat(firstResult).isEqualTo(secondResult); + assertThat(firstResult.operationId()).isEqualTo(secondResult.operationId()); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isEqualTo(1); + verify(concurrentGameDesign, times(2)).resolve(any()); + verify(concurrentGameDesign, times(2)).get(any(GetRequest.class)); + } finally { + executor.shutdownNow(); + } + } + + private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient() { + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenAnswer( + invocation -> { + AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); + return syntheticDescriptor(request); + }); + when(client.get(any(GetRequest.class))) + .thenAnswer( + invocation -> { + GetRequest request = invocation.getArgument(0); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request.expectedRequest()); + assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + return descriptor; + }); + return client; + } + + private static AuthoredWorldLaunchDescriptorClient concurrentSyntheticGameDesignClient( + CountDownLatch bothResolved) { + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenAnswer( + invocation -> { + AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); + bothResolved.countDown(); + try { + if (!bothResolved.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent exact attempts did not both resolve"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent exact attempt was interrupted", exception); + } + return syntheticDescriptor(request); + }); + when(client.get(any(GetRequest.class))) + .thenAnswer( + invocation -> { + GetRequest request = invocation.getArgument(0); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request.expectedRequest()); + assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + return descriptor; + }); + return client; + } + + private static AuthoredWorldLaunchDescriptorEvidence syntheticDescriptor( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source) { + return syntheticDescriptor(request.descriptorRequest(catalog, source.source())); + } + + private static AuthoredWorldLaunchDescriptorEvidence syntheticDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "synthetic-descriptor-" + request.controlPlaneRequestId(), + 515, + false, + null, + "{}", + "generation-config-1", + 4, + 616, + "synthetic-published-release-616", + false, + null); + } + + private static CreateCanonicalLaunchPreparationRequest request( + IntakeReceipt source, CanonicalRealmCatalogSnapshot catalog) { + return new CreateCanonicalLaunchPreparationRequest( + "canonical-launch-it-" + catalog.realmId(), + ACTOR, + NAMESPACE, + TENANT, + catalog.realmId(), + catalog.creationRequestId(), + catalog.catalogRevision(), + source.operationId(), + 404, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private Fixture fixture( + boolean seedRetainedNumericRows, boolean seedCanonicalOwnerEvidenceBeforeV24) { + String schema = "gs_canonical_launch_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("11")) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + if (seedRetainedNumericRows) { + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status) " + + "VALUES (?, ?, ?, ?, ?)", + RETAINED_GAME_INSTANCE_ID, + RETAINED_TENANT_ID, + "retained-runtime", + 77L, + "RUNNING"); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + RETAINED_TENANT_ID, + RETAINED_SHARED_NAMESPACE_ID); + dsl.execute( + "INSERT INTO gameplay_admission_pointer " + + "(world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "legacy-world", + "Legacy World", + "legacy-realm", + "Legacy Realm", + RETAINED_TENANT_ID, + 501L, + 1L, + true, + false, + "SHARED", + "ALLOW_NEW", + "fixture", + "retained evidence", + true, + RETAINED_REALM_ID, + RETAINED_PLAYABLE_NAMESPACE_ID); + } + + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("23")) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext transactionalDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(transactionalDsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(transactionalDsl); + IntakeReceipt preV24Source = null; + CanonicalRealmCatalogSnapshot preV24Catalog = null; + if (seedCanonicalOwnerEvidenceBeforeV24) { + preV24Source = + java.util.Objects.requireNonNull( + transactions.execute( + status -> sourceRepository.register(INTAKE_REQUEST, freshSource()))); + CreateCanonicalRealmCatalogRequest catalogRequest = + new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST, + NAMESPACE, + TENANT, + preV24Source.operationId(), + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var preparedCatalog = catalogRepository.prepareInitialPublicProduction(catalogRequest); + preV24Catalog = + java.util.Objects.requireNonNull( + transactions.execute( + status -> catalogRepository.createInitialPublicProduction(preparedCatalog))); + } + + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + GameSessionCanonicalLaunchPreparationRepository preparationRepository = + new GameSessionCanonicalLaunchPreparationRepository(transactionalDsl, catalogRepository); + return new Fixture( + transactionalDsl, + sourceRepository, + catalogRepository, + preparationRepository, + transactionManager, + transactions, + preV24Source, + preV24Catalog); + } + + private static AuthoredWorldSourceEvidence freshSource() { + String worldSlug = "violet-wilds"; + String tenantSlug = "tenant-" + TENANT.toString().substring(0, 8); + String displayName = "Violet Wilds"; + UUID registrationRequestId = uuid(111); + long sourceGameRowId = 821; + String sourceGameTenantKey = "fresh-source-821"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, TENANT, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static Record requiredRecord(DSLContext dsl, String sql, Object... bindings) { + return java.util.Objects.requireNonNull( + dsl.fetchOne(sql, bindings), "Expected owner evidence row is missing"); + } + + private static String digest(String letter) { + return "sha256:" + letter.repeat(64); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + DSLContext dsl, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + IntakeReceipt preV24Source, + CanonicalRealmCatalogSnapshot preV24Catalog) { + IntakeReceipt registerFreshSource() { + IntakeReceipt receipt = + transactions.execute(status -> sourceRepository.register(INTAKE_REQUEST, freshSource())); + return java.util.Objects.requireNonNull(receipt); + } + + CanonicalRealmCatalogSnapshot createCatalog(IntakeReceipt source) { + CreateCanonicalRealmCatalogRequest request = + new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST, + NAMESPACE, + TENANT, + source.operationId(), + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var prepared = catalogRepository.prepareInitialPublicProduction(request); + CanonicalRealmCatalogSnapshot created = + transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); + return java.util.Objects.requireNonNull(created); + } + + GameSessionCanonicalLaunchPreparationService service( + AuthoredWorldLaunchDescriptorClient descriptorClient) { + return new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java new file mode 100644 index 0000000000..b03150ae8b --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java @@ -0,0 +1,405 @@ +package integration.net.firedevops.firemud.gamesession.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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClient; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** PostgreSQL proof of coordinator ordering, exact retry, ambiguity, and stale-claim rejection. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "world-runtime"; + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String OPAQUE_REFERENCE = "A".repeat(43); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void postgresClaimIsCommittedBeforeAccountAndExactRetryDoesNotRedeemAgain() throws Exception { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("coordinator-committed-retry"); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + AtomicInteger accountCalls = new AtomicInteger(); + when(redemptionClient.redeem(any(), eq(OPAQUE_REFERENCE), any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(fixture.attemptCount()) + .as("the claim must be visible from an independent PostgreSQL connection") + .isEqualTo(1); + accountCalls.incrementAndGet(); + StartSessionPostAuthorizationExecutionTuple deliveredTuple = + invocation.getArgument(0); + AttemptClaim claim = invocation.getArgument(2); + return new StartSessionOperatorRedemptionClient.RedemptionResult( + claim, projection(deliveredTuple), false); + }); + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + coordinator(fixture, redemptionClient); + + var first = withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(first.progress()) + .isEqualTo( + GameSessionStartSessionOperatorAuthorizationCoordinator.Progress + .ACCOUNT_PROJECTION_ATTACHED); + assertThat(fixture.attemptCount()).isEqualTo(1); + AttemptSnapshot persisted = fixture.reserve(tuple).snapshot(); + assertThat(persisted.accountRedemptionProjection()) + .containsExactly(projection(tuple).canonicalBytes()); + + var retry = withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(retry.progress()) + .isEqualTo(GameSessionStartSessionOperatorAuthorizationCoordinator.Progress.EXACT_REPLAY); + assertThat(retry.claim()).isEmpty(); + assertThat(retry.snapshot().ownerAttemptId()).isEqualTo(first.snapshot().ownerAttemptId()); + assertThat(accountCalls.get()).isEqualTo(1); + verify(redemptionClient, times(1)).redeem(eq(tuple), eq(OPAQUE_REFERENCE), any()); + assertThat(fixture.attemptCount()).isEqualTo(1); + } + + @Test + void ambiguousAccountTransportStaysPendingAndExactRetryDoesNotCallAccountAgain() + throws Exception { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("coordinator-ambiguous"); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + AtomicInteger accountCalls = new AtomicInteger(); + when(redemptionClient.redeem(any(), eq(OPAQUE_REFERENCE), any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(fixture.attemptCount()).isEqualTo(1); + accountCalls.incrementAndGet(); + throw new StatusRuntimeException(Status.DEADLINE_EXCEEDED); + }); + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + coordinator(fixture, redemptionClient); + + var first = withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(first.progress()) + .isEqualTo( + GameSessionStartSessionOperatorAuthorizationCoordinator.Progress + .ACCOUNT_OUTCOME_AMBIGUOUS); + assertThat(first.snapshot().accountRedemptionProjection()).isNull(); + assertThat(fixture.attemptCount()).isEqualTo(1); + AttemptSnapshot persisted = fixture.reserve(tuple).snapshot(); + assertThat(persisted.accountRedemptionProjection()).isNull(); + + var retry = withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(retry.progress()) + .isEqualTo(GameSessionStartSessionOperatorAuthorizationCoordinator.Progress.EXACT_REPLAY); + assertThat(retry.snapshot().accountRedemptionProjection()).isNull(); + assertThat(accountCalls.get()).isEqualTo(1); + verify(redemptionClient, times(1)).redeem(eq(tuple), eq(OPAQUE_REFERENCE), any()); + assertThat(fixture.attemptCount()).isEqualTo(1); + } + + @Test + void expiredRealPostgresClaimCannotPersistTheReturnedAccountProjection() throws Exception { + Duration lease = Duration.ofSeconds(2); + Fixture fixture = fixture(lease); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("coordinator-stale-claim"); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + AtomicInteger accountCalls = new AtomicInteger(); + when(redemptionClient.redeem(any(), eq(OPAQUE_REFERENCE), any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(fixture.attemptCount()).isEqualTo(1); + accountCalls.incrementAndGet(); + StartSessionPostAuthorizationExecutionTuple deliveredTuple = + invocation.getArgument(0); + AttemptClaim claim = invocation.getArgument(2); + fixture.awaitClaimLeaseExpired(claim); + return new StartSessionOperatorRedemptionClient.RedemptionResult( + claim, projection(deliveredTuple), false); + }); + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + coordinator(fixture, redemptionClient); + + assertThatThrownBy(() -> withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired"); + + assertThat(accountCalls.get()).isEqualTo(1); + AttemptSnapshot persisted = fixture.reserve(tuple).snapshot(); + assertThat(persisted.accountRedemptionProjection()).isNull(); + assertThat(fixture.attemptCount()).isEqualTo(1); + + var retry = withLoggingPeer(() -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + assertThat(retry.progress()) + .isEqualTo(GameSessionStartSessionOperatorAuthorizationCoordinator.Progress.EXACT_REPLAY); + assertThat(retry.snapshot().accountRedemptionProjection()).isNull(); + assertThat(accountCalls.get()).isEqualTo(1); + verify(redemptionClient, times(1)).redeem(eq(tuple), eq(OPAQUE_REFERENCE), any()); + } + + private static GameSessionStartSessionOperatorAuthorizationCoordinator coordinator( + Fixture fixture, StartSessionOperatorRedemptionClient redemptionClient) { + return new GameSessionStartSessionOperatorAuthorizationCoordinator( + fixture.repository, redemptionClient, fixture.transactionManager, NAMESPACE); + } + + private static StartSessionOperatorRedemptionClient mockRedemptionClient() { + return mock(StartSessionOperatorRedemptionClient.class); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String requestId) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Game Session operator authorization coordinator PostgreSQL proof"); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + WORKLOAD, + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException( + "could not create canonical test authority bundle", exception); + } + } + + private static AccountRedemptionProjection projection( + StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())); + } + + private static GrpcPeerIdentity peer() { + return GrpcPeerIdentity.parseUri(WORKLOAD).orElseThrow(); + } + + private static T withLoggingPeer(ThrowingSupplier work) throws Exception { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer()); + Context previous = context.attach(); + try { + return work.get(); + } finally { + context.detach(previous); + } + } + + private static Fixture fixture(Duration claimLease) { + String schema = "gs_operator_coordinator_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + dsl, + transactionManager, + transactions, + new GameSessionStartSessionOperatorAttemptRepository(dsl, claimLease)); + } + + @FunctionalInterface + private interface ThrowingSupplier { + T get() throws Exception; + } + + private record Fixture( + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + GameSessionStartSessionOperatorAttemptRepository repository) { + ReservationResult reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + return Objects.requireNonNull( + transactions.execute(status -> repository.reserve(tuple)), + "StartSession owner-attempt reservation result"); + } + + int attemptCount() { + return dsl.fetchCount(DSL.table(DSL.name("game_session_start_session_operator_attempt"))); + } + + void awaitClaimLeaseExpired(AttemptClaim claim) throws InterruptedException { + long deadlineNanos = System.nanoTime() + Duration.ofSeconds(10).toNanos(); + while (!claimLeaseExpired(claim) && System.nanoTime() < deadlineNanos) { + Thread.sleep(10L); + } + assertThat(claimLeaseExpired(claim)) + .as("PostgreSQL must report the exact original owner claim lease expired") + .isTrue(); + } + + private boolean claimLeaseExpired(AttemptClaim claim) { + Record validity = + dsl.fetchOne( + "SELECT lease_expires_at <= clock_timestamp() AS expired " + + "FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ? " + + "AND owner_attempt_id = ? AND owner_mutation_id = ? " + + "AND claim_owner_id = ? AND owner_fence = ?", + claim.targetNamespace(), + claim.controlPlaneRequestId(), + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.claimOwnerId(), + claim.ownerFence()); + return validity != null && Boolean.TRUE.equals(validity.get("expired", Boolean.class)); + } + } +} diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java new file mode 100644 index 0000000000..135c86ee96 --- /dev/null +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java @@ -0,0 +1,234 @@ +package net.firedevops.firemud.gamesession.repository; + +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 net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import org.junit.jupiter.api.Test; + +class CanonicalCurrentOpenPointerSnapshotDigestTest { + @Test + void canonicalEncodingMatchesFixedVectorIncludingLongUtf8AndNullOriginVersion() { + var projection = new Fixture().projection(); + + assertThat(projection.initialAdmissionRequestId()).hasSize(120); + assertThat(CanonicalCurrentOpenPointerSnapshotDigest.digest(projection)) + .isEqualTo("7bb3cb77966978f60e81ebd7189bae2ac40ead75fa6f496f4bf87d0366cf3cc2"); + } + + @Test + void canonicalDecimalCounterEncodingSupportsMaximumPositiveLongValues() { + Fixture fixture = new Fixture(); + fixture.catalogRevision = Long.MAX_VALUE; + fixture.pointerVersion = Long.MAX_VALUE; + fixture.activeWorldEpoch = Long.MAX_VALUE; + fixture.auditEventId = Long.MAX_VALUE; + fixture.originKind = OriginKind.EXPECT_CLOSED; + fixture.expectedPriorPointerVersion = Long.MAX_VALUE; + + assertThat(CanonicalCurrentOpenPointerSnapshotDigest.digest(fixture.projection())) + .isEqualTo("02703fae1556ed0b11d9d580e9d02b916f2e13cab623d5e3d73dad8cd9ead28f"); + } + + @Test + void changesToCurrentPointerTupleOrTerminalOwnerEvidenceChangeDigest() { + String base = digest(new Fixture()); + + Fixture changedPointerVersion = new Fixture(); + changedPointerVersion.pointerVersion = 74L; + assertThat(digest(changedPointerVersion)).isNotEqualTo(base); + + Fixture changedCatalogRevision = new Fixture(); + changedCatalogRevision.catalogRevision = 42L; + assertThat(digest(changedCatalogRevision)).isNotEqualTo(base); + + Fixture changedRequestIdentity = new Fixture(); + changedRequestIdentity.initialAdmissionRequestId = "first-open-operation-18"; + assertThat(digest(changedRequestIdentity)).isNotEqualTo(base); + + Fixture changedRequestDigest = new Fixture(); + changedRequestDigest.initialAdmissionRequestDigest = "b".repeat(64); + assertThat(digest(changedRequestDigest)).isNotEqualTo(base); + + Fixture changedHoldFence = new Fixture(); + changedHoldFence.holdFence = uuid("99999999-9999-4999-8999-999999999999"); + assertThat(digest(changedHoldFence)).isNotEqualTo(base); + + Fixture changedHoldDigest = new Fixture(); + changedHoldDigest.holdBindingDigest = "sha256:" + "d".repeat(64); + assertThat(digest(changedHoldDigest)).isNotEqualTo(base); + + Fixture changedOwnerProof = new Fixture(); + changedOwnerProof.ownerProofDigest = "sha256:" + "e".repeat(64); + assertThat(digest(changedOwnerProof)).isNotEqualTo(base); + + Fixture changedAudit = new Fixture(); + changedAudit.auditEventId = 28L; + assertThat(digest(changedAudit)).isNotEqualTo(base); + + Fixture changedTerminalTime = new Fixture(); + changedTerminalTime.terminalAt = Instant.parse("2026-10-07T00:00:00.000001Z"); + assertThat(digest(changedTerminalTime)).isNotEqualTo(base); + } + + @Test + void rejectsNoncurrentFlagsInvalidSelectorsAndMalformedDigests() { + Fixture hidden = new Fixture(); + hidden.visible = false; + assertInvalid(hidden); + + Fixture privateRealm = new Fixture(); + privateRealm.publicProductionRealm = false; + assertInvalid(privateRealm); + + Fixture isolatedRealm = new Fixture(); + isolatedRealm.playableStateScope = "ISOLATED"; + assertInvalid(isolatedRealm); + + Fixture closedPointer = new Fixture(); + closedPointer.admissionState = "CLOSED"; + assertInvalid(closedPointer); + + Fixture changedSelector = new Fixture(); + changedSelector.worldSlug = "not a canonical slug"; + assertInvalid(changedSelector); + + Fixture nonpositivePointer = new Fixture(); + nonpositivePointer.pointerVersion = 0L; + assertInvalid(nonpositivePointer); + + Fixture nonpositiveCatalog = new Fixture(); + nonpositiveCatalog.catalogRevision = 0L; + assertInvalid(nonpositiveCatalog); + + Fixture nonpositiveEpoch = new Fixture(); + nonpositiveEpoch.activeWorldEpoch = 0L; + assertInvalid(nonpositiveEpoch); + + Fixture malformedRequestDigest = new Fixture(); + malformedRequestDigest.initialAdmissionRequestDigest = "A".repeat(64); + assertInvalid(malformedRequestDigest); + + Fixture malformedHoldDigest = new Fixture(); + malformedHoldDigest.holdBindingDigest = "sha256:" + "G".repeat(64); + assertInvalid(malformedHoldDigest); + + Fixture requiresCharacterSelection = new Fixture(); + requiresCharacterSelection.requiresCharacterSelection = true; + assertInvalid(requiresCharacterSelection); + + Fixture preparedVersionUpgrade = new Fixture(); + preparedVersionUpgrade.preparedVersionUpgradeId = "prepared-upgrade"; + assertInvalid(preparedVersionUpgrade); + + Fixture invalidNullableOrigin = new Fixture(); + invalidNullableOrigin.expectedPriorPointerVersion = 1L; + assertInvalid(invalidNullableOrigin); + + Fixture invalidUtf16 = new Fixture(); + invalidUtf16.worldDisplayName = "bad\uD800"; + assertInvalid(invalidUtf16); + } + + @Test + void nullablePriorVersionHasAClosedOriginRepresentation() { + Fixture noPrior = new Fixture(); + assertThat(noPrior.expectedPriorPointerVersion).isNull(); + String noPriorDigest = digest(noPrior); + + Fixture expectedClosed = new Fixture(); + expectedClosed.originKind = OriginKind.EXPECT_CLOSED; + expectedClosed.expectedPriorPointerVersion = 1L; + assertThat(digest(expectedClosed)).isNotEqualTo(noPriorDigest); + + expectedClosed.expectedPriorPointerVersion = null; + assertInvalid(expectedClosed); + } + + private static String digest(Fixture fixture) { + return CanonicalCurrentOpenPointerSnapshotDigest.digest(fixture.projection()); + } + + private static void assertInvalid(Fixture fixture) { + assertThatThrownBy(() -> fixture.projection()).isInstanceOf(IllegalArgumentException.class); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Fixture { + int representationVersion = 3; + String targetNamespace = "gameplay"; + UUID canonicalTenantId = uuid("11111111-1111-4111-8111-111111111111"); + String worldSlug = "demo-world"; + String worldDisplayName = "Demo Ω World"; + UUID realmId = uuid("22222222-2222-4222-8222-222222222222"); + String realmSlug = "main"; + String realmDisplayName = "Production — Main"; + UUID playableStateNamespaceId = uuid("33333333-3333-4333-8333-333333333333"); + String playableStateScope = "SHARED"; + long catalogRevision = 41L; + long pointerVersion = 73L; + String admissionState = "OPEN"; + boolean visible = true; + boolean publicProductionRealm = true; + Boolean requiresCharacterSelection; + String characterCreationPolicy = "ALLOW_NEW"; + UUID canonicalGameInstanceId = uuid("44444444-4444-4444-8444-444444444444"); + UUID canonicalVersionId = uuid("55555555-5555-4555-8555-555555555555"); + String initialAdmissionRequestId = "request-" + "x".repeat(112); + String initialAdmissionRequestDigest = "a".repeat(64); + OriginKind originKind = OriginKind.NO_PRIOR_POINTER; + Long expectedPriorPointerVersion; + long activeWorldEpoch = 82L; + UUID holdId = uuid("77777777-7777-4777-8777-777777777777"); + UUID holdFence = uuid("88888888-8888-4888-8888-888888888888"); + String holdBindingDigest = "sha256:" + "c".repeat(64); + String lastUpdatedBy = "game-session-canonical-initial-admission"; + String lastUpdateReason = "World-held initial admission"; + String preparedVersionUpgradeId; + String ownerProofDigest = "sha256:" + "f".repeat(64); + long auditEventId = 27L; + Instant terminalAt = Instant.parse("2026-10-07T00:00:00Z"); + + CanonicalCurrentOpenPointerSnapshotDigest.Projection projection() { + return new CanonicalCurrentOpenPointerSnapshotDigest.Projection( + representationVersion, + targetNamespace, + canonicalTenantId, + worldSlug, + worldDisplayName, + realmId, + realmSlug, + realmDisplayName, + playableStateNamespaceId, + playableStateScope, + catalogRevision, + pointerVersion, + admissionState, + visible, + publicProductionRealm, + requiresCharacterSelection, + characterCreationPolicy, + canonicalGameInstanceId, + canonicalVersionId, + initialAdmissionRequestId, + initialAdmissionRequestDigest, + originKind, + expectedPriorPointerVersion, + activeWorldEpoch, + holdId, + holdFence, + holdBindingDigest, + lastUpdatedBy, + lastUpdateReason, + preparedVersionUpgradeId, + ownerProofDigest, + auditEventId, + terminalAt); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java new file mode 100644 index 0000000000..a70856d0c2 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java @@ -0,0 +1,415 @@ +package net.firedevops.firemud.gamesession.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.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.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +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.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionOperatorRedemptionClientTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID OWNER_ATTEMPT = UUID.fromString("69116466-a576-4fa6-9e11-4c0c6b2a92f0"); + private static final UUID OWNER_MUTATION = + UUID.fromString("89da7d84-12f5-4cf8-b69b-30ba8eb115a4"); + private static final UUID CLAIM_OWNER = UUID.fromString("31f85ac3-e621-4c38-a207-0e5aab116d34"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "world-runtime"; + private static final String REQUEST_ID = "redemption-client-request"; + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String OPAQUE_REFERENCE = "A".repeat(43); + private static final Clock CURRENT_CLOCK = + Clock.fixed(Instant.parse("2026-10-09T00:00:00Z"), ZoneOffset.UTC); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void sendsExactPreTupleReservationAndActualGameSessionAttemptClaimOnce() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + AttemptClaim claim = claim(REQUEST_ID); + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class))) + .thenReturn(validResponse(tuple)); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + + StartSessionOperatorRedemptionClient.RedemptionResult result = + client.redeem(tuple, OPAQUE_REFERENCE, claim); + + var requestCaptor = + org.mockito.ArgumentCaptor.forClass(RedeemOperatorAuthorizationRequest.class); + verify(stub, times(1)).redeemOperatorAuthorization(requestCaptor.capture()); + RedeemOperatorAuthorizationRequest request = requestCaptor.getValue(); + assertThat(request.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly( + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(request.getOperatorAuthorizationReference()).isEqualTo(OPAQUE_REFERENCE); + assertThat(request.getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(request.getReservationOwnerId()).isEqualTo(RESERVATION_OWNER.toString()); + assertThat(request.getReservationClaimFence()).isEqualTo(19L); + assertThat(request.getOwnerAttemptId()).isEqualTo(OWNER_ATTEMPT.toString()); + assertThat(request.getOwnerFence()).isEqualTo(37L); + assertThat(result.gameSessionClaim()).isEqualTo(claim); + assertThat(result.accountReplay()).isFalse(); + AccountRedemptionProjection projection = result.projection(); + assertThat(projection.authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(projection.authorityEvidenceBundleBytes()) + .containsExactly(tuple.authorityEvidenceBundleBytes()); + assertThat(projection.issuanceOperationId()).isEqualTo(ISSUANCE_ID); + assertThat(projection.issuanceFence()).isEqualTo(23L); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsMismatchedClaimAndExpiredAuthorityBeforeCallingAccount() throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + + assertThatThrownBy( + () -> + client.redeem( + tuple, + OPAQUE_REFERENCE, + new AttemptClaim( + "another-namespace", + REQUEST_ID, + OWNER_ATTEMPT, + OWNER_MUTATION, + CLAIM_OWNER, + 37L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("claim differs"); + + StartSessionPostAuthorizationExecutionTuple expired = + tuple(REQUEST_ID, "2026-10-09T00:00:00Z", "2026-10-09T00:00:30Z"); + StartSessionOperatorRedemptionClient expiredClient = + newClient(stub, Clock.fixed(Instant.parse("2026-10-09T00:01:00Z"), ZoneOffset.UTC)); + assertThatThrownBy(() -> expiredClient.redeem(expired, OPAQUE_REFERENCE, claim(REQUEST_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("expired"); + verifyNoInteractions(stub); + } + + @Test + void rejectsMalformedMissingUnknownAndSubstitutedAccountProjectionFields() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + assertRejected(tuple, RedeemOperatorAuthorizationResponse.getDefaultInstance()); + + assertRejected( + tuple, + validResponse(tuple).toBuilder() + .setAuthorizationReferenceFingerprint("arfp/v1/other/" + "c".repeat(64)) + .build()); + assertRejected( + tuple, validResponse(tuple).toBuilder().setIssuanceOperationId("not-a-uuid").build()); + assertRejected(tuple, validResponse(tuple).toBuilder().setIssuanceFence(24L).build()); + assertRejected( + tuple, + validResponse(tuple).toBuilder() + .setAuthorityEvidenceBundle( + ByteString.copyFrom( + bundle( + tuple.preAuthorizationTuple(), + "18", + "2026-10-09T00:00:00Z", + "2026-10-09T00:05:00Z"))) + .build()); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + assertRejected(tuple, validResponse(tuple).toBuilder().setUnknownFields(unknown).build()); + } + + @Test + void letsRedemptionTimeoutRemainAmbiguousWithoutAutomaticRetryOrTerminalization() { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + StatusRuntimeException timeout = + new StatusRuntimeException(Status.DEADLINE_EXCEEDED.withDescription("ambiguous response")); + when(stub.redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class))) + .thenThrow(timeout); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + + assertThatThrownBy(() -> client.redeem(tuple(REQUEST_ID), OPAQUE_REFERENCE, claim(REQUEST_ID))) + .isSameAs(timeout); + + verify(stub, times(1)) + .redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class)); + } + + @Test + void refusesPlaintextOrMissingMutualTlsCredentialsAndDoesNotInitializeByConstruction() { + CommonGrpcClientProperties plaintext = tlsProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new StartSessionOperatorRedemptionClient( + new ServiceEndpointsProperties(), + plaintext, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + CURRENT_CLOCK)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mutual TLS"); + + CommonGrpcClientProperties missingIdentity = new CommonGrpcClientProperties(); + missingIdentity.setCaCert("ca.pem"); + assertThatThrownBy( + () -> + new StartSessionOperatorRedemptionClient( + new ServiceEndpointsProperties(), + missingIdentity, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + CURRENT_CLOCK)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mutual TLS"); + + StartSessionOperatorRedemptionClient uninitialized = newClient(null, CURRENT_CLOCK); + assertThatThrownBy( + () -> uninitialized.redeem(tuple(REQUEST_ID), OPAQUE_REFERENCE, claim(REQUEST_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("explicitly initialized"); + } + + private static void assertRejected( + StartSessionPostAuthorizationExecutionTuple tuple, + RedeemOperatorAuthorizationResponse response) + throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class))) + .thenReturn(response); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + assertThatThrownBy(() -> client.redeem(tuple, OPAQUE_REFERENCE, claim(REQUEST_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("malformed or tuple-substituted"); + verify(stub, times(1)) + .redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class)); + } + + private static StartSessionOperatorRedemptionClient newClient( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub, + Clock clock) { + StartSessionOperatorRedemptionClient client = + new StartSessionOperatorRedemptionClient( + new ServiceEndpointsProperties(), + tlsProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + clock); + if (stub != null) { + setStub(client, stub); + } + return client; + } + + private static CommonGrpcClientProperties tlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("client-chain.pem"); + tls.setPrivateKey("client-key.pem"); + tls.setCaCert("account-ca.pem"); + tls.setPlaintext(false); + return tls; + } + + private static void setStub( + StartSessionOperatorRedemptionClient client, + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub) { + try { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } catch (ReflectiveOperationException exception) { + throw new AssertionError(exception); + } + } + + private static AttemptClaim claim(String requestId) { + return new AttemptClaim(NAMESPACE, requestId, OWNER_ATTEMPT, OWNER_MUTATION, CLAIM_OWNER, 37L); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String requestId) { + return tuple(requestId, "2026-10-09T00:00:00Z", "2026-10-09T00:05:00Z"); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, String evaluatedAt, String expiresAt) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Game Session Account redemption client contract"); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + WORKLOAD, + FINGERPRINT, + RESERVATION_OWNER, + 19L, + bundle(pre, "17", evaluatedAt, expiresAt), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static RedeemOperatorAuthorizationResponse validResponse( + StartSessionPostAuthorizationExecutionTuple tuple) { + return RedeemOperatorAuthorizationResponse.newBuilder() + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setAuthorityEvidenceBundle(ByteString.copyFrom(tuple.authorityEvidenceBundleBytes())) + .setIssuanceOperationId(ISSUANCE_ID.toString()) + .setIssuanceFence(23L) + .setReplay(false) + .build(); + } + + private static byte[] bundle( + StartSessionPreAuthorizationReservationTuple tuple, + String sourceVersion, + String evaluatedAt, + String expiresAt) { + String tenantId = TENANT.toString(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + sourceVersion, + "projectionStatus", + "CURRENT", + "evaluatedAt", + evaluatedAt, + "expiresAt", + expiresAt); + Map identity = + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException(exception); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java new file mode 100644 index 0000000000..e501ca164b --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java @@ -0,0 +1,232 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalClosedAdmissionPointerRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.junit.jupiter.api.Test; + +class GameSessionCanonicalAdmissionPointerRepositoryTest { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String TARGET_NAMESPACE = "canonical-closed-pointer-test"; + + @Test + void requestAndReceiptDigestsMatchFixedOrderUtf8GoldenVectors() { + CreateCanonicalClosedAdmissionPointerRequest request = request("Café 🐉", "close 東京"); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + String requestDigest = + GameSessionCanonicalAdmissionPointerRepository.requestDigest(request, catalog); + + assertThat(requestDigest) + .isEqualTo("sha256:0dc3926970e3d5be36349ff3fe259869fed779f3429b767e2e20ece407313d24"); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.requestDigest( + request("Café 🐲", "close 東京"), catalog)) + .isNotEqualTo(requestDigest); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, + catalog, + requestDigest, + 123L, + Instant.parse("2026-10-03T00:00:00.123456Z"))) + .isEqualTo("sha256:5d465f6eec3f08d0de06c5562ba60d2bd44d335c41f82355c4adc158d5806286"); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, + catalog, + requestDigest, + 124L, + Instant.parse("2026-10-03T00:00:00.123456Z"))) + .isNotEqualTo("sha256:5d465f6eec3f08d0de06c5562ba60d2bd44d335c41f82355c4adc158d5806286"); + } + + @Test + void requestRejectsNilIdentityAndNonCanonicalTargetNamespace() { + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + NIL_UUID, TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), "Canonical_Closed", uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 0L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("catalogRevision must be positive"); + } + + @Test + void requestRejectsMalformedOrUnboundedAuditText() { + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), + TARGET_NAMESPACE, + uuid(2), + uuid(3), + uuid(4), + 1L, + "bad" + (char) 0xD800, + "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bounded and nonblank"); + } + + @Test + void expectedClosedVersionCheckRequiresTheExactInitialPointerAndCatalogTuple() { + CreateCanonicalClosedAdmissionPointerRequest request = request("origin actor", "origin reason"); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + String requestDigest = + GameSessionCanonicalAdmissionPointerRepository.requestDigest(request, catalog); + Instant updatedAt = Instant.parse("2026-10-03T00:00:00.123456Z"); + CanonicalClosedAdmissionPointerSnapshot origin = + new CanonicalClosedAdmissionPointerSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + 1L, + catalog.catalogRevision(), + "CLOSED", + null, + request.requestId(), + requestDigest, + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, catalog, requestDigest, 123L, updatedAt), + request.actorPrincipal(), + request.reason(), + 123L, + updatedAt, + catalog); + + assertThatCode( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 1L, 1L)) + .doesNotThrowAnyException(); + assertThatThrownBy( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 2L, 1L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("versions do not match"); + assertThatThrownBy( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 1L, 2L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("versions do not match"); + } + + private static CreateCanonicalClosedAdmissionPointerRequest request( + String actorPrincipal, String reason) { + return new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, actorPrincipal, reason); + } + + private static CanonicalRealmCatalogSnapshot catalogSnapshot() { + UUID tenantId = uuid(2); + UUID registrationRequestId = uuid(10); + UUID sourceOperationId = uuid(11); + String tenantSlug = "unit-tenant"; + String worldSlug = "authored-world"; + String worldDisplayName = "Authored World"; + String sourceGameTenantKey = "gds-unit-tenant"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + TARGET_NAMESPACE, + registrationRequestId, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + TARGET_NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceGameTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + TARGET_NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceGameTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + UUID intakeRequestId = uuid(12); + String intakeRequestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, source); + IntakeReceipt sourceReceipt = + new IntakeReceipt( + uuid(13), + intakeRequestId, + intakeRequestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + uuid(13), intakeRequestDigest, source.evidenceDigest())); + return new CanonicalRealmCatalogSnapshot( + TARGET_NAMESPACE, + tenantId, + tenantSlug, + worldSlug, + uuid(3), + "Arcology", + "Public Realm", + true, + true, + "SHARED", + uuid(14), + "owner-policy-v1", + 1L, + uuid(4), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + sourceReceipt); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java new file mode 100644 index 0000000000..978f2afe70 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java @@ -0,0 +1,1224 @@ +package net.firedevops.firemud.gamesession.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.Mockito.inOrder; +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.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.InvalidLaunchPreparationEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.LaunchPreparationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +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.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class GameSessionCanonicalLaunchPreparationServiceTest { + private static final String NAMESPACE = "canonical-launch-test"; + private static final String CONTROL_PLANE_REQUEST = "launch-attempt-1"; + private static final UUID ACTOR = uuid(1); + private static final UUID TENANT = uuid(2); + private static final UUID SOURCE_OPERATION = uuid(3); + private static final UUID SOURCE_INTAKE_OPERATION = uuid(4); + private static final UUID INTAKE_REQUEST = uuid(5); + private static final UUID REALM = uuid(6); + private static final UUID CATALOG_REQUEST = uuid(7); + private static final UUID RESERVATION_OWNER = uuid(20); + private static final UUID ISSUANCE_ID = uuid(21); + private static final UUID TOKEN_JTI = uuid(22); + private static final UUID OWNER_ATTEMPT_ID = uuid(23); + private static final UUID OWNER_MUTATION_ID = uuid(24); + private static final UUID CLAIM_OWNER_ID = uuid(25); + private static final String AUTHORIZATION_FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String LOGGING_WORKLOAD = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final AuthoredWorldLaunchDescriptorClient descriptorClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + private final GameSessionCanonicalRealmCatalogRepository catalogRepository = + mock(GameSessionCanonicalRealmCatalogRepository.class); + private final GameSessionAuthoredWorldSourceRepository sourceRepository = + mock(GameSessionAuthoredWorldSourceRepository.class); + private final GameSessionCanonicalLaunchPreparationRepository preparationRepository = + mock(GameSessionCanonicalLaunchPreparationRepository.class); + private final GameSessionStartSessionOperatorAttemptRepository attemptRepository = + mock(GameSessionStartSessionOperatorAttemptRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final GameSessionCanonicalLaunchPreparationService service = + new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsAmbientTransactionBeforeAnyOwnerReadOrNetworkCall() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> service.prepare(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void rejectsAmbientTransactionBeforeCompleteBindingOwnerReadOrNetworkCall() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void readsCompleteBindingOnlyForExactCommittedPreparationAndPreservesBothSharedEvidenceValues() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + CompleteLaunchBindingEvidence binding = completeBinding(snapshot.launchDescriptorEvidence()); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(snapshot)); + when(descriptorClient.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(binding); + + assertThat(service.readCompleteBinding(snapshot)).isEqualTo(binding); + + ArgumentCaptor request = + ArgumentCaptor.forClass(GetLaunchDescriptorRequest.class); + verify(descriptorClient).getComplete(request.capture()); + GetLaunchDescriptorRequest selector = request.getValue(); + assertThat(UUID.fromString(selector.getRequestId())).isNotEqualTo(SOURCE_OPERATION); + assertThat(selector) + .isEqualTo( + AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest( + new GetRequest( + UUID.fromString(selector.getRequestId()), + snapshot.launchDescriptorEvidence().request(), + snapshot.launchDescriptorEvidence().resultDigest()))); + assertThat(selector.getCanonicalTenantId()).isEqualTo(TENANT.toString()); + assertThat(selector.getWorldSlug()).isEqualTo(snapshot.launchDescriptorEvidence().worldSlug()); + assertThat(selector.getControlPlaneRequestId()).isEqualTo(CONTROL_PLANE_REQUEST); + assertThat(selector.getExpectedRequestDigest()) + .isEqualTo(snapshot.launchDescriptorEvidence().requestDigest()); + assertThat(selector.getExpectedResultDigest()) + .isEqualTo(snapshot.launchDescriptorEvidence().resultDigest()); + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(descriptorClient, never()).resolve(any()); + verify(descriptorClient, never()).get(any(GetRequest.class)); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedCommittedSourceFailsBeforeCompleteBindingNetworkRead() { + CanonicalLaunchPreparationSnapshot requested = preparedSnapshot(); + AuthoredWorldSourceEvidence changedSource = source("emerald-grove"); + IntakeReceipt changedIntake = intake(changedSource); + CanonicalRealmCatalogSnapshot changedCatalog = catalog(changedIntake); + CanonicalLaunchPreparationSnapshot changedCommitted = + snapshot( + requested.request(), + changedCatalog, + changedIntake, + descriptor(requested.request(), changedCatalog, changedSource)); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(changedCommitted)); + + assertThatThrownBy(() -> service.readCompleteBinding(requested)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("changed before complete binding read"); + + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verifyNoInteractions(descriptorClient); + } + + @Test + void missingCommittedPreparationFailsBeforeCompleteBindingNetworkRead() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("missing before complete binding read"); + + verifyNoInteractions(descriptorClient); + } + + @Test + void namespaceMismatchFailsBeforeCompleteBindingOwnerReadOrNetworkCall() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + GameSessionCanonicalLaunchPreparationService otherNamespaceService = + new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE + "-other"); + + assertThatThrownBy(() -> otherNamespaceService.readCompleteBinding(snapshot)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("namespace"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + } + + @Test + void changedCompleteDescriptorFailsAfterExactCommittedPreparationRead() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + AuthoredWorldLaunchDescriptorEvidence original = snapshot.launchDescriptorEvidence(); + AuthoredWorldLaunchDescriptorEvidence changed = + AuthoredWorldLaunchDescriptorEvidence.create( + original.request(), + original.launchDescriptorId() + "-changed", + original.versionId(), + original.scriptPatchVersionPresent(), + original.scriptPatchVersion(), + original.runtimeFlagsJson(), + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + original.remapSetIdPresent(), + original.remapSetId()); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(snapshot)); + when(descriptorClient.getComplete(any(GetLaunchDescriptorRequest.class))) + .thenReturn(completeBinding(changed)); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("differs from the committed launch descriptor"); + + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(descriptorClient).getComplete(any(GetLaunchDescriptorRequest.class)); + } + + @Test + void resolvesThenGetsExactDescriptorOutsideShortOwnerTransactionAndReadsCommitBack() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot snapshot = snapshot(request, catalog, intake, descriptor); + stubNewPreparation(request, source, intake, catalog, descriptor, snapshot); + + assertThat(service.prepare(request)).isEqualTo(snapshot); + + ArgumentCaptor getRequest = ArgumentCaptor.forClass(GetRequest.class); + verify(descriptorClient).resolve(descriptor.request()); + verify(descriptorClient).get(getRequest.capture()); + assertThat(getRequest.getValue().expectedRequest()).isEqualTo(descriptor.request()); + assertThat(getRequest.getValue().expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + assertThat(getRequest.getValue().requestId()).isNotEqualTo(SOURCE_OPERATION); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.commitCount).isEqualTo(1); + verify(preparationRepository).persistPrepared(request, catalog, intake, descriptor); + } + + @Test + void changedDurableCommitReadbackFailsWithoutRepairingTheStoredPreparation() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot written = snapshot(request, catalog, intake, descriptor); + CanonicalLaunchPreparationSnapshot changedReadback = + snapshot(request, catalog, intake, descriptor, uuid(14)); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(changedReadback)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(descriptor.request())).thenReturn(descriptor); + when(descriptorClient.get(any(GetRequest.class))).thenReturn(descriptor); + when(preparationRepository.persistPrepared(request, catalog, intake, descriptor)) + .thenReturn(written); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("changed during independent commit readback"); + + verify(preparationRepository, times(1)).persistPrepared(request, catalog, intake, descriptor); + verify(preparationRepository, times(2)) + .readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + } + + @Test + void exactRetryReturnsOriginalPreparationWithoutRepeatingSourceOrDescriptorCalls() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot original = snapshot(request, catalog, intake, descriptor); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + + assertThat(service.prepare(request)).isEqualTo(original); + + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void authorizedExactRetryValidatesCurrentClaimBeforeReturningWithoutResolvingAgain() + throws Exception { + CreateCanonicalLaunchPreparationRequest request = request(); + CanonicalLaunchPreparationSnapshot original = preparedSnapshot(); + StartSessionPostAuthorizationExecutionTuple tuple = authorizedTuple(request); + AttemptClaim claim = attemptClaim(request); + AttemptSnapshot attempt = attemptSnapshot(tuple, accountProjection(tuple)); + when(attemptRepository.validateCurrentClaim(claim)) + .thenAnswer( + ignored -> { + assertOwnerTransaction(); + return attempt; + }); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + + assertThat(authorizedService().prepareAuthorized(claim, request)).isEqualTo(original); + + org.mockito.InOrder calls = inOrder(attemptRepository, preparationRepository); + calls.verify(attemptRepository).validateCurrentClaim(claim); + calls + .verify(preparationRepository) + .readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + assertThat(transactionManager.commitCount).isEqualTo(1); + + resetRepositories(); + when(attemptRepository.validateCurrentClaim(claim)).thenReturn(attempt); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + CreateCanonicalLaunchPreparationRequest changedSource = + new CreateCanonicalLaunchPreparationRequest( + request.controlPlaneRequestId(), + request.actingAccountUuid(), + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision(), + uuid(99), + request.gameTemplateId(), + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion(), + request.sourceVersionIdPresent(), + request.sourceVersionId(), + request.targetVersionIdPresent(), + request.targetVersionId(), + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson()); + + assertThatThrownBy(() -> authorizedService().prepareAuthorized(claim, changedSource)) + .isInstanceOf(LaunchPreparationConflictException.class) + .hasMessageContaining("changed"); + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + } + + @Test + void rejectsAuthorizedActorTenantTemplateAndDescriptorOverrideSubstitutionBeforeUpstreamCalls() + throws Exception { + CreateCanonicalLaunchPreparationRequest request = request(); + StartSessionPostAuthorizationExecutionTuple tuple = authorizedTuple(request); + AttemptClaim claim = attemptClaim(request); + AttemptSnapshot authorizedAttempt = attemptSnapshot(tuple, accountProjection(tuple)); + when(attemptRepository.validateCurrentClaim(claim)).thenReturn(authorizedAttempt); + GameSessionCanonicalLaunchPreparationService authorizedService = authorizedService(); + + assertThatThrownBy( + () -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, uuid(98), TENANT, 71L, false, null))) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("actor, tenant, or template"); + assertThatThrownBy( + () -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, ACTOR, uuid(97), 71L, false, null))) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("actor, tenant, or template"); + assertThatThrownBy( + () -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, ACTOR, TENANT, 72L, false, null))) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("actor, tenant, or template"); + assertThatThrownBy( + () -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, ACTOR, TENANT, 71L, true, 72L))) + .isInstanceOf(LaunchPreparationConflictException.class) + .hasMessageContaining("does not authorize launch descriptor overrides"); + + verify(attemptRepository, times(4)).validateCurrentClaim(claim); + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + } + + @Test + void authorizedPreparationChecksProjectionBeforeNetworkAndRevalidatesClaimAtCommit() + throws Exception { + CreateCanonicalLaunchPreparationRequest request = request(); + StartSessionPostAuthorizationExecutionTuple tuple = authorizedTuple(request); + AttemptClaim claim = attemptClaim(request); + AccountRedemptionProjection substitutedProjection = + new AccountRedemptionProjection( + "arfp/v1/other-key/" + "c".repeat(64), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L); + AttemptSnapshot substitutedAttempt = attemptSnapshot(tuple, substitutedProjection); + when(attemptRepository.validateCurrentClaim(claim)).thenReturn(substitutedAttempt); + + assertThatThrownBy(() -> authorizedService().prepareAuthorized(claim, request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("differs from the original post-authorization tuple"); + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + int commitsAfterRejectedProjection = transactionManager.commitCount; + + resetRepositories(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot prepared = snapshot(request, catalog, intake, descriptor); + AttemptSnapshot exactAttempt = attemptSnapshot(tuple, accountProjection(tuple)); + when(attemptRepository.validateCurrentClaim(claim)) + .thenAnswer( + ignored -> { + assertOwnerTransaction(); + return exactAttempt; + }); + stubNewPreparation(request, source, intake, catalog, descriptor, prepared, true); + + assertThat(authorizedService().prepareAuthorized(claim, request)).isEqualTo(prepared); + verify(attemptRepository, times(2)).validateCurrentClaim(claim); + assertThat(transactionManager.commitCount).isEqualTo(commitsAfterRejectedProjection + 2); + verify(preparationRepository).persistPrepared(request, catalog, intake, descriptor); + } + + @Test + void changedRetryInputConflictsBeforeUpstreamResolutionOrMutation() { + CreateCanonicalLaunchPreparationRequest originalRequest = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(originalRequest, catalog, source); + CanonicalLaunchPreparationSnapshot original = + snapshot(originalRequest, catalog, intake, descriptor); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + CreateCanonicalLaunchPreparationRequest changed = + new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + NAMESPACE, + TENANT, + REALM, + CATALOG_REQUEST, + 1, + SOURCE_INTAKE_OPERATION, + 71, + true, + "", // Present-empty remains distinct from absence. + false, + null, + false, + null, + false, + null); + + assertThatThrownBy(() -> service.prepare(changed)) + .isInstanceOf(LaunchPreparationConflictException.class) + .hasMessageContaining("changed"); + + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void catalogAndSourceSubstitutionFailBeforeDescriptorResolution() { + CreateCanonicalLaunchPreparationRequest request = request(); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + CanonicalRealmCatalogSnapshot changedCatalog = catalog(intake(source()), uuid(88)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(changedCatalog)); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + + resetRepositories(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source, uuid(89)); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact fresh source intake"); + verifyNoInteractions(descriptorClient); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + } + + @Test + void namespaceTenantAndCatalogSelectorMismatchesFailBeforeDescriptorResolution() { + CreateCanonicalLaunchPreparationRequest wrongNamespace = + request(NAMESPACE + "-other", TENANT, CATALOG_REQUEST, 1); + assertThatThrownBy(() -> service.prepare(wrongNamespace)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("namespace"); + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + + resetRepositories(); + CreateCanonicalLaunchPreparationRequest wrongTenant = + request(NAMESPACE, uuid(91), CATALOG_REQUEST, 1); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog(intake(source())))); + + assertThatThrownBy(() -> service.prepare(wrongTenant)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + + resetRepositories(); + UUID changedCatalogRequestId = uuid(92); + CreateCanonicalLaunchPreparationRequest wrongCatalog = + request(NAMESPACE, TENANT, changedCatalogRequestId, 2); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, changedCatalogRequestId)) + .thenReturn(Optional.of(catalog(intake(source())))); + + assertThatThrownBy(() -> service.prepare(wrongCatalog)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + } + + @Test + void descriptorAndIndependentReadbackMustBothMatchCompleteSharedEvidence() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence.Request expected = + request.descriptorRequest(catalog, source); + AuthoredWorldLaunchDescriptorEvidence substituted = + AuthoredWorldLaunchDescriptorEvidence.create( + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + CONTROL_PLANE_REQUEST, + TENANT, + catalog.worldSlug(), + uuid(90), + source.evidenceDigest(), + 71, + false, + null, + false, + null, + false, + null, + false, + null), + "descriptor-90", + 72, + false, + null, + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(expected)).thenReturn(substituted); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("does not match"); + verify(descriptorClient, never()).get(any()); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + + resetRepositories(); + AuthoredWorldLaunchDescriptorEvidence resolved = descriptor(request, catalog, source); + AuthoredWorldLaunchDescriptorEvidence changedReadback = + AuthoredWorldLaunchDescriptorEvidence.create( + resolved.request(), + "changed-descriptor-readback", + 74, + false, + null, + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(resolved.request())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return resolved; + }); + when(descriptorClient.get(any(GetRequest.class))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return changedReadback; + }); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("readback differs"); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + } + + @Test + void requestDigestBindsOptionalPresenceAndDescriptorDigest() { + CreateCanonicalLaunchPreparationRequest absent = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence absentDescriptor = descriptor(absent, catalog, source); + CreateCanonicalLaunchPreparationRequest presentEmpty = + new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + NAMESPACE, + TENANT, + REALM, + CATALOG_REQUEST, + 1, + SOURCE_INTAKE_OPERATION, + 71, + true, + "", + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence presentEmptyDescriptor = + descriptor(presentEmpty, catalog, source); + + assertThat( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, catalog, intake, absentDescriptor)) + .isNotEqualTo( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + presentEmpty, catalog, intake, presentEmptyDescriptor)); + + CanonicalRealmCatalogSnapshot changedCatalogPayload = + new CanonicalRealmCatalogSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.realmId(), + "changed-realm-slug", + "Changed Realm Display Name", + catalog.visible(), + catalog.publicProduction(), + catalog.stateScope(), + uuid(93), + catalog.characterCreationPolicy(), + catalog.catalogRevision(), + catalog.creationRequestId(), + catalog.requestDigest(), + catalog.receiptDigest(), + intake); + assertThat( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, changedCatalogPayload, intake, absentDescriptor)) + .isNotEqualTo( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, catalog, intake, absentDescriptor)); + } + + private GameSessionCanonicalLaunchPreparationService authorizedService() { + return new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + attemptRepository, + transactionManager, + NAMESPACE); + } + + private static void assertOwnerTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static AttemptClaim attemptClaim(CreateCanonicalLaunchPreparationRequest request) { + return new AttemptClaim( + NAMESPACE, + request.controlPlaneRequestId(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + CLAIM_OWNER_ID, + 29L); + } + + private static CreateCanonicalLaunchPreparationRequest requestVariant( + CreateCanonicalLaunchPreparationRequest original, + UUID actor, + UUID tenant, + long gameTemplateId, + boolean targetVersionPresent, + Long targetVersion) { + return new CreateCanonicalLaunchPreparationRequest( + original.controlPlaneRequestId(), + actor, + original.targetNamespace(), + tenant, + original.realmId(), + original.catalogCreationRequestId(), + original.catalogRevision(), + original.sourceIntakeOperationId(), + gameTemplateId, + false, + null, + false, + null, + targetVersionPresent, + targetVersion, + false, + null); + } + + private static AttemptSnapshot attemptSnapshot( + StartSessionPostAuthorizationExecutionTuple tuple, AccountRedemptionProjection projection) { + AttemptSnapshot snapshot = mock(AttemptSnapshot.class); + when(snapshot.targetNamespace()).thenReturn(NAMESPACE); + when(snapshot.controlPlaneRequestId()).thenReturn(tuple.controlPlaneRequestId()); + when(snapshot.canonicalTenantId()).thenReturn(TENANT); + when(snapshot.ownerAttemptId()).thenReturn(OWNER_ATTEMPT_ID); + when(snapshot.ownerMutationId()).thenReturn(OWNER_MUTATION_ID); + when(snapshot.ownerFence()).thenReturn(29L); + when(snapshot.phaseState()).thenReturn("OWNER_EXECUTION_PENDING"); + when(snapshot.postAuthorizationExecutionTuple()).thenReturn(tuple.canonicalBytes()); + when(snapshot.accountRedemptionProjection()).thenReturn(projection.canonicalBytes()); + return snapshot; + } + + private static AccountRedemptionProjection accountProjection( + StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())); + } + + private static StartSessionPostAuthorizationExecutionTuple authorizedTuple( + CreateCanonicalLaunchPreparationRequest request) throws IOException { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(request.gameTemplateId(), ACTOR), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Game Session source-qualified launch preparation"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + request.controlPlaneRequestId(), ACTOR, action); + byte[] bundleBytes = authorityEvidenceBundle(preTuple); + StartSessionAuthorityEvidenceBundle.BundleReference reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + LOGGING_WORKLOAD, + AUTHORIZATION_FINGERPRINT, + RESERVATION_OWNER, + 19L, + bundleBytes, + reference); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple preTuple) throws IOException { + String tenantId = TENANT.toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map identity = + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", preTuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + preTuple.controlPlaneRequestId()), + "mutationDigest", preTuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", preTuple.action().actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private void stubNewPreparation( + CreateCanonicalLaunchPreparationRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + IntakeReceipt intake, + CanonicalRealmCatalogSnapshot catalog, + AuthoredWorldLaunchDescriptorEvidence descriptor, + CanonicalLaunchPreparationSnapshot snapshot) { + stubNewPreparation(request, sourceEvidence, intake, catalog, descriptor, snapshot, false); + } + + private void stubNewPreparation( + CreateCanonicalLaunchPreparationRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + IntakeReceipt intake, + CanonicalRealmCatalogSnapshot catalog, + AuthoredWorldLaunchDescriptorEvidence descriptor, + CanonicalLaunchPreparationSnapshot snapshot, + boolean verifyAuthorizedClaimRevalidation) { + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(snapshot)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(descriptor.request())) + .thenAnswer( + ignored -> { + if (verifyAuthorizedClaimRevalidation) { + verify(attemptRepository, times(1)).validateCurrentClaim(attemptClaim(request)); + } + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return descriptor; + }); + when(descriptorClient.get(any(GetRequest.class))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return descriptor; + }); + when(preparationRepository.persistPrepared(request, catalog, intake, descriptor)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(descriptor.authoredWorldSourceOperationId()) + .isEqualTo(sourceEvidence.operationId()); + if (verifyAuthorizedClaimRevalidation) { + verify(attemptRepository, times(2)).validateCurrentClaim(attemptClaim(request)); + } + return snapshot; + }); + } + + private void resetRepositories() { + org.mockito.Mockito.reset( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + attemptRepository); + } + + private static CanonicalLaunchPreparationSnapshot preparedSnapshot() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + return snapshot(request, catalog, intake, descriptor(request, catalog, source)); + } + + private static CreateCanonicalLaunchPreparationRequest request() { + return request(NAMESPACE, TENANT, CATALOG_REQUEST, 1); + } + + private static CreateCanonicalLaunchPreparationRequest request( + String namespace, UUID tenant, UUID catalogRequest, long catalogRevision) { + return new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + namespace, + tenant, + REALM, + catalogRequest, + catalogRevision, + SOURCE_INTAKE_OPERATION, + 71, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static AuthoredWorldSourceEvidence source() { + return source("violet-wilds"); + } + + private static AuthoredWorldSourceEvidence source(String world) { + String tenantSlug = "north-star"; + String displayName = "emerald-grove".equals(world) ? "Emerald Grove" : "Violet Wilds"; + UUID registrationId = uuid(10); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationId, TENANT, tenantSlug, world, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationId, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + tenantSlug, + world, + displayName, + 44, + "fresh-source-key-44", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationId, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + tenantSlug, + world, + displayName, + 44, + "fresh-source-key-44", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static IntakeReceipt intake(AuthoredWorldSourceEvidence source) { + return intake(source, SOURCE_INTAKE_OPERATION); + } + + private static IntakeReceipt intake(AuthoredWorldSourceEvidence source, UUID operationId) { + String requestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(INTAKE_REQUEST, source); + return new IntakeReceipt( + operationId, + INTAKE_REQUEST, + requestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, source.evidenceDigest())); + } + + private static CanonicalRealmCatalogSnapshot catalog(IntakeReceipt source) { + return catalog(source, REALM); + } + + private static CanonicalRealmCatalogSnapshot catalog(IntakeReceipt source, UUID realmId) { + return new CanonicalRealmCatalogSnapshot( + NAMESPACE, + TENANT, + source.source().tenantSlug(), + source.source().worldSlug(), + realmId, + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + uuid(12), + "explicit-policy-v1", + 1, + CATALOG_REQUEST, + digest("c"), + digest("d"), + source); + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptor( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + AuthoredWorldSourceEvidence source) { + long targetVersionId = + request.targetVersionIdPresent() + ? java.util.Objects.requireNonNull(request.targetVersionId(), "targetVersionId") + : 72L; + return AuthoredWorldLaunchDescriptorEvidence.create( + request.descriptorRequest(catalog, source), + "launch-descriptor-1", + targetVersionId, + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion(), + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + } + + private static CompleteLaunchBindingEvidence completeBinding( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + String publishCommitId = "publish-commit-902"; + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + publishCommitId, + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest("d") : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + uuid(15), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant:version:request", + publishCommitId, + participants, + digest("b"), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + } + + private static CanonicalLaunchPreparationSnapshot snapshot( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return snapshot(request, catalog, source, descriptor, uuid(13)); + } + + private static CanonicalLaunchPreparationSnapshot snapshot( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID operationId) { + String requestDigest = + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + request, catalog, source, descriptor); + return new CanonicalLaunchPreparationSnapshot( + operationId, + request, + catalog, + source, + descriptor, + requestDigest, + GameSessionCanonicalLaunchPreparationRepository.receiptDigest( + operationId, request, catalog, source, descriptor, requestDigest)); + } + + private static String digest(String letter) { + return "sha256:" + letter.repeat(64); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private TransactionDefinition startedWith; + private int commitCount; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commitCount++; + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java new file mode 100644 index 0000000000..348ca6b2c7 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java @@ -0,0 +1,507 @@ +package net.firedevops.firemud.gamesession.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.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 io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClient; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationDisposition; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class GameSessionStartSessionOperatorAuthorizationCoordinatorTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID OWNER_ATTEMPT = UUID.fromString("69116466-a576-4fa6-9e11-4c0c6b2a92f0"); + private static final UUID OWNER_MUTATION = + UUID.fromString("89da7d84-12f5-4cf8-b69b-30ba8eb115a4"); + private static final UUID CLAIM_OWNER = UUID.fromString("31f85ac3-e621-4c38-a207-0e5aab116d34"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "world-runtime"; + private static final String REQUEST_ID = "authorization-coordinator-request"; + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String OPAQUE_REFERENCE = "A".repeat(43); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void commitsOwnerClaimBeforeOneAccountCallAndAttachesOnlyUnderSameCurrentClaim() + throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + AttemptClaim claim = claim(REQUEST_ID); + AccountRedemptionProjection projection = projection(tuple); + AttemptSnapshot reserved = snapshot(tuple, claim, null); + AttemptSnapshot attached = snapshot(tuple, claim, projection.canonicalBytes()); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = + coordinator(repository, redemptionClient, transactions); + List order = new ArrayList<>(); + + when(repository.reserve(tuple)) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + order.add("reserve"); + return new ReservationResult( + ReservationDisposition.CLAIM_CREATED, reserved, Optional.of(claim)); + }); + when(redemptionClient.redeem(tuple, OPAQUE_REFERENCE, claim)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(transactions.commitCount).isEqualTo(1); + order.add("account"); + return new StartSessionOperatorRedemptionClient.RedemptionResult( + claim, projection, false); + }); + when(repository.validateCurrentClaim(claim)) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + order.add("validate"); + return reserved; + }); + when(repository.attachAccountRedemptionProjection(claim, projection)) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + order.add("attach"); + return attached; + }); + + GameSessionStartSessionOperatorAuthorizationCoordinator.AuthorizationResult result = + withPeer(peer(WORKLOAD), () -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(order).containsExactly("reserve", "account", "validate", "attach"); + assertThat(transactions.commitCount).isEqualTo(2); + assertThat(transactions.rollbackCount).isZero(); + assertThat(transactions.definitions) + .hasSize(2) + .allSatisfy( + definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); + assertThat(result.progress()) + .isEqualTo( + GameSessionStartSessionOperatorAuthorizationCoordinator.Progress + .ACCOUNT_PROJECTION_ATTACHED); + assertThat(result.claim()).contains(claim); + assertThat(result.snapshot()).isSameAs(attached); + assertThat(result.toString()).doesNotContain(OPAQUE_REFERENCE); + verify(repository).attachAccountRedemptionProjection(claim, projection); + } + + @Test + void exactRetryReturnsDurablePendingSnapshotWithoutRedeemingAgain() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + AttemptSnapshot pending = snapshot(tuple, claim(REQUEST_ID), null); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + when(repository.reserve(tuple)) + .thenReturn( + new ReservationResult(ReservationDisposition.EXACT_REPLAY, pending, Optional.empty())); + + var result = + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, transactions) + .authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(result.progress()) + .isEqualTo(GameSessionStartSessionOperatorAuthorizationCoordinator.Progress.EXACT_REPLAY); + assertThat(result.snapshot()).isSameAs(pending); + assertThat(result.claim()).isEmpty(); + assertThat(transactions.commitCount).isEqualTo(1); + verifyNoInteractions(redemptionClient); + verify(repository, never()).validateCurrentClaim(any()); + verify(repository, never()).attachAccountRedemptionProjection(any(), any()); + } + + @Test + void rejectsWrongAuthenticatedPeerOrNamespaceBeforeOwnerAccess() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + var coordinator = coordinator(repository, redemptionClient, transactions); + + assertThatThrownBy( + () -> + withPeer( + peer("spiffe://firemud/ns/world-runtime/sa/account-service"), + () -> coordinator.authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("spiffe://firemud/ns/other-runtime/sa/logging-admin-service"), + () -> coordinator.authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf(SecurityException.class); + + assertThat(transactions.definitions).isEmpty(); + verifyNoInteractions(repository, redemptionClient); + } + + @Test + void tupleConflictRollsBackClaimReservationAndNeverCallsAccount() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + when(repository.reserve(tuple)) + .thenThrow( + new GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException("different immutable tuple")); + + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, transactions) + .authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + + assertThat(transactions.commitCount).isZero(); + assertThat(transactions.rollbackCount).isEqualTo(1); + verifyNoInteractions(redemptionClient); + } + + @Test + void ambiguousAccountTransportLeavesCommittedClaimPendingWithoutRetryOrAttachment() + throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + AttemptClaim claim = claim(REQUEST_ID); + AttemptSnapshot pending = snapshot(tuple, claim, null); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + when(repository.reserve(tuple)) + .thenReturn( + new ReservationResult( + ReservationDisposition.CLAIM_CREATED, pending, Optional.of(claim))); + when(redemptionClient.redeem(tuple, OPAQUE_REFERENCE, claim)) + .thenThrow(new StatusRuntimeException(Status.DEADLINE_EXCEEDED)); + + var result = + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, transactions) + .authorize(tuple, OPAQUE_REFERENCE)); + + assertThat(result.progress()) + .isEqualTo( + GameSessionStartSessionOperatorAuthorizationCoordinator.Progress + .ACCOUNT_OUTCOME_AMBIGUOUS); + assertThat(result.snapshot()).isSameAs(pending); + assertThat(result.claim()).contains(claim); + assertThat(result.toString()).doesNotContain(OPAQUE_REFERENCE); + assertThat(transactions.commitCount).isEqualTo(1); + assertThat(transactions.rollbackCount).isZero(); + verify(redemptionClient).redeem(tuple, OPAQUE_REFERENCE, claim); + verify(repository, never()).validateCurrentClaim(any()); + verify(repository, never()).attachAccountRedemptionProjection(any(), any()); + } + + @Test + void staleClaimDuringProjectionAttachmentCannotProduceAttachedProgress() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + AttemptClaim claim = claim(REQUEST_ID); + AccountRedemptionProjection projection = projection(tuple); + AttemptSnapshot pending = snapshot(tuple, claim, null); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + RecordingTransactionManager transactions = new RecordingTransactionManager(); + when(repository.reserve(tuple)) + .thenReturn( + new ReservationResult( + ReservationDisposition.CLAIM_CREATED, pending, Optional.of(claim))); + when(redemptionClient.redeem(tuple, OPAQUE_REFERENCE, claim)) + .thenReturn( + new StartSessionOperatorRedemptionClient.RedemptionResult(claim, projection, false)); + when(repository.validateCurrentClaim(claim)).thenReturn(pending); + when(repository.attachAccountRedemptionProjection(claim, projection)) + .thenThrow( + new GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException("claim expired before attachment")); + + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, transactions) + .authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException.class); + + assertThat(transactions.commitCount).isEqualTo(1); + assertThat(transactions.rollbackCount).isEqualTo(1); + verify(repository).validateCurrentClaim(claim); + verify(repository).attachAccountRedemptionProjection(claim, projection); + } + + @Test + void refusesToRunInsideAmbientTransactionBeforeOwnerAccess() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, new RecordingTransactionManager()) + .authorize(tuple, OPAQUE_REFERENCE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient owner transaction"); + + verifyNoInteractions(repository, redemptionClient); + } + + private static GameSessionStartSessionOperatorAuthorizationCoordinator coordinator( + GameSessionStartSessionOperatorAttemptRepository repository, + StartSessionOperatorRedemptionClient redemptionClient, + PlatformTransactionManager transactions) { + return new GameSessionStartSessionOperatorAuthorizationCoordinator( + repository, redemptionClient, transactions, NAMESPACE); + } + + private static GameSessionStartSessionOperatorAttemptRepository mockRepository() { + return mock(GameSessionStartSessionOperatorAttemptRepository.class); + } + + private static StartSessionOperatorRedemptionClient mockRedemptionClient() { + return mock(StartSessionOperatorRedemptionClient.class); + } + + private static void assertWritableReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static AttemptClaim claim(String requestId) { + return new AttemptClaim(NAMESPACE, requestId, OWNER_ATTEMPT, OWNER_MUTATION, CLAIM_OWNER, 37L); + } + + private static AttemptSnapshot snapshot( + StartSessionPostAuthorizationExecutionTuple tuple, AttemptClaim claim, byte[] projection) { + AttemptSnapshot snapshot = mock(AttemptSnapshot.class); + when(snapshot.targetNamespace()).thenReturn(NAMESPACE); + when(snapshot.controlPlaneRequestId()).thenReturn(tuple.controlPlaneRequestId()); + when(snapshot.canonicalTenantId()).thenReturn(TENANT); + when(snapshot.ownerAttemptId()).thenReturn(claim.ownerAttemptId()); + when(snapshot.ownerMutationId()).thenReturn(claim.ownerMutationId()); + when(snapshot.ownerFence()).thenReturn(claim.ownerFence()); + when(snapshot.phaseState()).thenReturn("OWNER_EXECUTION_PENDING"); + when(snapshot.postAuthorizationExecutionTuple()).thenReturn(tuple.canonicalBytes()); + when(snapshot.accountRedemptionProjection()) + .thenReturn(projection == null ? null : projection.clone()); + return snapshot; + } + + private static AccountRedemptionProjection projection( + StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String requestId) + throws IOException { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Game Session operator authorization coordinator contract"); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + WORKLOAD, + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) + throws IOException { + String tenantId = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static GrpcPeerIdentity peer(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static T withPeer(GrpcPeerIdentity peer, ThrowingSupplier work) throws Exception { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return work.get(); + } finally { + context.detach(previous); + } + } + + @FunctionalInterface + private interface ThrowingSupplier { + T get() throws Exception; + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private final List definitions = new ArrayList<>(); + private int commitCount; + private int rollbackCount; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + definitions.add(definition); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commitCount++; + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + rollbackCount++; + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java new file mode 100644 index 0000000000..7bc86fd9c5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.gamesession.service.impl; + +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.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class DatabaseCanonicalInitialAdmissionServiceTest { + private final CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + private final GameSessionCanonicalAdmissionPointerRepository pointerRepository = + mock(GameSessionCanonicalAdmissionPointerRepository.class); + private final CanonicalInitialAdmissionWorldVerifier worldVerifier = + mock(CanonicalInitialAdmissionWorldVerifier.class); + private final DatabaseCanonicalInitialAdmissionService service = + new DatabaseCanonicalInitialAdmissionService(repository, pointerRepository, worldVerifier); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void bindRejectsWritableAmbientTransactionBeforeAnyCollaboratorAccess() { + assertAmbientTransactionRejected(false, () -> service.bind(request())); + } + + @Test + void bindRejectsReadOnlyAmbientTransactionBeforeAnyCollaboratorAccess() { + assertAmbientTransactionRejected(true, () -> service.bind(request())); + } + + @Test + void abortRejectsWritableAmbientTransactionBeforeAnyCollaboratorAccess() { + assertAmbientTransactionRejected(false, () -> service.abort(request(), "test abort")); + } + + @Test + void abortRejectsReadOnlyAmbientTransactionBeforeAnyCollaboratorAccess() { + assertAmbientTransactionRejected(true, () -> service.abort(request(), "test abort")); + } + + @Test + void committedReplayReturnsStoredOwnerProofWithoutWorldVerification() { + CanonicalInitialAdmissionRequest request = request(); + CanonicalInitialAdmissionOwnerProof committed = committedProof(request); + when(repository.read(request.targetNamespace(), request.initialAdmissionRequestId())) + .thenReturn(Optional.of(committed)); + + assertThat(service.bind(request)).isEqualTo(committed); + + verify(repository).reserve(request); + verify(repository).read(request.targetNamespace(), request.initialAdmissionRequestId()); + verifyNoInteractions(pointerRepository, worldVerifier); + } + + private void assertAmbientTransactionRejected(boolean readOnly, Runnable operation) { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly); + + assertThatThrownBy(operation::run) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + + verifyNoInteractions(repository, pointerRepository, worldVerifier); + } + + private static CanonicalInitialAdmissionRequest request() { + String targetNamespace = "initial-admission-test"; + UUID tenantId = uuid("11111111-1111-4111-8111-111111111111"); + String worldSlug = "demo-world"; + UUID realmId = uuid("22222222-2222-4222-8222-222222222222"); + UUID playableStateNamespaceId = uuid("33333333-3333-4333-8333-333333333333"); + String playableStateScope = "SHARED"; + UUID gameInstanceId = uuid("44444444-4444-4444-8444-444444444444"); + UUID versionId = uuid("55555555-5555-4555-8555-555555555555"); + long activeLifecycleEpoch = 6L; + long catalogRevision = 7L; + OriginKind originKind = OriginKind.NO_PRIOR_POINTER; + String requestId = "initial-admission-replay-1"; + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + targetNamespace, + tenantId, + worldSlug, + realmId, + playableStateNamespaceId, + playableStateScope, + gameInstanceId, + versionId, + activeLifecycleEpoch, + catalogRevision, + originKind, + null, + requestId); + + return new CanonicalInitialAdmissionRequest( + targetNamespace, + tenantId, + worldSlug, + realmId, + playableStateNamespaceId, + playableStateScope, + gameInstanceId, + versionId, + activeLifecycleEpoch, + catalogRevision, + originKind, + null, + requestId, + requestDigest, + uuid("66666666-6666-4666-8666-666666666666"), + uuid("77777777-7777-4777-8777-777777777777"), + "sha256:" + "a".repeat(64)); + } + + private static CanonicalInitialAdmissionOwnerProof committedProof( + CanonicalInitialAdmissionRequest request) { + return new CanonicalInitialAdmissionOwnerProof( + Outcome.COMMITTED, + request.initialAdmissionRequestId(), + request.requestDigest(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + request.activeLifecycleEpoch(), + request.expectedCatalogRevision(), + request.originKind(), + request.expectedPriorPointerVersion(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest(), + 1L, + 1L, + "sha256:" + "b".repeat(64), + false, + Instant.parse("2026-10-10T00:00:00Z")); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} From b2759f0f3e5cb35958ac2c1fae50dd59d9276422 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:47:14 +1300 Subject: [PATCH 03/22] Correct canonical World source provenance and inactive owner proof status --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 488e1e3b71..db277b768a 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 Game Session has an unregistered original-claim evidence-continuation preparation: owner repositories, typed read/pin carriers, before-and-after authenticated Account projection reads outside SQL, and database-clock claim/reference-expiry checks at descriptor pinning. Consolidated Common/Game Session unit and non-container integration checks pass, as do generated-source compilation, formatting, static analysis, and documentation checks. PostgreSQL fixtures cover expiry, exact replay, mismatch, and pin races but remain unexecuted locally without Docker. Genuine Account original-redeemed receiver revalidation and full pointer/audit/live-owner composition remain required; mocked responses do not prove that receiver. This preparation grants no new mutation authorization or admission and does not establish playable closure. The bounded contract is owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). -The same inactive preparation now includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These new repositories, coordinator and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Consolidated local checks passed in 2m36s: 271 Common and 1,992 Game Session unit definitions had zero failures (17 Game Session skips); 208 integration definitions executed 18 and skipped 190 without Docker, while cross-service definitions executed one and skipped 38. The new PostgreSQL fixtures compile but have not physically executed. The prepared request requires a World-owned hold-binding digest and supports a CLOSED origin that the current no-prior-pointer World hold RPC does not supply; those interfaces must converge before authenticated composition. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. +The same inactive preparation now includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These new repositories, coordinator and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Consolidated local checks passed in 2m36s and passed again after exact parent reconciliation in 54s: 271 Common and 1,992 Game Session unit definitions had zero failures (17 Game Session skips); 208 integration definitions executed 18 and skipped 190 without Docker, while cross-service definitions executed one and skipped 38. These include reused task outputs rather than a claim that every definition executed again. The new PostgreSQL fixtures compile but have not physically executed. Document's published `2cb445617` supplies the canonical World hold request and immutable identity, including both origin selectors and the request-binding digest; the older numeric hold RPC is not that interface. The canonical consumer still needs durable pre-hold intent, exact attachment, authenticated live-owner verification and terminal composition. Historical acquisition identity alone is not live hold or admission proof. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. The 7a physical and local proof scopes, failures, and V98 limitation are detailed below and in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Hosted-terms acceptance, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898/#2848 and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). From c79103014c1b991f4caaa3f1fef04652ec1adda8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:31:33 +1300 Subject: [PATCH 04/22] Prepare durable canonical initial-hold intent and historical owner reads --- .../game-session-service/api-contracts.md | 4 + .../player-access-and-session.md | 4 +- ...rld_canonical_initial_admission_hold.proto | 45 + ...ld_canonical_instance_lifecycle_read.proto | 22 + ...WorldCanonicalInstanceLifecycleClient.java | 156 ++++ ...rldCanonicalInstanceLifecycleEvidence.java | 556 +++++++++++ ...ldCanonicalInstanceLifecycleGrpcCodec.java | 69 ++ ...onicalInstanceLifecycleClientMtlsTest.java | 587 ++++++++++++ ...anonicalInstanceLifecycleEvidenceTest.java | 879 ++++++++++++++++++ ...ldCanonicalInitialAdmissionHoldClient.java | 267 ++++++ ...nonicalInitialAdmissionIntentSnapshot.java | 226 +++++ ...nicalInitialAdmissionIntentRepository.java | 467 ++++++++++ ...StartSessionOperatorAttemptRepository.java | 70 ++ ...tSessionTemplateAssociationRepository.java | 35 + ...onicalInitialAdmissionHoldPreparation.java | 112 +++ ...issionIntentRepositoryIntegrationTest.java | 872 +++++++++++++++++ ...ratorAttemptRepositoryIntegrationTest.java | 248 ++++- ...eAssociationRepositoryIntegrationTest.java | 169 +++- ...nonicalInitialAdmissionHoldClientTest.java | 615 ++++++++++++ ...lInitialAdmissionIntentRepositoryTest.java | 132 +++ ...alInitialAdmissionHoldPreparationTest.java | 434 +++++++++ 21 files changed, 5963 insertions(+), 6 deletions(-) create mode 100644 protos/world-management/v1/world_canonical_initial_admission_hold.proto create mode 100644 protos/world-management/v1/world_canonical_instance_lifecycle_read.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionIntentSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparation.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparationTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 8fce3878ac..5b187456d2 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,6 +8,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status +The canonical initial-admission preparation is inactive: the durable pre-hold intent repository and coordinator, exact World hold client, and lifecycle read client are not registered for runtime use. The coordinator commits the immutable intent before the remote hold request, then attaches only the exact World-issued identity in a separate owner transaction; an attached or terminal intent replay is historical evidence, not permission to admit. Authenticated live-hold validation, continuous protection through the pointer/audit commit, and cross-owner terminal reconciliation remain required. The narrower historical original-operation read is described under [restricted original-claim evidence continuation](#restricted-original-claim-evidence-continuation); neither that read nor a lifecycle snapshot supplies those missing guarantees. + `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` currently fail closed at their authenticated internal receiving boundary with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable`, before command, coordinator, follow-up, or queue mutation. The retained lower-level admission implementation does not prove the cross-service Automation admission-epoch fence required by [ADR 0106](../../decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md). A separate receiver-fence successor must durably serialize installation against receiving admission, preserve exact retry outcomes, and prove that a handoff whose intent committed before an Automation pause cannot create live work under the displaced admission epoch afterward. This gate preserves ordinary gameplay APIs and does not claim the successor implemented. Realm-catalog identity status: Game Session pointer and audit rows persist a separately advancing positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; player-facing catalog and runtime pointer projections fail closed when identity is incomplete or a tenant catalog is ambiguous. The control-plane `SetAdmissionPointer` and `ExecutePreparedVersionCutover` paths remain closed pending catalog-revision and durable-identity preconditions. The configuration-driven pointer initializer validates seed shape but does not write authority rows while World-owned lifecycle proof is unavailable; raw seed inputs do not establish that proof or an owner-validated initial bind. Current implementation and proof gaps are tracked in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md). @@ -133,6 +135,8 @@ Under approved original-claim continuation decision `ae27ed99`, this narrowly bo The continuation is restricted to reading and exact replay of an existing immutable association pin. It must not replay redemption, create or reselect an association, create a claim, attempt, fence, or authorization reference, renew or transfer ownership, mutate domain state, or admit a player. Remote Account/source reads occur outside SQL; Game Session then locks and rechecks the same owner state before returning the association. The actual pin/read statement enforces claim expiry using the database clock. Missing or unattached projections, absent or changed pins, changed tuples, expired claims, and ambiguous outcomes remain reconciliation-only and cannot be treated as authorization or admission. +Historical original-operation reconciliation is separate from that live continuation. The unregistered owner repositories can read the complete retained StartSession tuple, actual original attempt/fence, exact attached Account projection and existing immutable first-selection pin after lease or reference expiry. These reads create no claim, renewal, redemption, reselection, pointer/audit mutation or admission authority; missing or mismatched retained evidence fails closed. The authenticated World-facing producer and cross-owner recovery composition remain unimplemented. This historical evidence is not a current World hold or a Game Session terminal outcome. + ### gRPC Outcome Handling Game Session follows the [canonical gRPC outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification). A successfully produced command, control-plane, or read outcome uses its typed response contract; a failure that prevents producing that domain result uses canonical non-OK status with bounded structured details. Game Session preserves stable mutation request identities and reconciles ambiguous timeouts or transport failures before replaying work. Current handlers use a mixture of response-level `ErrorDetail` and transport failures, so exact per-RPC classifications and focused migration proof remain implementation gaps rather than a new service contract. 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 46666dcdd0..36b6764bf5 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 Game Session has an unregistered original-claim evidence-continuation preparation: owner repositories, typed read/pin carriers, before-and-after authenticated Account projection reads outside SQL, and database-clock claim/reference-expiry checks at descriptor pinning. Consolidated Common/Game Session unit and non-container integration checks pass, as do generated-source compilation, formatting, static analysis, and documentation checks. PostgreSQL fixtures cover expiry, exact replay, mismatch, and pin races but remain unexecuted locally without Docker. Genuine Account original-redeemed receiver revalidation and full pointer/audit/live-owner composition remain required; mocked responses do not prove that receiver. This preparation grants no new mutation authorization or admission and does not establish playable closure. The bounded contract is owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). -The same inactive preparation now includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These new repositories, coordinator and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Consolidated local checks passed in 2m36s and passed again after exact parent reconciliation in 54s: 271 Common and 1,992 Game Session unit definitions had zero failures (17 Game Session skips); 208 integration definitions executed 18 and skipped 190 without Docker, while cross-service definitions executed one and skipped 38. These include reused task outputs rather than a claim that every definition executed again. The new PostgreSQL fixtures compile but have not physically executed. Document's published `2cb445617` supplies the canonical World hold request and immutable identity, including both origin selectors and the request-binding digest; the older numeric hold RPC is not that interface. The canonical consumer still needs durable pre-hold intent, exact attachment, authenticated live-owner verification and terminal composition. Historical acquisition identity alone is not live hold or admission proof. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. +The same inactive preparation includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These repositories, coordinator and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Earlier consolidated local checks passed in 2m36s and after exact parent reconciliation in 54s: 271 Common and 1,992 Game Session unit definitions had zero failures (17 Game Session skips); 208 integration definitions executed 18 and skipped 190 without Docker, while cross-service definitions executed one and skipped 38. These include reused task outputs rather than a claim that every definition executed again. The PostgreSQL fixtures compile but have not physically executed locally. Document's published `2cb445617` supplies the canonical World hold request and immutable identity, including both origin selectors and the request-binding digest; the older numeric hold RPC is not that interface. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. + +The newer inactive consumer adds exact mTLS World acquisition/identity and lifecycle read clients, the V28-backed durable pre-hold intent repository, and a coordinator that commits the immutable request before contacting World and attaches only the exact returned hold identity in a separate owner transaction. Remote failure preserves the pending intent for the same request; attached or terminal replay returns historical evidence only. Owner repositories also expose non-mutating historical reads of the complete original StartSession tuple, actual attempt/fence, attached Account projection and immutable first template pin after expiry, separately from the still-unexpired live continuation. Consolidated Common/Game Session checks, generated and integration-source compilation, formatting, Checkstyle, SpotBugs, links and Markdown checks passed in 1m5s. The local snapshot has 283 Common and 2,006 Game Session unit definitions with zero failures and 17 Game Session skips; integration definitions executed 18 and skipped 200, and cross-service executed one and skipped 38 without Docker. Cached task outputs are included, not claimed as fresh re-execution. The new PostgreSQL ordering fixture checks that a separate connection sees the exact committed pending intent before World acquisition and that remote failure/retry preserves one exact intent; it has not physically executed locally. An authenticated World-facing original-owner producer, live hold validation, continuous protection through pointer/audit commit and cross-owner terminal reconciliation remain unimplemented. Neither a historical identity nor a lifecycle snapshot proves those guarantees, and no runtime registration or activation is added. The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. Historical and current bounded proof, failures, and pending physical validation are recorded below. Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Hosted-terms acceptance, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898/#2848 and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). diff --git a/protos/world-management/v1/world_canonical_initial_admission_hold.proto b/protos/world-management/v1/world_canonical_initial_admission_hold.proto new file mode 100644 index 0000000000..f33c447ac0 --- /dev/null +++ b/protos/world-management/v1/world_canonical_initial_admission_hold.proto @@ -0,0 +1,45 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Canonical World initial-admission hold owner operations. Runtime composition is explicitly +// opt-in and default-disabled; each operation authenticates the exact Game Session workload. +service WorldCanonicalInitialAdmissionHoldService { + rpc AcquireCanonicalInitialAdmissionHold(AcquireCanonicalInitialAdmissionHoldRequest) + returns (AcquireCanonicalInitialAdmissionHoldResponse); + rpc ReadCanonicalInitialAdmissionHoldIdentity(ReadCanonicalInitialAdmissionHoldIdentityRequest) + returns (ReadCanonicalInitialAdmissionHoldIdentityResponse); +} + +message AcquireCanonicalInitialAdmissionHoldRequest { + // Complete closed canonical World initial-admission hold request bytes. + bytes canonical_hold_request_bytes = 1; + + // Complete closed canonical World lifecycle read request bytes for the exact target. + bytes canonical_lifecycle_read_request_bytes = 2; +} + +message AcquireCanonicalInitialAdmissionHoldResponse { + // Immutable World-issued hold identity, including the exact request bytes and binding digest. + bytes hold_identity_bytes = 1; +} + +message ReadCanonicalInitialAdmissionHoldIdentityRequest { + // Fresh non-nil UUID correlation for this read, in canonical lowercase form. + string read_request_id = 1; + + // Complete closed canonical World initial-admission hold request bytes. + bytes canonical_hold_request_bytes = 2; +} + +message ReadCanonicalInitialAdmissionHoldIdentityResponse { + // Exact correlation echoed from this read request. + string read_request_id = 1; + + // Historical immutable acquisition identity only; this is not terminal state, current + // admission, or an absence checkpoint. + bytes hold_identity_bytes = 2; +} diff --git a/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto b/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto new file mode 100644 index 0000000000..2fe0c25a6b --- /dev/null +++ b/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Read-only complete canonical World lifecycle owner evidence for authenticated Game Session. +service WorldCanonicalInstanceLifecycleReadService { + rpc ReadWorldCanonicalInstanceLifecycle(ReadWorldCanonicalInstanceLifecycleRequest) + returns (ReadWorldCanonicalInstanceLifecycleResponse); +} + +message ReadWorldCanonicalInstanceLifecycleRequest { + // Complete closed versioned WorldCanonicalInstanceLifecycleEvidence.Request bytes. + bytes canonical_request_bytes = 1; +} + +message ReadWorldCanonicalInstanceLifecycleResponse { + // Complete closed evidence bytes, including the exact request echo and full launch binding. + bytes canonical_response_bytes = 1; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java new file mode 100644 index 0000000000..33aef52809 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.world; + +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.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 net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; + +/** Explicit mTLS client for the exact World canonical instance lifecycle read. */ +public final class WorldCanonicalInstanceLifecycleClient + extends AbstractReloadingBlockingGrpcClient< + WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldCanonicalInstanceLifecycleClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldCanonicalInstanceLifecycleClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Game Session service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World canonical lifecycle client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World canonical lifecycle client has no gRPC stub"); + } + initialized = true; + } + + /** Reads and validates World-owned lifecycle evidence for this exact canonical request. */ + public WorldCanonicalInstanceLifecycleEvidence read( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World canonical lifecycle request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldCanonicalInstanceLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request)); + try { + return WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid canonical instance lifecycle evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldCanonicalInstanceLifecycleReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World canonical lifecycle client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World canonical lifecycle 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( + "World canonical lifecycle read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World canonical lifecycle read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World canonical lifecycle read " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World canonical lifecycle read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java new file mode 100644 index 0000000000..cef01812bf --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java @@ -0,0 +1,556 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact, non-admitting World lifecycle owner readback for an authenticated canonical caller. + * + *

Decoding this carrier does not authenticate World, establish current Account authority, or + * grant lifecycle activation or gameplay admission. The transport endpoint owns workload + * authentication; the consumer must keep admission and its current-authority checks separate. + */ +public record WorldCanonicalInstanceLifecycleEvidence( + Request request, + CompleteLaunchBindingEvidence launchBinding, + RoomTemplateRef startLocation, + long runtimeRoomInstanceId, + String lifecycleStatus, + long lifecycleEpoch, + long rowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest, + Map operationalRegionAssignments) { + public static final String SCHEMA = "world-canonical-instance-lifecycle-evidence/v1"; + public static final String REQUEST_SCHEMA = "world-canonical-instance-lifecycle-read-request/v1"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern BARE_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set EVIDENCE_FIELDS = + Set.of( + "schema", + "request", + "launchBindingBytesBase64", + "startLocation", + "runtimeRoomInstanceId", + "lifecycleStatus", + "lifecycleEpoch", + "rowVersion", + "captureId", + "graphSha256", + "preparationInputDigest", + "operationalRegionAssignments"); + private static final Set REQUEST_FIELDS = + Set.of( + "schemaVersion", + "readRequestId", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "canonicalGameInstanceId", + "playableStateNamespaceId", + "playableStateScope", + "publicProduction", + "controlPlaneRequestId", + "canonicalVersionId", + "expectedDescriptorRequestDigest", + "expectedDescriptorResultDigest", + "expectedReleaseAttestationDigest"); + private static final Set REQUEST_ENVELOPE_FIELDS = Set.of("schema", "request"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final Set LIFECYCLE_STATUSES = + Set.of("PREPARING", "ACTIVE", "FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + + public WorldCanonicalInstanceLifecycleEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(launchBinding, "launchBinding"); + Objects.requireNonNull(startLocation, "startLocation"); + if (runtimeRoomInstanceId <= 0) { + throw new IllegalArgumentException("runtimeRoomInstanceId must be positive"); + } + if (lifecycleStatus == null || !LIFECYCLE_STATUSES.contains(lifecycleStatus)) { + throw new IllegalArgumentException("Unsupported World lifecycle status"); + } + if (lifecycleEpoch <= 0) { + throw new IllegalArgumentException("World lifecycleEpoch must be positive"); + } + if (rowVersion < 0) { + throw new IllegalArgumentException("World lifecycle rowVersion must be nonnegative"); + } + requireNonNil(captureId, "captureId"); + requireDigest(graphSha256, BARE_SHA256, "graphSha256"); + requireDigest(preparationInputDigest, PREFIXED_SHA256, "preparationInputDigest"); + operationalRegionAssignments = + immutableOperationalRegionAssignments(operationalRegionAssignments); + requireExactBinding(request, launchBinding, startLocation, graphSha256); + } + + /** Returns an immutable ordered copy without exposing the retained map representation. */ + @Override + public Map operationalRegionAssignments() { + return Collections.unmodifiableMap(new LinkedHashMap<>(operationalRegionAssignments)); + } + + /** Closed canonical representation with the complete descriptor and separate attestation. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("request", requestJson(request)); + value.put( + "launchBindingBytesBase64", + Base64.getEncoder().encodeToString(closedLaunchBindingBytes(launchBinding))); + value.put("startLocation", roomTemplateRefJson(startLocation)); + value.put("runtimeRoomInstanceId", Long.toString(runtimeRoomInstanceId)); + value.put("lifecycleStatus", lifecycleStatus); + value.put("lifecycleEpoch", Long.toString(lifecycleEpoch)); + value.put("rowVersion", Long.toString(rowVersion)); + value.put("captureId", captureId.toString()); + value.put("graphSha256", graphSha256); + value.put("preparationInputDigest", preparationInputDigest); + value.put( + "operationalRegionAssignments", + operationalRegionAssignmentsJson(operationalRegionAssignments)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World canonical lifecycle evidence cannot be encoded", impossible); + } + } + + /** Decodes closed retained bytes; this does not authenticate the producing World workload. */ + public static WorldCanonicalInstanceLifecycleEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, EVIDENCE_FIELDS, "World canonical lifecycle evidence"); + if (!SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported World canonical lifecycle evidence schema"); + } + Request request = parseRequest(root.get("request")); + CompleteLaunchBindingEvidence launchBinding = + parseLaunchBinding(base64(root, "launchBindingBytesBase64")); + WorldCanonicalInstanceLifecycleEvidence evidence = + new WorldCanonicalInstanceLifecycleEvidence( + request, + launchBinding, + parseRoomTemplateRef(root.get("startLocation")), + positiveLong(text(root, "runtimeRoomInstanceId"), "runtimeRoomInstanceId"), + text(root, "lifecycleStatus"), + positiveLong(text(root, "lifecycleEpoch"), "lifecycleEpoch"), + nonNegativeLong(text(root, "rowVersion"), "rowVersion"), + parseUuid(text(root, "captureId"), "captureId"), + text(root, "graphSha256"), + text(root, "preparationInputDigest"), + parseOperationalRegionAssignments(root.get("operationalRegionAssignments"))); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("World canonical lifecycle evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World canonical lifecycle evidence is invalid", invalid); + } + } + + private static void requireExactBinding( + Request request, + CompleteLaunchBindingEvidence binding, + RoomTemplateRef startLocation, + String graphSha256) { + AuthoredWorldLaunchDescriptorEvidence descriptor = binding.descriptor(); + AuthoredWorldReleaseAttestationEvidence release = binding.releaseAttestation(); + descriptor.requireValid(); + release.requireValid(descriptor); + if (!request.targetNamespace().equals(descriptor.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.worldSlug().equals(descriptor.worldSlug()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request.expectedReleaseAttestationDigest().equals(release.evidenceDigest()) + || !request.canonicalVersionId().equals(release.canonicalVersionId())) { + throw new IllegalArgumentException( + "World lifecycle request differs from the complete launch binding"); + } + if (!AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + release.schemaVersion()) + || release.worldStartLocationEvidence() == null) { + throw new IllegalArgumentException( + "World lifecycle evidence requires complete selected-release selector evidence"); + } + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored( + release.worldStartLocationEvidence().selectorReceiptBytes()); + String selectedGraphSha256 = selectorReceipt.graphDigest().substring("sha256:".length()); + if (!selectorReceipt.startLocation().equals(startLocation) + || !selectedGraphSha256.equals(graphSha256)) { + throw new IllegalArgumentException( + "World lifecycle ROOM selector or graph digest differs from the complete release selector"); + } + } + + private static byte[] closedLaunchBindingBytes(CompleteLaunchBindingEvidence binding) { + try { + // Preserve every original descriptor/release value, including long numeric fields, inside + // the opaque outer base64 envelope instead of subjecting those owner bytes to RFC 8785's + // JavaScript-number range. + return JSON.writeValueAsString(binding).getBytes(StandardCharsets.UTF_8); + } catch (tools.jackson.core.JacksonException impossible) { + throw new IllegalStateException("Complete launch binding cannot be encoded", impossible); + } + } + + private static CompleteLaunchBindingEvidence parseLaunchBinding(byte[] stored) { + try { + JsonNode node = JSON.readTree(strictUtf8(stored)); + requireFields(node, Set.of("descriptor", "releaseAttestation"), "complete launch binding"); + CompleteLaunchBindingEvidence binding = + JSON.treeToValue(node, CompleteLaunchBindingEvidence.class); + if (!Arrays.equals(stored, closedLaunchBindingBytes(binding))) { + throw new IllegalArgumentException( + "Nested complete launch binding bytes are not canonical"); + } + return binding; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException( + "Nested complete launch binding bytes are invalid", invalid); + } + } + + private static Request parseRequest(JsonNode node) { + requireFields(node, REQUEST_FIELDS, "World canonical lifecycle request"); + JsonNode publicProduction = node.get("publicProduction"); + if (publicProduction == null || !publicProduction.isBoolean()) { + throw new IllegalArgumentException("publicProduction must be present as a boolean"); + } + return new Request( + intValue(node, "schemaVersion"), + parseUuid(text(node, "readRequestId"), "readRequestId"), + text(node, "targetNamespace"), + parseUuid(text(node, "canonicalTenantId"), "canonicalTenantId"), + text(node, "worldSlug"), + parseUuid(text(node, "canonicalGameInstanceId"), "canonicalGameInstanceId"), + parseUuid(text(node, "playableStateNamespaceId"), "playableStateNamespaceId"), + text(node, "playableStateScope"), + publicProduction.booleanValue(), + text(node, "controlPlaneRequestId"), + parseUuid(text(node, "canonicalVersionId"), "canonicalVersionId"), + text(node, "expectedDescriptorRequestDigest"), + text(node, "expectedDescriptorResultDigest"), + text(node, "expectedReleaseAttestationDigest")); + } + + private static RoomTemplateRef parseRoomTemplateRef(JsonNode node) { + requireFields(node, ROOM_TEMPLATE_REF_FIELDS, "World lifecycle startLocation"); + return new RoomTemplateRef( + parseUuid(text(node, "tenantId"), "startLocation.tenantId"), + parseUuid(text(node, "versionId"), "startLocation.versionId"), + parseUuid(text(node, "roomTemplateId"), "startLocation.roomTemplateId")); + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("schemaVersion", request.schemaVersion()); + value.put("readRequestId", request.readRequestId().toString()); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("worldSlug", request.worldSlug()); + value.put("canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + value.put("playableStateNamespaceId", request.playableStateNamespaceId().toString()); + value.put("playableStateScope", request.playableStateScope()); + value.put("publicProduction", request.publicProduction()); + value.put("controlPlaneRequestId", request.controlPlaneRequestId()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("expectedDescriptorRequestDigest", request.expectedDescriptorRequestDigest()); + value.put("expectedDescriptorResultDigest", request.expectedDescriptorResultDigest()); + value.put("expectedReleaseAttestationDigest", request.expectedReleaseAttestationDigest()); + return value; + } + + private static Map roomTemplateRefJson(RoomTemplateRef reference) { + Map value = new LinkedHashMap<>(); + value.put("tenantId", reference.tenantId().toString()); + value.put("versionId", reference.versionId().toString()); + value.put("roomTemplateId", reference.roomTemplateId().toString()); + return value; + } + + private static Map operationalRegionAssignmentsJson(Map assignments) { + Map value = new LinkedHashMap<>(); + assignments.entrySet().stream() + .sorted((left, right) -> left.getKey().toString().compareTo(right.getKey().toString())) + .forEach(entry -> value.put(entry.getKey().toString(), entry.getValue().toString())); + return value; + } + + private static Map parseOperationalRegionAssignments(JsonNode node) { + if (node == null || !node.isObject() || node.size() == 0) { + throw new IllegalArgumentException("operationalRegionAssignments must be a nonempty object"); + } + Map assignments = new LinkedHashMap<>(); + node.propertyNames() + .forEach( + canonicalRegionId -> { + JsonNode operationalRegion = node.get(canonicalRegionId); + if (operationalRegion == null || !operationalRegion.isTextual()) { + throw new IllegalArgumentException( + "operationalRegionAssignments values must be canonical UUID strings"); + } + UUID canonical = parseUuid(canonicalRegionId, "operationalRegionAssignments key"); + UUID operational = + parseUuid(operationalRegion.textValue(), "operationalRegionAssignments value"); + if (assignments.putIfAbsent(canonical, operational) != null) { + throw new IllegalArgumentException( + "operationalRegionAssignments contains duplicate canonical region identities"); + } + }); + return immutableOperationalRegionAssignments(assignments); + } + + private static Map immutableOperationalRegionAssignments( + Map assignments) { + Objects.requireNonNull(assignments, "operationalRegionAssignments"); + if (assignments.isEmpty()) { + throw new IllegalArgumentException("operationalRegionAssignments must be nonempty"); + } + assignments.forEach( + (canonical, operational) -> { + requireNonNil(canonical, "operationalRegionAssignments canonical region ID"); + requireNonNil(operational, "operationalRegionAssignments operational region ID"); + }); + Map ordered = new LinkedHashMap<>(); + Set operationalIdentities = new HashSet<>(); + assignments.entrySet().stream() + .sorted((left, right) -> left.getKey().toString().compareTo(right.getKey().toString())) + .forEach( + entry -> { + UUID canonical = entry.getKey(); + UUID operational = entry.getValue(); + if (canonical.equals(operational)) { + throw new IllegalArgumentException( + "Canonical and operational region identities must be distinct"); + } + if (!operationalIdentities.add(operational)) { + throw new IllegalArgumentException( + "operationalRegionAssignments contains duplicate operational region identities"); + } + ordered.put(canonical, operational); + }); + return Collections.unmodifiableMap(ordered); + } + + private static byte[] base64(JsonNode node, String field) { + try { + return Base64.getDecoder().decode(text(node, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid base64 field " + field, invalid); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + return value.textValue(); + } + + private static int intValue(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException(field + " must be an integer"); + } + return value.intValue(); + } + + private static long positiveLong(String value, String field) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static long nonNegativeLong(String value, String field) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical nonnegative decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "Canonical World lifecycle bytes are not strict UTF-8", invalid); + } + } + + private static UUID parseUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, Pattern pattern, String label) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is not a canonical SHA-256 digest"); + } + } + + private static void requireFields(JsonNode object, Set fields, String label) { + if (object == null || !object.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + Set actual = new java.util.HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + /** Exact shared request envelope for the read-only World lifecycle capture. */ + public record Request( + int schemaVersion, + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String playableStateScope, + boolean publicProduction, + String controlPlaneRequestId, + UUID canonicalVersionId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationDigest) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World canonical lifecycle read schema"); + } + requireNonNil(readRequestId, "readRequestId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "This lifecycle carrier accepts SHARED scope only; private/playtest proof is unavailable"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "This lifecycle carrier requires public-production evidence"); + } + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireDigest( + expectedDescriptorRequestDigest, PREFIXED_SHA256, "expectedDescriptorRequestDigest"); + requireDigest( + expectedDescriptorResultDigest, PREFIXED_SHA256, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationDigest, PREFIXED_SHA256, "expectedReleaseAttestationDigest"); + } + + /** Closed canonical request bytes used by the standalone World read RPC. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", REQUEST_SCHEMA); + value.put("request", requestJson(this)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World canonical lifecycle request cannot be encoded", impossible); + } + } + + /** Decodes only a complete closed request; this does not authenticate its sender. */ + public static Request fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, REQUEST_ENVELOPE_FIELDS, "World canonical lifecycle read request"); + if (!REQUEST_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException( + "Unsupported World canonical lifecycle request schema"); + } + Request request = parseRequest(root.get("request")); + if (!Arrays.equals(stored, request.canonicalBytes())) { + throw new IllegalArgumentException("World canonical lifecycle request is not canonical"); + } + return request; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World canonical lifecycle request is invalid", invalid); + } + } + + private static void requireText(String value, String label, int maxLength) { + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(label + " is required and must fit its limit"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java new file mode 100644 index 0000000000..9caf305d68 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; + +/** Closed byte-carrier mapping for the authenticated, read-only World lifecycle RPC. */ +public final class WorldCanonicalInstanceLifecycleGrpcCodec { + private WorldCanonicalInstanceLifecycleGrpcCodec() {} + + /** Encodes the complete closed request as one canonical byte value. */ + public static ReadWorldCanonicalInstanceLifecycleRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + return ReadWorldCanonicalInstanceLifecycleRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFrom(request.canonicalBytes())) + .build(); + } + + /** Decodes only after the World receiver authenticates its exact same-namespace caller. */ + public static Request fromRequest(ReadWorldCanonicalInstanceLifecycleRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadWorldCanonicalInstanceLifecycleRequest"); + if (request.getCanonicalRequestBytes().isEmpty()) { + throw new IllegalArgumentException("World canonical lifecycle request bytes are required"); + } + return Request.fromStored(request.getCanonicalRequestBytes().toByteArray()); + } + + /** Encodes a complete response only when it contains the exact immutable caller request. */ + public static ReadWorldCanonicalInstanceLifecycleResponse toResponse( + Request request, WorldCanonicalInstanceLifecycleEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "World lifecycle evidence differs from exact read request"); + } + return ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(evidence.canonicalBytes())) + .build(); + } + + /** Validates the complete closed response and its exact request echo. */ + public static WorldCanonicalInstanceLifecycleEvidence fromResponse( + Request request, ReadWorldCanonicalInstanceLifecycleResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldCanonicalInstanceLifecycleResponse"); + if (response.getCanonicalResponseBytes().isEmpty()) { + throw new IllegalArgumentException("World canonical lifecycle response bytes are required"); + } + WorldCanonicalInstanceLifecycleEvidence evidence = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + response.getCanonicalResponseBytes().toByteArray()); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException("World lifecycle response changed exact read request"); + } + return evidence; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java new file mode 100644 index 0000000000..682315cc0f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java @@ -0,0 +1,587 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +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 io.grpc.stub.StreamObserver; +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.CertificateEncodingException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +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 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.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; +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; + +/** Physical socket proof for the explicit Game Session to World lifecycle-read transport only. */ +class WorldCanonicalInstanceLifecycleClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_WORLD_URI = + "spiffe://firemud/ns/other-test/sa/world-management-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID READ_REQUEST_ID = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private Server server; + private WorldCanonicalInstanceLifecycleClient client; + private AtomicInteger serverCallStarts; + private AtomicInteger applicationCalls; + private AtomicReference receivedPeerUri; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void exactWorldWorkloadPeerReadsTheCompleteEchoedCaptureOverPhysicalMtls() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + startServer(pki.worldServer(), ResponseMode.EXACT, expected); + client = newClient(server); + client.init(); + + WorldCanonicalInstanceLifecycleEvidence actual = client.read(expected.request()); + + assertThat(actual.canonicalBytes()).containsExactly(expected.canonicalBytes()); + assertThat(serverCallStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + assertThat(receivedPeerUri).hasValue(GAME_SESSION_URI); + } + + @Test + void trustedWrongWorldWorkloadAndNamespaceCannotSendRequestMetadataOrBody() throws Exception { + List wrongPeers = List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer()); + for (TestIdentity wrongPeer : wrongPeers) { + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + startServer(wrongPeer, ResponseMode.EXACT, expected); + client = newClient(server); + client.init(); + + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(serverCallStarts).as(wrongPeer.alias()).hasValue(0); + assertThat(applicationCalls).as(wrongPeer.alias()).hasValue(0); + stopTransport(); + } + } + + @Test + void exactPeerResponseMustEchoTheRequestAndContainAValidCompleteCarrier() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + + startServer(pki.worldServer(), ResponseMode.WRONG_READ_REQUEST_ID, expected); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical instance lifecycle evidence"); + assertThat(serverCallStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + stopTransport(); + + startServer(pki.worldServer(), ResponseMode.MALFORMED_EVIDENCE, expected); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical instance lifecycle evidence"); + assertThat(serverCallStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + } + + @Test + void refusesPlaintextClasspathFilesAndCallsBeforeExplicitInitialization() throws Exception { + serverCallStarts = new AtomicInteger(); + applicationCalls = new AtomicInteger(); + receivedPeerUri = new AtomicReference<>(); + var plaintext = pki.clientProperties(tempDirectory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceLifecycleClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var classpath = pki.clientProperties(tempDirectory); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceLifecycleClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + startServer(pki.worldServer(), ResponseMode.EXACT, expected); + client = newClient(server); + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + assertThat(serverCallStarts).hasValue(0); + assertThat(applicationCalls).hasValue(0); + } + + private void startServer( + TestIdentity identity, + ResponseMode responseMode, + WorldCanonicalInstanceLifecycleEvidence expected) + throws Exception { + serverCallStarts = new AtomicInteger(); + applicationCalls = new AtomicInteger(); + receivedPeerUri = new AtomicReference<>(); + var service = + new WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceImplBase() { + @Override + public void readWorldCanonicalInstanceLifecycle( + ReadWorldCanonicalInstanceLifecycleRequest request, + StreamObserver observer) { + applicationCalls.incrementAndGet(); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + receivedPeerUri.set(peer == null ? null : peer.uri()); + WorldCanonicalInstanceLifecycleEvidence.Request decoded = + WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request); + ReadWorldCanonicalInstanceLifecycleResponse response; + if (responseMode == ResponseMode.MALFORMED_EVIDENCE) { + response = + ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(new byte[] {(byte) 0xff})) + .build(); + } else if (responseMode == ResponseMode.WRONG_READ_REQUEST_ID) { + var changedRequest = + withReadRequestId(decoded, uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")); + var changedEvidence = withRequest(expected, changedRequest); + response = + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse( + changedRequest, changedEvidence); + } else { + response = WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(decoded, expected); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countApplicationHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + serverCallStarts.incrementAndGet(); + return next.startCall(call, headers); + } + }; + server = + 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( + service, countApplicationHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private WorldCanonicalInstanceLifecycleClient newClient(Server target) + throws IOException, CertificateEncodingException { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + target.getPort()); + return new WorldCanonicalInstanceLifecycleClient( + endpoints, pki.clientProperties(tempDirectory), new GrpcChannelFactory(), NAMESPACE); + } + + private static WorldCanonicalInstanceLifecycleEvidence evidence( + String status, long epoch, long rowVersion, UUID readRequestId) throws Exception { + WorldPublishedStartLocationEvidence selector = + AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldReleaseAttestationSelectorTest.descriptor(selector); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationSelectorTest.release(descriptor, selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + RoomTemplateRef startLocation = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()).startLocation(); + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + readRequestId, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 9_007_199_254_740_993L, + status, + epoch, + rowVersion, + uuid("33333333-3333-4333-8333-333333333333"), + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) + .graphDigest() + .substring("sha256:".length()), + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + + private static WorldCanonicalInstanceLifecycleEvidence withRequest( + WorldCanonicalInstanceLifecycleEvidence evidence, + WorldCanonicalInstanceLifecycleEvidence.Request request) { + return new WorldCanonicalInstanceLifecycleEvidence( + request, + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest(), + evidence.operationalRegionAssignments()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request withReadRequestId( + WorldCanonicalInstanceLifecycleEvidence.Request source, UUID readRequestId) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + source.schemaVersion(), + readRequestId, + source.targetNamespace(), + source.canonicalTenantId(), + source.worldSlug(), + source.canonicalGameInstanceId(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.publicProduction(), + source.controlPlaneRequestId(), + source.canonicalVersionId(), + source.expectedDescriptorRequestDigest(), + source.expectedDescriptorResultDigest(), + source.expectedReleaseAttestationDigest()); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private enum ResponseMode { + EXACT, + WRONG_READ_REQUEST_ID, + MALFORMED_EVIDENCE + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity worldServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity gameSessionClient) { + 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 lifecycle 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"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "world-server", WORLD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-workload-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-namespace-server", OTHER_WORLD_URI, true), + issueIdentity( + directory, caStore, caFile, "game-session-client", GAME_SESSION_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) + throws IOException, CertificateEncodingException { + Path clientCertificate = + writePem( + directory.resolve("game-session-client.crt"), + "CERTIFICATE", + gameSessionClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-session-client.key"), + "PRIVATE KEY", + gameSessionClient.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + 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"); + var command = new java.util.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", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java new file mode 100644 index 0000000000..247b555611 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java @@ -0,0 +1,879 @@ +package net.firedevops.firemud.common.world; + +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.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInstanceLifecycleEvidenceTest { + private static final UUID NIL = new UUID(0L, 0L); + + @Test + void completeOwnerCaptureAndExactRequestEchoRoundTrip() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = evidence(); + Request request = expected.request(); + + assertThat(Request.fromStored(request.canonicalBytes())).isEqualTo(request); + var wireRequest = WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request); + assertThat(WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(request); + + var firstResponse = WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(request, expected); + var retryResponse = WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(request, expected); + assertThat(retryResponse).isEqualTo(firstResponse); + var decoded = WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(request, firstResponse); + var reread = WorldCanonicalInstanceLifecycleEvidence.fromStored(decoded.canonicalBytes()); + assertThat(decoded.canonicalBytes()).containsExactly(expected.canonicalBytes()); + assertThat(reread).isEqualTo(expected); + assertThat(reread.hashCode()).isEqualTo(expected.hashCode()); + assertThat(reread.operationalRegionAssignments()) + .containsExactlyEntriesOf(expected.operationalRegionAssignments()); + } + + @Test + void rejectsMalformedOperationalRegionAssignmentMapsAndFreezesCallerInput() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + UUID canonicalRegionId = uuid("abcdefab-cdef-4abc-8def-abcdefabcdef"); + UUID operationalRegionId = uuid("22222222-2222-4222-8222-222222222222"); + Map mutableAssignments = new java.util.LinkedHashMap<>(); + mutableAssignments.put(canonicalRegionId, operationalRegionId); + var frozen = + new WorldCanonicalInstanceLifecycleEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest(), + mutableAssignments); + mutableAssignments.clear(); + assertThat(frozen.operationalRegionAssignments()) + .containsExactlyEntriesOf(Map.of(canonicalRegionId, operationalRegionId)); + assertThatThrownBy( + () -> frozen.operationalRegionAssignments().put(canonicalRegionId, operationalRegionId)) + .isInstanceOf(UnsupportedOperationException.class); + + UUID secondCanonicalRegionId = uuid("44444444-4444-4444-8444-444444444444"); + UUID secondOperationalRegionId = uuid("55555555-5555-4555-8555-555555555555"); + Map forward = new java.util.LinkedHashMap<>(); + forward.put(canonicalRegionId, operationalRegionId); + forward.put(secondCanonicalRegionId, secondOperationalRegionId); + Map reverse = new java.util.LinkedHashMap<>(); + reverse.put(secondCanonicalRegionId, secondOperationalRegionId); + reverse.put(canonicalRegionId, operationalRegionId); + assertThat(withAssignments(evidence, forward).canonicalBytes()) + .containsExactly(withAssignments(evidence, reverse).canonicalBytes()); + + String stored = new String(frozen.canonicalBytes(), StandardCharsets.UTF_8); + String assignmentField = + "\"operationalRegionAssignments\":{\"" + + canonicalRegionId + + "\":\"" + + operationalRegionId + + "\"}"; + assertThat(stored).contains(assignmentField); + String legacyShape = stored.replace("," + assignmentField, ""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + legacyShape.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing or unsupported fields"); + assertInvalidStoredAssignments(stored, assignmentField, "{}", "nonempty"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"00000000-0000-0000-0000-000000000000\":\"" + operationalRegionId + "\"}", + "non-nil UUID"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + canonicalRegionId + "\":\"00000000-0000-0000-0000-000000000000\"}", + "non-nil UUID"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + canonicalRegionId + "\":\"" + canonicalRegionId + "\"}", + "must be distinct"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + canonicalRegionId.toString().toUpperCase() + "\":\"" + operationalRegionId + "\"}", + "canonical non-nil UUID"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + + canonicalRegionId + + "\":\"" + + operationalRegionId + + "\",\"" + + canonicalRegionId + + "\":\"" + + uuid("33333333-3333-4333-8333-333333333333") + + "\"}", + "invalid"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + + canonicalRegionId + + "\":\"" + + operationalRegionId + + "\",\"" + + uuid("44444444-4444-4444-8444-444444444444") + + "\":\"" + + operationalRegionId + + "\"}", + "duplicate operational region identities"); + } + + @Test + void rejectsChangedCanonicalIdentitiesAndEveryExpectedBindingDigest() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + Request request = evidence.request(); + var changedInstance = + copyRequest( + request, + request.readRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + uuid("99999999-9999-4999-8999-999999999999"), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.controlPlaneRequestId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest()); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse( + changedInstance, + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(request, evidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed exact read request"); + + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "1".repeat(64), + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + uuid("66666666-6666-4666-8666-666666666666"), + null, + null, + null, + null, + null, + null, + null, + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, null, null, "another-world", null, null, null, null, null, null, null, null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + "other-control-request", + null, + null, + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + uuid("88888888-8888-4888-8888-888888888888"), + null, + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "2".repeat(64), + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "3".repeat(64), + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "4".repeat(64)), + "complete launch binding"); + + var changedSelector = + new RoomTemplateRef( + evidence.startLocation().tenantId(), + evidence.startLocation().versionId(), + uuid("66666666-6666-4666-8666-666666666666")); + assertThatThrownBy( + () -> + with( + evidence, + request, + evidence.launchBinding(), + changedSelector, + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("release selector"); + assertThatThrownBy( + () -> + with( + evidence, + request, + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + "f".repeat(64), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graph digest"); + } + + @Test + void rejectsUnselectedV1ReleaseAndMalformedLifecycleCountersOrDigests() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + var request = evidence.request(); + var descriptor = evidence.launchBinding().descriptor(); + var release = evidence.launchBinding().releaseAttestation(); + // Independent retained-v1 fixture; its GD digest is not the selected-v2 content hash. + var v1Participants = + release.participantDigests().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? "e".repeat(64) + : participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant.participantKey(), + AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) + .toList(); + var v1Release = + AuthoredWorldReleaseAttestationEvidence.create( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + release.publishWorkflowId(), + release.commitId(), + v1Participants, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision()); + var v1Request = + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + v1Release.evidenceDigest()); + assertThatThrownBy( + () -> + with( + evidence, + v1Request, + new CompleteLaunchBindingEvidence(descriptor, v1Release), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete selected-release selector evidence"); + + assertInvalid(evidence, evidence.runtimeRoomInstanceId(), evidence.lifecycleEpoch(), -1); + assertInvalid(evidence, evidence.runtimeRoomInstanceId(), 0, evidence.rowVersion()); + assertInvalid(evidence, 0, evidence.lifecycleEpoch(), evidence.rowVersion()); + assertThatThrownBy( + () -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + NIL, + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("captureId"); + assertThatThrownBy( + () -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + "A".repeat(64), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graphSha256"); + } + + @Test + void requestOnlyAcceptsProvedSharedPublicProductionIdentity() throws Exception { + Request request = evidence().request(); + assertThatThrownBy( + () -> + copyRequest( + request, NIL, null, null, null, null, null, null, null, null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("readRequestId"); + assertThatThrownBy( + () -> + copyRequest( + request, + null, + null, + null, + null, + null, + "ISOLATED", + null, + null, + null, + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SHARED scope only"); + assertThatThrownBy( + () -> + new Request( + request.schemaVersion(), + request.readRequestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + false, + request.controlPlaneRequestId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("public-production evidence"); + assertThatThrownBy( + () -> + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + "not-a-digest", + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("expectedDescriptorRequestDigest"); + } + + @Test + void preservesLongPrecisionAndRejectsOverflowOrNoncanonicalDecimalStrings() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = evidence(); + long beyondJavaScriptInteger = 9_007_199_254_740_993L; + WorldCanonicalInstanceLifecycleEvidence precise = + with( + expected, + expected.request(), + expected.launchBinding(), + expected.startLocation(), + beyondJavaScriptInteger, + expected.lifecycleStatus(), + beyondJavaScriptInteger + 2, + beyondJavaScriptInteger + 4, + expected.captureId(), + expected.graphSha256(), + expected.preparationInputDigest()); + assertThat(WorldCanonicalInstanceLifecycleEvidence.fromStored(precise.canonicalBytes())) + .isEqualTo(precise); + + WorldCanonicalInstanceLifecycleEvidence maximum = + with( + expected, + expected.request(), + expected.launchBinding(), + expected.startLocation(), + Long.MAX_VALUE, + expected.lifecycleStatus(), + Long.MAX_VALUE, + Long.MAX_VALUE, + expected.captureId(), + expected.graphSha256(), + expected.preparationInputDigest()); + byte[] maxBytes = maximum.canonicalBytes(); + assertThat(WorldCanonicalInstanceLifecycleEvidence.fromStored(maxBytes)).isEqualTo(maximum); + String maxJson = new String(maxBytes, StandardCharsets.UTF_8); + String overflow = + maxJson.replace( + "\"runtimeRoomInstanceId\":\"" + Long.MAX_VALUE + "\"", + "\"runtimeRoomInstanceId\":\"9223372036854775808\""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + overflow.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("supported integer range"); + String negative = + maxJson.replace( + "\"lifecycleEpoch\":\"" + Long.MAX_VALUE + "\"", "\"lifecycleEpoch\":\"-1\""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + negative.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical positive decimal"); + String leadingZero = + maxJson.replace("\"rowVersion\":\"" + Long.MAX_VALUE + "\"", "\"rowVersion\":\"01\""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + leadingZero.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical nonnegative decimal"); + } + + @Test + void rejectsClosedJsonAndProtobufUnknownOrDuplicateFields() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + String stored = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); + String unknownField = stored.substring(0, 1) + "\"unsupported\":true," + stored.substring(1); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + unknownField.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + String duplicate = + stored.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + duplicate.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> Request.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strict UTF-8"); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strict UTF-8"); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + ReadWorldCanonicalInstanceLifecycleRequest request = + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(evidence.request()).toBuilder() + .setUnknownFields(unknown) + .build(); + assertThatThrownBy(() -> WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + ReadWorldCanonicalInstanceLifecycleResponse response = + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(evidence.request(), evidence) + .toBuilder() + .setUnknownFields(unknown) + .build(); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(evidence.request(), response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse( + evidence.request(), + ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.EMPTY) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("required"); + } + + private static void assertRejectedRequest( + WorldCanonicalInstanceLifecycleEvidence evidence, Request changed, String message) { + assertThatThrownBy( + () -> + with( + evidence, + changed, + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(message); + } + + private static void assertInvalid( + WorldCanonicalInstanceLifecycleEvidence evidence, + long runtimeRoomInstanceId, + long lifecycleEpoch, + long rowVersion) { + assertThatThrownBy( + () -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + runtimeRoomInstanceId, + evidence.lifecycleStatus(), + lifecycleEpoch, + rowVersion, + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldCanonicalInstanceLifecycleEvidence with( + WorldCanonicalInstanceLifecycleEvidence source, + Request request, + CompleteLaunchBindingEvidence launchBinding, + RoomTemplateRef startLocation, + long runtimeRoomInstanceId, + String lifecycleStatus, + long lifecycleEpoch, + long rowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest) { + return new WorldCanonicalInstanceLifecycleEvidence( + request, + launchBinding, + startLocation, + runtimeRoomInstanceId, + lifecycleStatus, + lifecycleEpoch, + rowVersion, + captureId, + graphSha256, + preparationInputDigest, + source.operationalRegionAssignments()); + } + + private static Request copyRequest( + Request source, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String playableStateScope, + String controlPlaneRequestId, + UUID canonicalVersionId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationDigest) { + return new Request( + Request.SCHEMA_VERSION, + readRequestId == null ? source.readRequestId() : readRequestId, + source.targetNamespace(), + canonicalTenantId == null ? source.canonicalTenantId() : canonicalTenantId, + worldSlug == null ? source.worldSlug() : worldSlug, + canonicalGameInstanceId == null + ? source.canonicalGameInstanceId() + : canonicalGameInstanceId, + playableStateNamespaceId == null + ? source.playableStateNamespaceId() + : playableStateNamespaceId, + playableStateScope == null ? source.playableStateScope() : playableStateScope, + source.publicProduction(), + controlPlaneRequestId == null ? source.controlPlaneRequestId() : controlPlaneRequestId, + canonicalVersionId == null ? source.canonicalVersionId() : canonicalVersionId, + expectedDescriptorRequestDigest == null + ? source.expectedDescriptorRequestDigest() + : expectedDescriptorRequestDigest, + expectedDescriptorResultDigest == null + ? source.expectedDescriptorResultDigest() + : expectedDescriptorResultDigest, + expectedReleaseAttestationDigest == null + ? source.expectedReleaseAttestationDigest() + : expectedReleaseAttestationDigest); + } + + private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Exception { + WorldPublishedStartLocationEvidence selector = + WorldPublishedStartLocationGrpcCodecTest.evidence(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + RoomTemplateRef startLocation = selectorReceipt.startLocation(); + Request request = + new Request( + Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 1042L, + "PREPARING", + 3L, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64), + Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + + private static void assertInvalidStoredAssignments( + String stored, String assignmentField, String replacement, String message) { + String malformed = + stored.replace(assignmentField, "\"operationalRegionAssignments\":" + replacement); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + malformed.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(message); + } + + private static WorldCanonicalInstanceLifecycleEvidence withAssignments( + WorldCanonicalInstanceLifecycleEvidence source, Map assignments) { + return new WorldCanonicalInstanceLifecycleEvidence( + source.request(), + source.launchBinding(), + source.startLocation(), + source.runtimeRoomInstanceId(), + source.lifecycleStatus(), + source.lifecycleEpoch(), + source.rowVersion(), + source.captureId(), + source.graphSha256(), + source.preparationInputDigest(), + assignments); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java new file mode 100644 index 0000000000..2e69052bc5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java @@ -0,0 +1,267 @@ +package net.firedevops.firemud.gamesession.client; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +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.UUID; +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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit Game Session mTLS client for World initial-admission hold identity operations. */ +public final class WorldCanonicalInitialAdmissionHoldClient + extends AbstractReloadingBlockingGrpcClient< + WorldCanonicalInitialAdmissionHoldServiceGrpc + .WorldCanonicalInitialAdmissionHoldServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldCanonicalInitialAdmissionHoldClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldCanonicalInitialAdmissionHoldClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Opens its managed channel only when the owning Game Session workflow explicitly starts it. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World initial-admission hold client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World initial-admission hold client has no gRPC stub"); + } + initialized = true; + } + + /** + * Acquires the exact request once and returns only World's immutable issued identity. This call + * does not retry or create a new initial-admission request identity. + */ + public HoldIdentity acquire( + Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + requireNoAmbientOwnerTransaction(); + requireConfiguredNamespace(holdRequest); + requireLifecycleRequestMatches(holdRequest, lifecycleRequest); + + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .acquireCanonicalInitialAdmissionHold( + AcquireCanonicalInitialAdmissionHoldRequest.newBuilder() + .setCanonicalHoldRequestBytes( + ByteString.copyFrom(holdRequest.canonicalRequestBytes())) + .setCanonicalLifecycleReadRequestBytes( + ByteString.copyFrom(lifecycleRequest.canonicalBytes())) + .build()); + try { + requireNoUnknownFields(response, "AcquireCanonicalInitialAdmissionHoldResponse"); + HoldIdentity identity = decodeIdentity(response.getHoldIdentityBytes().toByteArray()); + requireExactRequest(holdRequest, identity); + return identity; + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid canonical initial-admission hold identity", invalid); + } + } + + /** + * Reads the historical immutable acquisition identity using a fresh correlation UUID. The result + * is not evidence of a live hold, terminal hold state, or gameplay admission. + */ + public HoldIdentity readIdentity(Request holdRequest) { + requireNoAmbientOwnerTransaction(); + requireConfiguredNamespace(holdRequest); + UUID readRequestId = UUID.randomUUID(); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readCanonicalInitialAdmissionHoldIdentity( + ReadCanonicalInitialAdmissionHoldIdentityRequest.newBuilder() + .setReadRequestId(readRequestId.toString()) + .setCanonicalHoldRequestBytes( + ByteString.copyFrom(holdRequest.canonicalRequestBytes())) + .build()); + try { + requireNoUnknownFields(response, "ReadCanonicalInitialAdmissionHoldIdentityResponse"); + if (!readRequestId.toString().equals(response.getReadRequestId())) { + throw new IllegalArgumentException( + "World initial-admission identity read changed its correlation UUID"); + } + HoldIdentity identity = decodeIdentity(response.getHoldIdentityBytes().toByteArray()); + requireExactRequest(holdRequest, identity); + return identity; + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid historical initial-admission hold identity", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldCanonicalInitialAdmissionHoldServiceGrpc + .WorldCanonicalInitialAdmissionHoldServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldCanonicalInitialAdmissionHoldServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldCanonicalInitialAdmissionHoldServiceGrpc + .WorldCanonicalInitialAdmissionHoldServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World initial-admission hold client is not initialized and available"); + } + return currentStub; + } + + private void requireConfiguredNamespace(Request request) { + Objects.requireNonNull(request, "holdRequest"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World initial-admission hold request must use the configured workload namespace"); + } + } + + private void requireLifecycleRequestMatches( + Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); + if (!lifecycleRequest.publicProduction()) { + throw new IllegalArgumentException( + "World initial-admission hold acquisition requires public-production lifecycle evidence"); + } + if (!workloadNamespace.equals(lifecycleRequest.targetNamespace()) + || !holdRequest.canonicalTenantId().equals(lifecycleRequest.canonicalTenantId()) + || !holdRequest.worldSlug().equals(lifecycleRequest.worldSlug()) + || !holdRequest.canonicalGameInstanceId().equals(lifecycleRequest.canonicalGameInstanceId()) + || !holdRequest + .playableStateNamespaceId() + .equals(lifecycleRequest.playableStateNamespaceId()) + || !holdRequest.playableStateScope().equals(lifecycleRequest.playableStateScope()) + || !holdRequest.canonicalVersionId().equals(lifecycleRequest.canonicalVersionId())) { + throw new IllegalArgumentException( + "World lifecycle request must bind the exact initial-admission target"); + } + } + + private static HoldIdentity decodeIdentity(byte[] encoded) { + if (encoded.length == 0) { + throw new IllegalArgumentException( + "World initial-admission hold identity bytes are required"); + } + return WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(encoded); + } + + private static void requireExactRequest(Request request, HoldIdentity identity) { + if (!request.equals(identity.request())) { + throw new IllegalArgumentException( + "World initial-admission hold identity changed the exact request"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static void requireNoAmbientOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World initial-admission hold calls require no ambient owner transaction"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "World initial-admission hold calls require 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( + "World initial-admission hold calls require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World initial-admission hold calls require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World initial-admission hold " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World initial-admission hold " + label + " must be an existing readable file"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionIntentSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionIntentSnapshot.java new file mode 100644 index 0000000000..1d3a995898 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionIntentSnapshot.java @@ -0,0 +1,226 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; + +/** + * Immutable readback of Game Session's pre-hold initial-admission intent. + * + *

The state is the durable intent row state only. Neither the historical World hold identity nor + * this snapshot proves a live World hold, lifecycle currentness, or gameplay admission. + */ +public record CanonicalInitialAdmissionIntentSnapshot( + Request holdRequest, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, + IntentState state, + HoldIdentity holdIdentity, + SourceBinding sourceBinding, + Instant createdAt, + Instant updatedAt, + Instant terminalAt) { + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + public enum IntentState { + PENDING_HOLD, + HOLD_ATTACHED, + TERMINAL + } + + public CanonicalInitialAdmissionIntentSnapshot { + Objects.requireNonNull(holdRequest, "holdRequest"); + Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); + Objects.requireNonNull(state, "state"); + Objects.requireNonNull(sourceBinding, "sourceBinding"); + Objects.requireNonNull(createdAt, "createdAt"); + Objects.requireNonNull(updatedAt, "updatedAt"); + requireExactBinding(holdRequest, lifecycleRequest, sourceBinding); + if (holdIdentity != null + && !java.util.Arrays.equals( + holdRequest.canonicalRequestBytes(), holdIdentity.canonicalRequestBytes())) { + throw new IllegalArgumentException( + "Attached World hold identity does not echo the retained canonical request"); + } + switch (state) { + case PENDING_HOLD -> { + if (holdIdentity != null || terminalAt != null) { + throw new IllegalArgumentException( + "Pending hold intent cannot contain attached identity"); + } + } + case HOLD_ATTACHED -> { + if (holdIdentity == null || terminalAt != null) { + throw new IllegalArgumentException("Attached hold intent requires only its identity"); + } + } + case TERMINAL -> { + if (holdIdentity == null || terminalAt == null) { + throw new IllegalArgumentException("Terminal intent requires identity and terminal time"); + } + } + } + } + + /** Exact owner fields retained beside the canonical World request bytes. */ + public record SourceBinding( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + boolean catalogVisible, + boolean catalogPublicProduction, + long catalogRevision, + UUID catalogCreationRequestId, + String catalogRequestDigest, + String catalogReceiptDigest, + UUID tenantAssociationOperationId, + long gameSessionTenantId, + UUID canonicalGameInstanceId, + long gameInstanceId, + UUID canonicalVersionId, + long runtimeVersionId, + String controlPlaneRequestId, + String launchDescriptorId, + long capturedStartingRowVersion, + long currentRowVersion, + String descriptorRequestDigest, + String descriptorResultDigest, + String releaseAttestationDigest) { + public SourceBinding { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + requireNonNil(realmId, "realmId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException("Initial admission intent requires SHARED scope"); + } + if (!catalogVisible || !catalogPublicProduction || catalogRevision <= 0) { + throw new IllegalArgumentException( + "Initial admission intent requires the exact visible public catalog source"); + } + requireNonNil(catalogCreationRequestId, "catalogCreationRequestId"); + requireDigest(catalogRequestDigest, PREFIXED_SHA256, "catalogRequestDigest"); + requireDigest(catalogReceiptDigest, PREFIXED_SHA256, "catalogReceiptDigest"); + requireNonNil(tenantAssociationOperationId, "tenantAssociationOperationId"); + requirePositive(gameSessionTenantId, "gameSessionTenantId"); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requirePositive(gameInstanceId, "gameInstanceId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requirePositive(runtimeVersionId, "runtimeVersionId"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 255); + if (capturedStartingRowVersion < 0 || currentRowVersion < capturedStartingRowVersion) { + throw new IllegalArgumentException("Launch row versions are invalid"); + } + requireDigest(descriptorRequestDigest, PREFIXED_SHA256, "descriptorRequestDigest"); + requireDigest(descriptorResultDigest, PREFIXED_SHA256, "descriptorResultDigest"); + requireDigest(releaseAttestationDigest, PREFIXED_SHA256, "releaseAttestationDigest"); + } + } + + /** Checks every request selector and digest against the immutable locked owner snapshots. */ + public static void requireExactBinding( + Request holdRequest, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, + SourceBinding source) { + Objects.requireNonNull(holdRequest, "holdRequest"); + Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); + Objects.requireNonNull(source, "source"); + requireIntentRequestId(holdRequest.initialAdmissionRequestId()); + OriginKind origin = OriginKind.valueOf(holdRequest.initialAdmissionOrigin().name()); + String computedDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + holdRequest.targetNamespace(), + holdRequest.canonicalTenantId(), + holdRequest.worldSlug(), + holdRequest.realmId(), + holdRequest.playableStateNamespaceId(), + holdRequest.playableStateScope(), + holdRequest.canonicalGameInstanceId(), + holdRequest.canonicalVersionId(), + holdRequest.activeLifecycleEpoch(), + holdRequest.expectedCatalogRevision(), + origin, + holdRequest.expectedPriorPointerVersion(), + holdRequest.initialAdmissionRequestId()); + if (!computedDigest.equals(holdRequest.initialAdmissionRequestDigest())) { + throw new IllegalArgumentException( + "Game Session request digest does not bind the complete initial-admission input"); + } + if (!source.targetNamespace().equals(holdRequest.targetNamespace()) + || !source.canonicalTenantId().equals(holdRequest.canonicalTenantId()) + || !source.worldSlug().equals(holdRequest.worldSlug()) + || !source.realmId().equals(holdRequest.realmId()) + || !source.playableStateNamespaceId().equals(holdRequest.playableStateNamespaceId()) + || !source.playableStateScope().equals(holdRequest.playableStateScope()) + || source.catalogRevision() != holdRequest.expectedCatalogRevision() + || !source.canonicalGameInstanceId().equals(holdRequest.canonicalGameInstanceId()) + || !source.canonicalVersionId().equals(holdRequest.canonicalVersionId())) { + throw new IllegalArgumentException( + "World hold request differs from the locked catalog and launch owner sources"); + } + if (!source.targetNamespace().equals(lifecycleRequest.targetNamespace()) + || !source.canonicalTenantId().equals(lifecycleRequest.canonicalTenantId()) + || !source.worldSlug().equals(lifecycleRequest.worldSlug()) + || !source.canonicalGameInstanceId().equals(lifecycleRequest.canonicalGameInstanceId()) + || !source.playableStateNamespaceId().equals(lifecycleRequest.playableStateNamespaceId()) + || !source.playableStateScope().equals(lifecycleRequest.playableStateScope()) + || !source.controlPlaneRequestId().equals(lifecycleRequest.controlPlaneRequestId()) + || !source.canonicalVersionId().equals(lifecycleRequest.canonicalVersionId()) + || !lifecycleRequest.publicProduction() + || !source + .descriptorRequestDigest() + .equals(lifecycleRequest.expectedDescriptorRequestDigest()) + || !source + .descriptorResultDigest() + .equals(lifecycleRequest.expectedDescriptorResultDigest()) + || !source + .releaseAttestationDigest() + .equals(lifecycleRequest.expectedReleaseAttestationDigest())) { + throw new IllegalArgumentException( + "World lifecycle selector differs from the locked launch owner source"); + } + } + + private static void requireIntentRequestId(String value) { + if (value == null + || value.isBlank() + || value.codePointCount(0, value.length()) > 120 + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException( + "Initial-admission request ID must fit the immutable V28 120-character intent column"); + } + } + + private static void requireText(String value, String name, int maximum) { + if (value == null || value.isBlank() || value.codePointCount(0, value.length()) > maximum) { + throw new IllegalArgumentException(name + " is required and must fit its storage limit"); + } + } + + private static void requireDigest(String value, Pattern pattern, String name) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException(name + " has an invalid SHA-256 digest"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java new file mode 100644 index 0000000000..2339c99167 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java @@ -0,0 +1,467 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.sql.Connection; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot.IntentState; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot.SourceBinding; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Durable Game Session intent persisted before an initial-admission request reaches World. */ +public final class CanonicalInitialAdmissionIntentRepository { + private static final String INTENT_TABLE = "game_session_canonical_initial_admission_intent"; + private static final int REQUEST_BYTES_LIMIT = 16_384; + private static final int HOLD_IDENTITY_BYTES_LIMIT = 65_536; + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final CanonicalGameInstanceLaunchAssociationRepository launchRepository; + + public CanonicalInitialAdmissionIntentRepository( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.launchRepository = Objects.requireNonNull(launchRepository, "launchRepository"); + } + + /** Locks both Game Session owner sources and commits exact World request bytes before acquire. */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public CanonicalInitialAdmissionIntentSnapshot reserve( + Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + Objects.requireNonNull(holdRequest, "holdRequest"); + Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); + requireIntentRequestId(holdRequest.initialAdmissionRequestId()); + byte[] holdBytes = boundedRequestBytes(holdRequest.canonicalRequestBytes(), "hold request"); + byte[] lifecycleBytes = + boundedRequestBytes(lifecycleRequest.canonicalBytes(), "lifecycle request"); + requireWritableReadCommittedOwnerTransaction(); + + LockedSources sources = lockSources(holdRequest); + CanonicalInitialAdmissionIntentSnapshot.requireExactBinding( + holdRequest, lifecycleRequest, sources.binding()); + + Record existing = + findIntent(holdRequest.targetNamespace(), holdRequest.initialAdmissionRequestId(), true); + if (existing != null) { + CanonicalInitialAdmissionIntentSnapshot snapshot = decodeSnapshot(existing); + requireExactRetry(snapshot, holdBytes, lifecycleBytes, sources.binding()); + return snapshot; + } + + if (findPendingRealmIntent(holdRequest, true) != null) { + throw conflict("Another nonterminal initial-admission intent already owns this realm"); + } + + try { + insertIntent(holdRequest, holdBytes, lifecycleBytes, sources.binding()); + } catch (DataAccessException failure) { + if ("23505".equals(failure.sqlState())) { + throw conflict("A competing initial-admission intent already owns this request or realm"); + } + throw failure; + } + Record inserted = + findIntent(holdRequest.targetNamespace(), holdRequest.initialAdmissionRequestId(), true); + if (inserted == null) { + throw new IllegalStateException( + "Committed initial-admission intent insert readback is missing"); + } + CanonicalInitialAdmissionIntentSnapshot snapshot = decodeSnapshot(inserted); + requireExactRetry(snapshot, holdBytes, lifecycleBytes, sources.binding()); + return snapshot; + } + + /** Attaches only World-issued acquisition identity to an already committed exact intent. */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public CanonicalInitialAdmissionIntentSnapshot attach( + Request exactHoldRequest, HoldIdentity holdIdentity) { + Objects.requireNonNull(exactHoldRequest, "exactHoldRequest"); + Objects.requireNonNull(holdIdentity, "holdIdentity"); + requireIntentRequestId(exactHoldRequest.initialAdmissionRequestId()); + byte[] holdBytes = + boundedRequestBytes(exactHoldRequest.canonicalRequestBytes(), "hold request"); + byte[] identityBytes = holdIdentity.canonicalBytes(); + if (identityBytes.length == 0 || identityBytes.length > HOLD_IDENTITY_BYTES_LIMIT) { + throw new IllegalArgumentException( + "World hold identity exceeds the immutable V28 byte limit"); + } + if (!Arrays.equals(holdBytes, holdIdentity.canonicalRequestBytes())) { + throw conflict("World hold identity does not echo the exact requested hold bytes"); + } + requireWritableReadCommittedOwnerTransaction(); + + LockedSources sources = lockSources(exactHoldRequest); + Record existing = + findIntent( + exactHoldRequest.targetNamespace(), exactHoldRequest.initialAdmissionRequestId(), true); + if (existing == null) { + throw conflict("Initial-admission intent must commit before World hold identity attachment"); + } + + CanonicalInitialAdmissionIntentSnapshot snapshot = decodeSnapshot(existing); + CanonicalInitialAdmissionIntentSnapshot.requireExactBinding( + snapshot.holdRequest(), snapshot.lifecycleRequest(), sources.binding()); + requireExactRetry( + snapshot, holdBytes, snapshot.lifecycleRequest().canonicalBytes(), sources.binding()); + if (!Arrays.equals( + snapshot.holdRequest().canonicalRequestBytes(), holdIdentity.canonicalRequestBytes())) { + throw conflict( + "World hold identity request differs from the retained initial-admission intent"); + } + + if (snapshot.state() != IntentState.PENDING_HOLD) { + if (snapshot.holdIdentity() != null + && Arrays.equals(snapshot.holdIdentity().canonicalBytes(), identityBytes)) { + return snapshot; + } + throw conflict( + "Attached or terminal initial-admission intent cannot accept a changed hold identity"); + } + + int updated = + dsl.execute( + "UPDATE " + + INTENT_TABLE + + " SET hold_identity_bytes = ?, state = 'HOLD_ATTACHED', " + + "updated_at = clock_timestamp() " + + "WHERE target_namespace = ? AND initial_admission_request_id = ? " + + "AND state = 'PENDING_HOLD' AND hold_identity_bytes IS NULL", + identityBytes, + exactHoldRequest.targetNamespace(), + exactHoldRequest.initialAdmissionRequestId()); + if (updated != 1) { + throw conflict("Initial-admission intent changed before hold identity attachment"); + } + Record attached = + findIntent( + exactHoldRequest.targetNamespace(), exactHoldRequest.initialAdmissionRequestId(), true); + if (attached == null) { + throw new IllegalStateException("Attached initial-admission intent readback is missing"); + } + CanonicalInitialAdmissionIntentSnapshot result = decodeSnapshot(attached); + if (result.state() != IntentState.HOLD_ATTACHED + || result.holdIdentity() == null + || !Arrays.equals(result.holdIdentity().canonicalBytes(), identityBytes)) { + throw new IllegalStateException( + "Attached initial-admission intent readback changed identity"); + } + return result; + } + + /** Returns one committed immutable intent readback, without asserting live World hold state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + String targetNamespace, String initialAdmissionRequestId) { + requireSelector(targetNamespace, initialAdmissionRequestId); + requireCommittedRead(); + Record row = findIntent(targetNamespace, initialAdmissionRequestId, false); + return row == null ? Optional.empty() : Optional.of(decodeSnapshot(row)); + } + + private LockedSources lockSources(Request request) { + CanonicalRealmCatalogSnapshot catalog = + catalogRepository.lockInitialAdmissionTarget( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.expectedCatalogRevision()); + CanonicalInitialAdmissionLaunchTarget launch = + launchRepository.lockForInitialAdmission( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId()); + SourceBinding source = sourceBinding(catalog, launch); + return new LockedSources(source); + } + + private static SourceBinding sourceBinding( + CanonicalRealmCatalogSnapshot catalog, CanonicalInitialAdmissionLaunchTarget launch) { + CanonicalGameInstanceLaunchAssociation association = launch.association(); + var descriptor = association.launchBindingEvidence().descriptor(); + var release = association.launchBindingEvidence().releaseAttestation(); + return new SourceBinding( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.worldSlug(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + catalog.visible(), + catalog.publicProduction(), + catalog.catalogRevision(), + catalog.creationRequestId(), + catalog.requestDigest(), + catalog.receiptDigest(), + association.tenantAssociationOperationId(), + association.gameSessionTenantId(), + association.gameInstanceUuid(), + launch.gameInstanceId(), + launch.canonicalVersionId(), + launch.runtimeVersionId(), + association.controlPlaneRequestId(), + association.launchDescriptorId(), + association.capturedStartingRowVersion(), + association.currentRowVersion(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + } + + private void insertIntent( + Request request, byte[] holdBytes, byte[] lifecycleBytes, SourceBinding source) { + dsl.execute( + "INSERT INTO " + + INTENT_TABLE + + " (target_namespace, initial_admission_request_id, request_digest, " + + "canonical_tenant_id, world_slug, realm_id, playable_state_namespace_id, " + + "playable_state_scope, catalog_visible, catalog_public_production, catalog_revision, " + + "catalog_creation_request_id, catalog_request_digest, catalog_receipt_digest, " + + "tenant_association_operation_id, game_session_tenant_id, canonical_game_instance_id, " + + "game_instance_id, canonical_version_id, runtime_version_id, control_plane_request_id, " + + "launch_descriptor_id, captured_starting_row_version, current_row_version, " + + "descriptor_request_digest, descriptor_result_digest, release_attestation_digest, " + + "canonical_hold_request_bytes, canonical_lifecycle_request_bytes, hold_identity_bytes, " + + "state, created_at, updated_at, terminal_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "?, ?, ?, ?, ?, NULL, ?, clock_timestamp(), clock_timestamp(), NULL)", + request.targetNamespace(), + request.initialAdmissionRequestId(), + request.initialAdmissionRequestDigest(), + source.canonicalTenantId(), + source.worldSlug(), + source.realmId(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.catalogVisible(), + source.catalogPublicProduction(), + source.catalogRevision(), + source.catalogCreationRequestId(), + source.catalogRequestDigest(), + source.catalogReceiptDigest(), + source.tenantAssociationOperationId(), + source.gameSessionTenantId(), + source.canonicalGameInstanceId(), + source.gameInstanceId(), + source.canonicalVersionId(), + source.runtimeVersionId(), + source.controlPlaneRequestId(), + source.launchDescriptorId(), + source.capturedStartingRowVersion(), + source.currentRowVersion(), + source.descriptorRequestDigest(), + source.descriptorResultDigest(), + source.releaseAttestationDigest(), + holdBytes, + lifecycleBytes, + IntentState.PENDING_HOLD.name()); + } + + private Record findIntent(String targetNamespace, String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + INTENT_TABLE + + " WHERE target_namespace = ? AND initial_admission_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + targetNamespace, + requestId); + } + + private Record findPendingRealmIntent(Request request, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + INTENT_TABLE + + " WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "AND state IN ('PENDING_HOLD', 'HOLD_ATTACHED') LIMIT 1" + + (forUpdate ? " FOR UPDATE" : ""), + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId()); + } + + private CanonicalInitialAdmissionIntentSnapshot decodeSnapshot(Record row) { + try { + String targetNamespace = required(row, "target_namespace", String.class); + String requestId = required(row, "initial_admission_request_id", String.class); + String requestDigest = required(row, "request_digest", String.class); + byte[] holdBytes = required(row, "canonical_hold_request_bytes", byte[].class).clone(); + byte[] lifecycleBytes = + required(row, "canonical_lifecycle_request_bytes", byte[].class).clone(); + Request holdRequest = Request.fromStored(holdBytes); + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest = + WorldCanonicalInstanceLifecycleEvidence.Request.fromStored(lifecycleBytes); + if (!targetNamespace.equals(holdRequest.targetNamespace()) + || !requestId.equals(holdRequest.initialAdmissionRequestId()) + || !requestDigest.equals(holdRequest.initialAdmissionRequestDigest())) { + throw new IllegalArgumentException( + "Persisted request keys or digest differ from canonical bytes"); + } + byte[] identityBytes = row.get("hold_identity_bytes", byte[].class); + HoldIdentity identity = + identityBytes == null ? null : HoldIdentity.fromStored(identityBytes.clone()); + SourceBinding source = sourceBindingFromRow(row); + IntentState state = IntentState.valueOf(required(row, "state", String.class)); + OffsetDateTime terminalAtValue = row.get("terminal_at", OffsetDateTime.class); + CanonicalInitialAdmissionIntentSnapshot snapshot = + new CanonicalInitialAdmissionIntentSnapshot( + holdRequest, + lifecycleRequest, + state, + identity, + source, + required(row, "created_at", OffsetDateTime.class).toInstant(), + required(row, "updated_at", OffsetDateTime.class).toInstant(), + terminalAtValue == null ? null : terminalAtValue.toInstant()); + if (holdBytes.length > REQUEST_BYTES_LIMIT + || lifecycleBytes.length > REQUEST_BYTES_LIMIT + || (identityBytes != null && identityBytes.length > HOLD_IDENTITY_BYTES_LIMIT)) { + throw new IllegalArgumentException("Persisted canonical request bytes exceed V28 limits"); + } + return snapshot; + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalStateException stateFailure + && stateFailure.getMessage() != null + && stateFailure.getMessage().startsWith("Persisted canonical initial-admission intent")) { + throw stateFailure; + } + throw new IllegalStateException( + "Persisted canonical initial-admission intent is malformed", malformed); + } + } + + private static SourceBinding sourceBindingFromRow(Record row) { + return new SourceBinding( + required(row, "target_namespace", String.class), + required(row, "canonical_tenant_id", UUID.class), + required(row, "world_slug", String.class), + required(row, "realm_id", UUID.class), + required(row, "playable_state_namespace_id", UUID.class), + required(row, "playable_state_scope", String.class), + required(row, "catalog_visible", Boolean.class), + required(row, "catalog_public_production", Boolean.class), + required(row, "catalog_revision", Long.class), + required(row, "catalog_creation_request_id", UUID.class), + required(row, "catalog_request_digest", String.class), + required(row, "catalog_receipt_digest", String.class), + required(row, "tenant_association_operation_id", UUID.class), + required(row, "game_session_tenant_id", Long.class), + required(row, "canonical_game_instance_id", UUID.class), + required(row, "game_instance_id", Long.class), + required(row, "canonical_version_id", UUID.class), + required(row, "runtime_version_id", Long.class), + required(row, "control_plane_request_id", String.class), + required(row, "launch_descriptor_id", String.class), + required(row, "captured_starting_row_version", Long.class), + required(row, "current_row_version", Long.class), + required(row, "descriptor_request_digest", String.class), + required(row, "descriptor_result_digest", String.class), + required(row, "release_attestation_digest", String.class)); + } + + private static void requireExactRetry( + CanonicalInitialAdmissionIntentSnapshot snapshot, + byte[] expectedHoldBytes, + byte[] expectedLifecycleBytes, + SourceBinding currentSource) { + if (!Arrays.equals(snapshot.holdRequest().canonicalRequestBytes(), expectedHoldBytes) + || !Arrays.equals(snapshot.lifecycleRequest().canonicalBytes(), expectedLifecycleBytes) + || !snapshot.sourceBinding().equals(currentSource)) { + throw conflict( + "Initial-admission retry differs from its retained request or locked owner source binding"); + } + } + + private static byte[] boundedRequestBytes(byte[] bytes, String label) { + Objects.requireNonNull(bytes, label + " bytes"); + if (bytes.length == 0 || bytes.length > REQUEST_BYTES_LIMIT) { + throw new IllegalArgumentException( + "Canonical " + label + " exceeds the immutable V28 byte limit"); + } + return bytes.clone(); + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical initial-admission intent mutation requires a writable owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical initial-admission intent DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical initial-admission intent mutation requires READ COMMITTED isolation"); + } + return null; + }); + Record readOnly = dsl.fetchOne("SHOW transaction_read_only"); + if (readOnly == null || !"off".equalsIgnoreCase(readOnly.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical initial-admission intent mutation requires a writable transaction"); + } + } + + private static void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical initial-admission intent read requires a committed owner read"); + } + } + + private static void requireSelector(String targetNamespace, String requestId) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical workload namespace"); + } + requireIntentRequestId(requestId); + } + + private static void requireIntentRequestId(String value) { + if (value == null + || value.isBlank() + || value.codePointCount(0, value.length()) > 120 + || value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException( + "Initial-admission request ID must fit the immutable V28 120-character intent column"); + } + } + + private static T required(Record row, String column, Class type) { + T value = row.get(column, type); + if (value == null) { + throw new IllegalStateException( + "Persisted canonical initial-admission intent is missing " + column); + } + return value; + } + + private static CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException + conflict(String message) { + return new CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException( + message); + } + + private record LockedSources(SourceBinding binding) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java index 5501dd7c6d..48429a3651 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java @@ -133,6 +133,69 @@ public AttemptSnapshot validateCurrentClaim(AttemptClaim claim) { return snapshot(row); } + /** + * Reads the immutable identity and attached Account projection for historical reconciliation. It + * does not require a live lease or reference and grants no permission to continue the mutation. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readHistoricalOwnerAttempt( + StartSessionPostAuthorizationExecutionTuple tuple, + UUID expectedOwnerAttemptId, + long expectedOwnerFence) { + requireOutsideOwnerTransaction(); + Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); + requireNonNil(expectedOwnerAttemptId, "expectedOwnerAttemptId"); + if (expectedOwnerFence <= 0L) { + throw new IllegalArgumentException("expectedOwnerFence must be positive"); + } + + String namespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + String requestId = tuple.controlPlaneRequestId(); + Record row = selectAttempt(namespace, requestId, false); + if (row == null) { + return Optional.empty(); + } + + byte[] expectedTuple = tuple.canonicalBytes(); + byte[] storedTuple = requiredBytes(row, "post_authorization_execution_tuple"); + if (!Arrays.equals(storedTuple, expectedTuple)) { + throw new StartSessionOperatorAttemptConflictException( + "Historical owner read differs from the complete original StartSession tuple"); + } + StartSessionPostAuthorizationExecutionTuple decodedTuple; + try { + decodedTuple = StartSessionPostAuthorizationExecutionTuple.decode(storedTuple); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Persisted historical StartSession owner tuple is malformed", malformed); + } + if (!Arrays.equals(decodedTuple.canonicalBytes(), storedTuple) + || !requiredText(row, "target_namespace").equals(namespace) + || !requiredText(row, "control_plane_request_id").equals(requestId)) { + throw new IllegalStateException( + "Persisted historical StartSession owner identity is not canonical"); + } + requireStoredProjectionColumnsMatch(row, decodedTuple); + if (!expectedOwnerAttemptId.equals(requiredUuid(row, "owner_attempt_id")) + || expectedOwnerFence != requiredLong(row, "owner_fence")) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Historical owner read does not match the original owner attempt and fence"); + } + + byte[] storedProjection = optionalBytes(row, "account_redemption_projection"); + if (storedProjection == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Historical StartSession owner attempt has no attached Account projection"); + } + AccountRedemptionProjection expectedProjection = projectionFromTuple(decodedTuple); + if (!Arrays.equals(storedProjection, expectedProjection.canonicalBytes())) { + throw new IllegalStateException( + "Persisted historical Account projection differs from its complete canonical tuple"); + } + requireProjectionMatches(decodedTuple, expectedProjection); + return Optional.of(snapshot(row)); + } + /** * Creates a narrow continuation capability for the exact existing pending attempt. This does not * reconstruct or expose an {@link AttemptClaim}; every use revalidates the stored claim identity. @@ -383,6 +446,13 @@ private void requireUnexpired(Record row) { } } + private static void requireOutsideOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Historical StartSession owner evidence requires a read outside the owner transaction"); + } + } + private void requireOriginalAuthorityUnexpired( StartSessionPostAuthorizationExecutionTuple tuple) { String referenceExpiresAt = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java index 8e56aa6b3a..1dbb185494 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java @@ -24,6 +24,7 @@ import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Unregistered immutable pin for the first normalized Game Design association selected by a @@ -86,6 +87,32 @@ public Optional findPinned( attempt)); } + /** + * Reads only the immutable first selection for historical owner reconciliation. It does not + * require a live owner lease, select again, or grant mutation or admission authority. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readHistoricalPinnedAssociation( + StartSessionPostAuthorizationExecutionTuple tuple, + UUID expectedOwnerAttemptId, + long expectedOwnerFence) { + requireOutsideOwnerTransaction(); + Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); + String namespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + String requestId = tuple.controlPlaneRequestId(); + Optional historicalAttempt = + attemptRepository.readHistoricalOwnerAttempt( + tuple, expectedOwnerAttemptId, expectedOwnerFence); + if (historicalAttempt.isEmpty()) { + return Optional.empty(); + } + + Record row = selectPin(namespace, requestId, false); + return row == null + ? Optional.empty() + : Optional.of(decodeStored(row, namespace, requestId, historicalAttempt.orElseThrow())); + } + /** * Pins the first configured selection or validates a later exact replay against the retained * selection. Only the byte-identical original response may replay INITIAL_CONFIGURED; a new @@ -362,6 +389,14 @@ private Record selectPin(String namespace, String requestId, boolean forUpdate) requestId); } + private static void requireOutsideOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Historical StartSession association evidence requires a read outside the owner " + + "transaction"); + } + } + private static void requireWireBound(byte[] requestWire, byte[] responseWire) { if (requestWire.length == 0 || responseWire.length == 0 diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparation.java new file mode 100644 index 0000000000..b95243f6f1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparation.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.client.WorldCanonicalInitialAdmissionHoldClient; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot.IntentState; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Inactive orchestration seam for the durable-intent, World-acquire, exact-attach sequence. + * + *

This type is deliberately not registered as a Spring component. A retained attached or + * terminal snapshot is historical intent evidence only; it does not establish a live World hold, + * current lifecycle, or admission. + */ +public final class CanonicalInitialAdmissionHoldPreparation { + private final CanonicalInitialAdmissionIntentRepository intentRepository; + private final WorldCanonicalInitialAdmissionHoldClient worldClient; + private final TransactionTemplate ownerTransaction; + + public CanonicalInitialAdmissionHoldPreparation( + CanonicalInitialAdmissionIntentRepository intentRepository, + WorldCanonicalInitialAdmissionHoldClient worldClient, + PlatformTransactionManager transactionManager) { + this.intentRepository = Objects.requireNonNull(intentRepository, "intentRepository"); + this.worldClient = Objects.requireNonNull(worldClient, "worldClient"); + Objects.requireNonNull(transactionManager, "transactionManager"); + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Persists the immutable request before acquiring the World hold, then attaches only the exact + * World-issued identity in a second owner transaction. + */ + public CanonicalInitialAdmissionIntentSnapshot prepare( + Request exactHoldRequest, + WorldCanonicalInstanceLifecycleEvidence.Request exactLifecycleRequest) { + requireNoAmbientTransaction(); + Objects.requireNonNull(exactHoldRequest, "exactHoldRequest"); + Objects.requireNonNull(exactLifecycleRequest, "exactLifecycleRequest"); + + CanonicalInitialAdmissionIntentSnapshot reserved = + ownerTransaction.execute( + status -> intentRepository.reserve(exactHoldRequest, exactLifecycleRequest)); + requireSnapshotMatches(reserved, exactHoldRequest, exactLifecycleRequest); + + // Replays retain the exact immutable historical snapshot. They do not check current World + // state and therefore cannot authorize admission or alter a terminal outcome. + if (reserved.state() != IntentState.PENDING_HOLD) { + return reserved; + } + + // TransactionTemplate returns only after commit; this network call is outside owner SQL. + HoldIdentity acquired = worldClient.acquire(exactHoldRequest, exactLifecycleRequest); + requireExactHoldIdentity(acquired, exactHoldRequest); + + CanonicalInitialAdmissionIntentSnapshot attached = + ownerTransaction.execute(status -> intentRepository.attach(exactHoldRequest, acquired)); + requireSnapshotMatches(attached, exactHoldRequest, exactLifecycleRequest); + if (attached.state() != IntentState.HOLD_ATTACHED + || attached.holdIdentity() == null + || !Arrays.equals(attached.holdIdentity().canonicalBytes(), acquired.canonicalBytes())) { + throw new IllegalStateException( + "Attached initial-admission intent did not retain the exact World hold identity"); + } + return attached; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Initial-admission hold preparation cannot enter from an ambient transaction"); + } + } + + private static void requireSnapshotMatches( + CanonicalInitialAdmissionIntentSnapshot snapshot, + Request holdRequest, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + if (snapshot == null + || !Arrays.equals( + snapshot.holdRequest().canonicalRequestBytes(), holdRequest.canonicalRequestBytes()) + || !Arrays.equals( + snapshot.lifecycleRequest().canonicalBytes(), lifecycleRequest.canonicalBytes())) { + throw new IllegalStateException( + "Durable initial-admission intent readback changed the exact request tuple"); + } + } + + private static void requireExactHoldIdentity(HoldIdentity identity, Request request) { + if (identity == null + || !Arrays.equals(identity.canonicalRequestBytes(), request.canonicalRequestBytes()) + || !Arrays.equals( + identity.request().canonicalRequestBytes(), request.canonicalRequestBytes()) + || !identity.holdBindingDigest().equals(request.holdBindingDigest())) { + throw new IllegalStateException( + "World initial-admission hold identity did not echo the exact retained request"); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java new file mode 100644 index 0000000000..a08cc78b97 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java @@ -0,0 +1,872 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +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.when; + +import java.nio.file.Path; +import java.sql.DriverManager; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamesession.client.WorldCanonicalInitialAdmissionHoldClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalInitialAdmissionHoldPreparation; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for the durable pre-World-hold Game Session intent owner. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalInitialAdmissionIntentRepositoryIntegrationTest { + private static final String NAMESPACE = "canonical-intent-it"; + private static final UUID TENANT = uuid(401); + private static final UUID SOURCE_OPERATION = uuid(402); + private static final UUID INTAKE_REQUEST = uuid(403); + private static final UUID CATALOG_REQUEST = uuid(404); + private static final UUID ACTOR = uuid(405); + private static final UUID GAME_INSTANCE_UUID = uuid(406); + private static final UUID CANONICAL_VERSION = uuid(407); + private static final UUID ASSOCIATION_OPERATION = uuid(408); + private static final String CONTROL_PLANE_REQUEST_ID = "canonical-intent-launch-1"; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() { + Harness harness = harness(); + try { + OwnerTarget target = harness.seed(); + var request = holdRequest(target, "intent-exact-replay"); + var lifecycle = target.lifecycleRequest(uuid(410)); + var identity = + new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, uuid(411), uuid(412)); + + assertThatThrownBy( + () -> + harness.transactions.execute( + status -> target.intents().attach(request, identity))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must commit before World hold identity attachment"); + assertNoAdmissionMutation(harness.dsl); + + CanonicalInitialAdmissionIntentSnapshot reserved = + harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); + assertThat(reserved.state()) + .isEqualTo(CanonicalInitialAdmissionIntentSnapshot.IntentState.PENDING_HOLD); + assertThat(reserved.holdIdentity()).isNull(); + assertThat(reserved.sourceBinding().gameInstanceId()).isEqualTo(target.gameInstanceId()); + assertThat(reserved.sourceBinding().currentRowVersion()).isPositive(); + assertThat( + target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) + .contains(reserved); + + CanonicalInitialAdmissionIntentSnapshot retry = + harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); + assertThat(retry).isEqualTo(reserved); + + var changedLifecycle = target.lifecycleRequest(uuid(413)); + assertThatThrownBy( + () -> + harness.transactions.execute( + status -> target.intents().reserve(request, changedLifecycle))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("retained request or locked owner source binding"); + + var changedDigest = withDigest(request, "b".repeat(64)); + assertThatThrownBy( + () -> + harness.transactions.execute( + status -> target.intents().reserve(changedDigest, lifecycle))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not bind the complete initial-admission input"); + + var changedSource = withInstance(request, uuid(414)); + assertThatThrownBy( + () -> + harness.transactions.execute( + status -> target.intents().reserve(changedSource, lifecycle))) + .isInstanceOf(IllegalStateException.class); + + var competingRequest = holdRequest(target, "intent-other-request"); + var competingLifecycle = target.lifecycleRequest(uuid(415)); + assertThatThrownBy( + () -> + harness.transactions.execute( + status -> target.intents().reserve(competingRequest, competingLifecycle))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("already owns this realm"); + + CanonicalInitialAdmissionIntentSnapshot attached = + harness.transactions.execute(status -> target.intents().attach(request, identity)); + assertThat(attached.state()) + .isEqualTo(CanonicalInitialAdmissionIntentSnapshot.IntentState.HOLD_ATTACHED); + assertThat(attached.holdIdentity()).isEqualTo(identity); + CanonicalInitialAdmissionIntentSnapshot attachedReplay = + harness.transactions.execute(status -> target.intents().attach(request, identity)); + assertThat(attachedReplay).isEqualTo(attached); + CanonicalInitialAdmissionIntentSnapshot reservedReplay = + harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); + assertThat(reservedReplay).isEqualTo(attached); + + var changedIdentity = + new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, uuid(416), uuid(417)); + assertThatThrownBy( + () -> + harness.transactions.execute( + status -> target.intents().attach(request, changedIdentity))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot accept a changed hold identity"); + assertThat( + target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) + .contains(attached); + assertThat( + harness.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_intent")))) + .isEqualTo(1); + assertNoAdmissionMutation(harness.dsl); + } finally { + harness.close(); + } + } + + @Test + void commitsPendingHoldBeforeWorldAcquireAndRetriesTheSameIntentAfterAcquireFailure() + throws Exception { + Harness harness = harness(); + try { + OwnerTarget target = harness.seed(); + var request = holdRequest(target, "intent-coordinator-ordering"); + var lifecycle = target.lifecycleRequest(uuid(418)); + var identity = + new WorldCanonicalInitialAdmissionHold.HoldIdentity(request, uuid(419), uuid(420)); + WorldCanonicalInitialAdmissionHoldClient worldClient = + mock(WorldCanonicalInitialAdmissionHoldClient.class); + AtomicInteger acquireCalls = new AtomicInteger(); + + when(worldClient.acquire(any(), any())) + .thenAnswer( + invocation -> { + var acquireRequest = + invocation.getArgument(0, WorldCanonicalInitialAdmissionHold.Request.class); + var acquireLifecycle = + invocation.getArgument( + 1, WorldCanonicalInstanceLifecycleEvidence.Request.class); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(acquireRequest.canonicalRequestBytes()) + .containsExactly(request.canonicalRequestBytes()); + assertThat(acquireLifecycle.canonicalBytes()) + .containsExactly(lifecycle.canonicalBytes()); + assertPendingIntentVisibleFromSeparateConnection( + harness, acquireRequest, acquireLifecycle); + + if (acquireCalls.incrementAndGet() == 1) { + throw new IllegalStateException("simulated World acquire failure"); + } + return identity; + }); + + var preparation = + new CanonicalInitialAdmissionHoldPreparation( + target.intents(), worldClient, harness.transactionManager); + + assertThatThrownBy(() -> preparation.prepare(request, lifecycle)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("simulated World acquire failure"); + var pending = + target + .intents() + .read(target.targetNamespace(), request.initialAdmissionRequestId()) + .orElseThrow(); + assertThat(pending.state()) + .isEqualTo(CanonicalInitialAdmissionIntentSnapshot.IntentState.PENDING_HOLD); + assertThat(pending.holdRequest().canonicalRequestBytes()) + .containsExactly(request.canonicalRequestBytes()); + assertThat(pending.lifecycleRequest().canonicalBytes()) + .containsExactly(lifecycle.canonicalBytes()); + assertThat(pending.holdIdentity()).isNull(); + + var attached = preparation.prepare(request, lifecycle); + assertThat(acquireCalls).hasValue(2); + assertThat(attached.state()) + .isEqualTo(CanonicalInitialAdmissionIntentSnapshot.IntentState.HOLD_ATTACHED); + assertThat(attached.holdRequest().canonicalRequestBytes()) + .containsExactly(request.canonicalRequestBytes()); + assertThat(attached.lifecycleRequest().canonicalBytes()) + .containsExactly(lifecycle.canonicalBytes()); + assertThat(attached.holdIdentity()).isEqualTo(identity); + assertThat( + target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) + .contains(attached); + assertThat( + harness.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_intent")))) + .isEqualTo(1); + assertNoAdmissionMutation(harness.dsl); + } finally { + harness.close(); + } + } + + private static void assertPendingIntentVisibleFromSeparateConnection( + Harness harness, + WorldCanonicalInitialAdmissionHold.Request request, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycle) + throws java.sql.SQLException { + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + connection.setSchema(harness.schema()); + try (var statement = + connection.prepareStatement( + "SELECT state, canonical_hold_request_bytes, canonical_lifecycle_request_bytes " + + "FROM game_session_canonical_initial_admission_intent " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?")) { + statement.setString(1, request.targetNamespace()); + statement.setString(2, request.initialAdmissionRequestId()); + try (var rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + assertThat(rows.getString("state")).isEqualTo("PENDING_HOLD"); + assertThat(rows.getBytes("canonical_hold_request_bytes")) + .containsExactly(request.canonicalRequestBytes()); + assertThat(rows.getBytes("canonical_lifecycle_request_bytes")) + .containsExactly(lifecycle.canonicalBytes()); + assertThat(rows.next()).isFalse(); + } + } + } + } + + @Test + void rollbackLeavesNoIntentAndChangedRuntimeVersionBlocksAttachment() { + Harness harness = harness(); + try { + OwnerTarget target = harness.seed(); + var request = holdRequest(target, "intent-runtime-version"); + var lifecycle = target.lifecycleRequest(uuid(420)); + + assertThatThrownBy( + () -> + harness.transactions.execute( + status -> { + target.intents().reserve(request, lifecycle); + throw new IllegalStateException("force owner rollback"); + })) + .hasMessageContaining("force owner rollback"); + assertThat( + target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) + .isEmpty(); + assertNoAdmissionMutation(harness.dsl); + + CanonicalInitialAdmissionIntentSnapshot reserved = + harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); + harness.transactions.execute( + status -> { + harness.dsl.execute( + "UPDATE game_instances SET row_version = row_version + 1 " + + "WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + return null; + }); + + var identity = + new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, uuid(421), uuid(422)); + assertThatThrownBy( + () -> + harness.transactions.execute( + status -> target.intents().attach(request, identity))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("retained request or locked owner source binding"); + assertThat( + target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) + .contains(reserved); + assertNoAdmissionMutation(harness.dsl); + } finally { + harness.close(); + } + } + + @Test + void competingRequestsSerializeOnTheCatalogAndOnlyOneIntentWins() throws Exception { + Harness harness = harness(); + try { + OwnerTarget target = harness.seed(); + var firstRequest = holdRequest(target, "intent-race-first"); + var secondRequest = holdRequest(target, "intent-race-second"); + var firstLifecycle = target.lifecycleRequest(uuid(430)); + var secondLifecycle = target.lifecycleRequest(uuid(431)); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit(() -> raceReserve(target, firstRequest, firstLifecycle, ready, start)); + var second = + executor.submit( + () -> raceReserve(target, secondRequest, secondLifecycle, ready, start)); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(first.get(20, TimeUnit.SECONDS)).isNotEqualTo(second.get(20, TimeUnit.SECONDS)); + } finally { + executor.shutdownNow(); + } + + assertThat( + harness.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_intent")))) + .isEqualTo(1); + assertNoAdmissionMutation(harness.dsl); + } finally { + harness.close(); + } + } + + private static boolean raceReserve( + OwnerTarget target, + WorldCanonicalInitialAdmissionHold.Request request, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycle, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to begin competing owner transaction"); + } + try { + target.harness().transactions.execute(status -> target.intents().reserve(request, lifecycle)); + return true; + } catch ( + CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException expected) { + return false; + } + } + + private static WorldCanonicalInitialAdmissionHold.Request holdRequest( + OwnerTarget target, String requestId) { + long activeEpoch = 2L; + var launch = target.launch().association(); + UUID canonicalVersionId = target.launch().canonicalVersionId(); + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + target.catalog().realmId(), + target.playableStateNamespaceId(), + "SHARED", + launch.gameInstanceUuid(), + canonicalVersionId, + activeEpoch, + target.catalog().catalogRevision(), + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + requestId); + return new WorldCanonicalInitialAdmissionHold.Request( + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + target.catalog().realmId(), + target.playableStateNamespaceId(), + "SHARED", + launch.gameInstanceUuid(), + canonicalVersionId, + activeEpoch, + requestId, + requestDigest, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + target.catalog().catalogRevision(), + null); + } + + private static WorldCanonicalInitialAdmissionHold.Request withDigest( + WorldCanonicalInitialAdmissionHold.Request request, String digest) { + return new WorldCanonicalInitialAdmissionHold.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + request.activeLifecycleEpoch(), + request.initialAdmissionRequestId(), + digest, + request.initialAdmissionOrigin(), + request.expectedCatalogRevision(), + request.expectedPriorPointerVersion()); + } + + private static WorldCanonicalInitialAdmissionHold.Request withInstance( + WorldCanonicalInitialAdmissionHold.Request request, UUID instanceId) { + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + instanceId, + request.canonicalVersionId(), + request.activeLifecycleEpoch(), + request.expectedCatalogRevision(), + CanonicalInitialAdmissionRequest.OriginKind.valueOf( + request.initialAdmissionOrigin().name()), + request.expectedPriorPointerVersion(), + request.initialAdmissionRequestId()); + return new WorldCanonicalInitialAdmissionHold.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + instanceId, + request.canonicalVersionId(), + request.activeLifecycleEpoch(), + request.initialAdmissionRequestId(), + requestDigest, + request.initialAdmissionOrigin(), + request.expectedCatalogRevision(), + request.expectedPriorPointerVersion()); + } + + private static void assertNoAdmissionMutation(DSLContext dsl) { + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM gameplay_admission_pointer " + + "WHERE representation_version = 3") + .get(0, Long.class)) + .isZero(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM gameplay_admission_pointer_event " + + "WHERE representation_version = 3") + .get(0, Long.class)) + .isZero(); + assertThat( + dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) + .isZero(); + } + + private static AuthoredWorldSourceEvidence freshSource() { + String worldSlug = "intent-world"; + String tenantSlug = "tenant-intent"; + String displayName = "Intent World"; + UUID registrationRequestId = uuid(432); + long sourceGameRowId = 823; + String sourceGameTenantKey = "gds-tenant-intent"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, TENANT, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static CreateCanonicalRealmCatalogRequest catalogRequest(IntakeReceipt source) { + return new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST, + NAMESPACE, + TENANT, + source.operationId(), + "intent-realm", + "Intent Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + } + + private static CreateCanonicalLaunchPreparationRequest preparationRequest( + IntakeReceipt source, CanonicalRealmCatalogSnapshot catalog) { + return new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST_ID, + ACTOR, + NAMESPACE, + TENANT, + catalog.realmId(), + CATALOG_REQUEST, + catalog.catalogRevision(), + source.operationId(), + 404, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source) { + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request.descriptorRequest(catalog, source.source()), + "launch-descriptor-canonical-intent", + 72, + false, + null, + "{}", + "generation-1", + 3, + 73, + "published-bundle-intent", + false, + null); + CompleteLaunchBindingEvidence binding = completeBinding(descriptor); + when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenReturn(descriptor); + when(client.get(any(GetRequest.class))).thenReturn(descriptor); + when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(binding); + return client; + } + + private static CompleteLaunchBindingEvidence completeBinding( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + String commitId = "publish-commit-canonical-intent"; + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + commitId, + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest("d") : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + CANONICAL_VERSION, + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish-canonical-intent", + commitId, + participants, + digest("b"), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } + + private static String digest(String letter) { + return "sha256:" + letter.repeat(64); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private static Harness harness() { + String schema = "gs_canonical_intent_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Harness(schema, dataSource, transactionManager, transactions, dsl); + } + + private record Harness( + String schema, + DriverManagerDataSource dataSource, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + DSLContext dsl) { + OwnerTarget seed() { + var sourceRepository = new GameSessionAuthoredWorldSourceRepository(dsl); + var catalogRepository = new GameSessionCanonicalRealmCatalogRepository(dsl); + var preparationRepository = + new GameSessionCanonicalLaunchPreparationRepository(dsl, catalogRepository); + var launchRepository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + IntakeReceipt source = + Objects.requireNonNull( + transactions.execute( + status -> sourceRepository.register(INTAKE_REQUEST, freshSource()))); + var preparedCatalog = + catalogRepository.prepareInitialPublicProduction(catalogRequest(source)); + CanonicalRealmCatalogSnapshot catalog = + Objects.requireNonNull( + transactions.execute( + status -> catalogRepository.createInitialPublicProduction(preparedCatalog))); + var preparationRequest = preparationRequest(source, catalog); + var preparationService = + new GameSessionCanonicalLaunchPreparationService( + syntheticGameDesignClient(preparationRequest, catalog, source), + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE); + var preparedLaunch = preparationService.prepare(preparationRequest); + CompleteLaunchBindingEvidence binding = + preparationService.readCompleteBinding(preparedLaunch); + createTestOnlyFreshMappingAndRunningLaunch(source, binding, launchRepository); + CanonicalInitialAdmissionLaunchTarget launch = + launchRepository + .readForInitialAdmission(NAMESPACE, TENANT, catalog.realmId(), GAME_INSTANCE_UUID) + .orElseThrow(); + var intentRepository = + new CanonicalInitialAdmissionIntentRepository(dsl, catalogRepository, launchRepository); + return new OwnerTarget(this, catalog, launch, intentRepository); + } + + private void createTestOnlyFreshMappingAndRunningLaunch( + IntakeReceipt source, + CompleteLaunchBindingEvidence binding, + CanonicalGameInstanceLaunchAssociationRepository launchRepository) { + RuntimeTenantIdentityEvidence sourceIdentity = + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + source.source().registrationRequestId(), + TENANT, + source.source().sourceGameRowId(), + source.source().sourceGameTenantKey(), + source.source().provenanceKind()); + transactions.execute( + status -> { + Record reservation = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO game_session_tenant_scope_reservation " + + "(reservation_kind) VALUES ('FRESH_SOURCE_BOUND') " + + "RETURNING game_session_tenant_id")); + long tenantId = reservation.get("game_session_tenant_id", Long.class); + var tenantAssociation = + new FreshGameSessionTenantAssociation( + ASSOCIATION_OPERATION, tenantId, sourceIdentity); + dsl.execute( + "INSERT INTO game_session_tenant_canonical_claim " + + "(target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, " + + "association_kind, reservation_kind, association_operation_id, " + + "association_request_id) " + + "VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", + NAMESPACE, + TENANT, + tenantId, + ASSOCIATION_OPERATION, + source.source().registrationRequestId()); + dsl.execute( + "INSERT INTO game_session_fresh_tenant_association " + + "(association_operation_id, target_namespace, association_request_id, " + + "source_schema_version, source_target_namespace, source_request_id, " + + "source_canonical_tenant_id, canonical_tenant_id, " + + "legacy_game_session_tenant_id, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, association_kind) " + + "VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND')", + ASSOCIATION_OPERATION, + NAMESPACE, + source.source().registrationRequestId(), + NAMESPACE, + source.source().registrationRequestId(), + TENANT, + TENANT, + tenantId, + source.source().sourceGameRowId(), + source.source().sourceGameTenantKey()); + Record instance = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO game_instances " + + "(tenant_id, runtime_version, game_template_id, launch_descriptor_id, " + + "version_id, release_bundle_id, generation_config_revision, " + + "version_state_epoch, owner_account_id, status, row_version, " + + "game_instance_uuid, run_owned_start_request_id, " + + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref, " + + "run_owned_start_preparing_epoch, run_owned_start_active_epoch) " + + "VALUES (?, '72', 404, ?, 72, 73, 'generation-1', 3, 77, 'STARTING', " + + "1, ?, ?, ?, ?, 1, 2) RETURNING id", + tenantId, + binding.descriptor().launchDescriptorId(), + GAME_INSTANCE_UUID, + CONTROL_PLANE_REQUEST_ID, + "c".repeat(64), + binding.descriptor().publishedReleaseBundleRef())); + long gameInstanceId = instance.get("id", Long.class); + launchRepository.capture(tenantAssociation, gameInstanceId, binding); + dsl.execute( + "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", + tenantId, + gameInstanceId); + return null; + }); + } + + void close() { + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException("Failed to dispose canonical intent test schema", failure); + } + } + } + + private record OwnerTarget( + Harness harness, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launch, + CanonicalInitialAdmissionIntentRepository intents) { + String targetNamespace() { + return catalog.targetNamespace(); + } + + UUID canonicalTenantId() { + return catalog.tenantId(); + } + + String worldSlug() { + return catalog.worldSlug(); + } + + UUID playableStateNamespaceId() { + return catalog.playableStateNamespaceId(); + } + + long gameSessionTenantId() { + return launch.association().gameSessionTenantId(); + } + + long gameInstanceId() { + return launch.gameInstanceId(); + } + + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest(UUID readRequestId) { + CanonicalGameInstanceLaunchAssociation association = launch.association(); + var binding = association.launchBindingEvidence(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + readRequestId, + targetNamespace(), + canonicalTenantId(), + worldSlug(), + association.gameInstanceUuid(), + playableStateNamespaceId(), + "SHARED", + true, + association.controlPlaneRequestId(), + launch.canonicalVersionId(), + binding.descriptor().requestDigest(), + binding.descriptor().resultDigest(), + binding.releaseAttestation().evidenceDigest()); + } + } +} 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 43c94bc553..d595db53ee 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 @@ -10,6 +10,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; @@ -162,6 +163,184 @@ void exactAccountProjectionAttachesOnceWhileFingerprintAndSourceSubstitutionsCon .isEqualTo(1); } + @Test + void historicalOwnerReadAcceptsExpiredExactAttemptWithoutChangingOwnerState() throws Exception { + Fixture fixture = fixture(Duration.ofMillis(500)); + StartSessionPostAuthorizationExecutionTuple tuple = + tuple( + "operator-attempt-historical-expired", + "canonical StartSession owner attempt", + RESERVATION_OWNER, + 19L, + FINGERPRINT, + Instant.parse("2000-01-01T00:05:00Z")); + AttemptClaim claim = fixture.reserve(tuple).claim().orElseThrow(); + AttemptSnapshot attached = + fixture.attach( + claim, + projection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + Thread.sleep(750L); + + var before = fixture.ownerClaimRow(tuple.controlPlaneRequestId()); + assertThat(before.get("lease_expires_at", java.time.OffsetDateTime.class).toInstant()) + .isEqualTo(attached.leaseExpiresAt()); + assertThat(fixture.leaseExpired(tuple.controlPlaneRequestId())).isTrue(); + int attemptsBefore = fixture.attemptCount(); + int instancesBefore = fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances"))); + int pointersBefore = fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer"))); + int pointerEventsBefore = + fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event"))); + + AttemptSnapshot historical = + fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence()).orElseThrow(); + + assertThat(historical.ownerAttemptId()).isEqualTo(attached.ownerAttemptId()); + assertThat(historical.ownerMutationId()).isEqualTo(attached.ownerMutationId()); + assertThat(historical.ownerFence()).isEqualTo(attached.ownerFence()); + assertThat(historical.phaseState()).isEqualTo(attached.phaseState()); + assertThat(historical.leaseExpiresAt()).isEqualTo(attached.leaseExpiresAt()); + assertThat(historical.postAuthorizationExecutionTuple()) + .containsExactly(attached.postAuthorizationExecutionTuple()); + assertThat(historical.accountRedemptionProjection()) + .containsExactly(attached.accountRedemptionProjection()); + var after = fixture.ownerClaimRow(tuple.controlPlaneRequestId()); + assertThat(after.get("claim_owner_id", UUID.class)) + .isEqualTo(before.get("claim_owner_id", UUID.class)); + assertThat(after.get("owner_attempt_id", UUID.class)) + .isEqualTo(before.get("owner_attempt_id", UUID.class)); + assertThat(after.get("owner_mutation_id", UUID.class)) + .isEqualTo(before.get("owner_mutation_id", UUID.class)); + assertThat(after.get("owner_fence", Long.class)) + .isEqualTo(before.get("owner_fence", Long.class)); + assertThat(after.get("phase_state", String.class)) + .isEqualTo(before.get("phase_state", String.class)); + assertThat(after.get("lease_expires_at", java.time.OffsetDateTime.class)) + .isEqualTo(before.get("lease_expires_at", java.time.OffsetDateTime.class)); + assertThat(after.get("account_redemption_projection", byte[].class)) + .containsExactly(before.get("account_redemption_projection", byte[].class)); + assertThat(fixture.attemptCount()).isEqualTo(attemptsBefore); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))) + .isEqualTo(instancesBefore); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isEqualTo(pointersBefore); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) + .isEqualTo(pointerEventsBefore); + + assertThatThrownBy(() -> fixture.validate(claim)) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired"); + ReservationResult expiredReplay = fixture.reserve(tuple); + assertThat(expiredReplay.claim()).isEmpty(); + assertThat(expiredReplay.snapshot().ownerAttemptId()).isEqualTo(claim.ownerAttemptId()); + assertThat(fixture.attemptCount()).isEqualTo(attemptsBefore); + } + + @Test + void historicalOwnerReadRejectsWrongTupleTenantAttemptAndFence() { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = + tuple("operator-attempt-historical-mismatch"); + AttemptClaim claim = fixture.reserve(tuple).claim().orElseThrow(); + fixture.attach( + claim, + projection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + + assertThatThrownBy( + () -> + fixture.historical( + tuple(tuple.controlPlaneRequestId(), "different complete action"), + claim.ownerAttemptId(), + claim.ownerFence())) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + assertThatThrownBy( + () -> + fixture.historical( + tupleWithTenant( + tuple.controlPlaneRequestId(), + UUID.fromString("4d2cde3b-0834-4e65-84aa-436d88e5f6c5")), + claim.ownerAttemptId(), + claim.ownerFence())) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + assertThatThrownBy( + () -> + fixture.historical( + tuple, + UUID.fromString("1819a1ce-04d2-4e3f-bb64-4a672d4eb711"), + claim.ownerFence())) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); + assertThatThrownBy( + () -> fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence() + 1L)) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> + fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside the owner transaction"); + assertThat(fixture.attemptCount()).isEqualTo(1); + } + + @Test + void historicalOwnerReadRejectsMissingAndCorruptedAttachedProjection() { + Fixture missing = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple missingTuple = + tuple("operator-attempt-historical-no-projection"); + AttemptClaim missingClaim = missing.reserve(missingTuple).claim().orElseThrow(); + assertThatThrownBy( + () -> + missing.historical( + missingTuple, missingClaim.ownerAttemptId(), missingClaim.ownerFence())) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("no attached Account projection"); + + Fixture corrupted = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple corruptedTuple = + tuple("operator-attempt-historical-corrupt-projection"); + AttemptClaim corruptedClaim = corrupted.reserve(corruptedTuple).claim().orElseThrow(); + corrupted.attach( + corruptedClaim, + projection( + corruptedTuple.authorizationReferenceFingerprint(), + corruptedTuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + corrupted.dsl.execute( + "ALTER TABLE game_session_start_session_operator_attempt " + + "DISABLE TRIGGER game_session_start_session_operator_attempt_immutable"); + try { + corrupted.dsl.execute( + "UPDATE game_session_start_session_operator_attempt " + + "SET account_redemption_projection = decode('00', 'hex') " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + corruptedTuple.controlPlaneRequestId()); + } finally { + corrupted.dsl.execute( + "ALTER TABLE game_session_start_session_operator_attempt " + + "ENABLE TRIGGER game_session_start_session_operator_attempt_immutable"); + } + assertThatThrownBy( + () -> + corrupted.historical( + corruptedTuple, corruptedClaim.ownerAttemptId(), corruptedClaim.ownerFence())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("projection differs"); + assertThat(corrupted.attemptCount()).isEqualTo(1); + } + @Test void evidenceContinuationRequiresTheExactAttachedProjectionAndUnexpiredOriginalAttempt() throws Exception { @@ -468,11 +647,41 @@ private static StartSessionPostAuthorizationExecutionTuple tuple( long reservationFence, String fingerprint, Instant authorityExpiresAt) { + return tuple( + requestId, + auditReason, + reservationOwner, + reservationFence, + fingerprint, + authorityExpiresAt, + TENANT); + } + + private static StartSessionPostAuthorizationExecutionTuple tupleWithTenant( + String requestId, UUID tenantId) { + return tuple( + requestId, + "canonical StartSession owner attempt", + RESERVATION_OWNER, + 19L, + FINGERPRINT, + Instant.parse("2099-01-01T00:05:00Z"), + tenantId); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, + String auditReason, + UUID reservationOwner, + long reservationFence, + String fingerprint, + Instant authorityExpiresAt, + UUID tenantId) { StartSessionOperatorAction action = new StartSessionOperatorAction( StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Scope(tenantId, NAMESPACE), new StartSessionOperatorAction.Target(91L, TARGET_OWNER), StartSessionOperatorAction.ExpectedVersion.ABSENT, new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), @@ -504,7 +713,8 @@ private static byte[] bundle( String version, String sourceEvidenceId, Instant authorityExpiresAt) { - String tenantId = TENANT.toString(); + String tenantId = tuple.action().scope().tenantId().toString(); + String targetNamespace = tuple.action().scope().targetNamespace(); Map projection = Map.of( "sourceType", @@ -557,7 +767,7 @@ private static byte[] bundle( StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "authorityScope", Map.of( - "scope", Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "scope", Map.of("tenantId", tenantId, "targetNamespace", targetNamespace), "actionFamily", tuple.actionFamily(), "applicableAccountId", ACTOR.toString(), "applicableTenantId", tenantId), @@ -667,5 +877,37 @@ PinnedLaunchDescriptorSnapshot pin(EvidenceContinuation continuation, Resolved c int attemptCount() { return dsl.fetchCount(DSL.table(DSL.name("game_session_start_session_operator_attempt"))); } + + Optional historical( + StartSessionPostAuthorizationExecutionTuple tuple, UUID ownerAttemptId, long ownerFence) { + return repository.readHistoricalOwnerAttempt(tuple, ownerAttemptId, ownerFence); + } + + org.jooq.Record ownerClaimRow(String requestId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT owner_attempt_id, owner_mutation_id, claim_owner_id, owner_fence, " + + "phase_state, lease_expires_at, account_redemption_projection " + + "FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + requestId), + "persisted owner attempt row"); + } + + boolean leaseExpired(String requestId) { + var row = + dsl.fetchOne( + "SELECT lease_expires_at <= clock_timestamp() AS expired " + + "FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + requestId); + if (row == null) { + throw new IllegalStateException("persisted owner attempt row missing while checking lease"); + } + Boolean expired = row.get("expired", Boolean.class); + return Boolean.TRUE.equals(expired); + } } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java index fb30b84baa..1bb568bb0c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java @@ -19,6 +19,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -59,6 +60,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot; @@ -195,6 +197,125 @@ void pinsOneInitialSelectionAndExactReplayReturnsTheOriginalWireSelection() { assertThat(fixture.pinCount()).isEqualTo(1); } + @Test + void historicalPinReadReturnsExpiredOwnerSelectionWithoutChangingOwnerState() throws Exception { + Fixture fixture = fixture(Duration.ofSeconds(2)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("association-pin-historical-expired"); + AttemptClaim claim = fixture.reserveAndAttach(tuple); + AttemptSnapshot ownerBeforePin = + fixture.historicalAttempt(tuple, claim.ownerAttemptId(), claim.ownerFence()).orElseThrow(); + PinnedAssociationSnapshot original = + fixture.pin(claim, result(tuple, claim, new InitialConfigured(), UUID.randomUUID())); + Thread.sleep(2500L); + + var before = fixture.ownerClaimRow(claim.controlPlaneRequestId()); + assertThat(fixture.leaseExpired(claim.controlPlaneRequestId())).isTrue(); + int attemptsBefore = fixture.attemptCount(); + int pinsBefore = fixture.pinCount(); + int instancesBefore = fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances"))); + int pointersBefore = fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer"))); + int pointerEventsBefore = + fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event"))); + + PinnedAssociationSnapshot historical = + fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence()).orElseThrow(); + + assertThat(historical.result()).isEqualTo(original.result()); + assertThat(historical.requestDigest()).isEqualTo(original.requestDigest()); + assertThat(historical.responseDigest()).isEqualTo(original.responseDigest()); + assertThat(historical.createdAt()).isEqualTo(original.createdAt()); + var after = fixture.ownerClaimRow(claim.controlPlaneRequestId()); + assertThat(after.get("owner_attempt_id", UUID.class)) + .isEqualTo(before.get("owner_attempt_id", UUID.class)); + assertThat(after.get("owner_mutation_id", UUID.class)) + .isEqualTo(before.get("owner_mutation_id", UUID.class)); + assertThat(after.get("claim_owner_id", UUID.class)) + .isEqualTo(before.get("claim_owner_id", UUID.class)); + assertThat(after.get("owner_fence", Long.class)) + .isEqualTo(before.get("owner_fence", Long.class)); + assertThat(after.get("phase_state", String.class)) + .isEqualTo(before.get("phase_state", String.class)); + assertThat(after.get("lease_expires_at", java.time.OffsetDateTime.class)) + .isEqualTo(before.get("lease_expires_at", java.time.OffsetDateTime.class)); + assertThat(fixture.attemptCount()).isEqualTo(attemptsBefore); + assertThat(fixture.pinCount()).isEqualTo(pinsBefore); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))) + .isEqualTo(instancesBefore); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isEqualTo(pointersBefore); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) + .isEqualTo(pointerEventsBefore); + assertThat(ownerBeforePin.ownerAttemptId()).isEqualTo(claim.ownerAttemptId()); + assertThat(ownerBeforePin.ownerFence()).isEqualTo(claim.ownerFence()); + + assertThatThrownBy(() -> fixture.find(claim)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired"); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> + fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside the owner transaction"); + assertThat(fixture.attemptCount()).isEqualTo(attemptsBefore); + assertThat(fixture.pinCount()).isEqualTo(pinsBefore); + } + + @Test + void historicalPinReadReturnsNoEvidenceForAnAbsentPinAfterClaimExpiry() throws Exception { + Fixture fixture = fixture(Duration.ofMillis(500)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("association-pin-historical-absent"); + AttemptClaim claim = fixture.reserveAndAttach(tuple); + Thread.sleep(750L); + + assertThat(fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence())).isEmpty(); + assertThat(fixture.attemptCount()).isEqualTo(1); + assertThat(fixture.pinCount()).isZero(); + assertThatThrownBy(() -> fixture.find(claim)) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired"); + } + + @Test + void historicalPinReadRejectsCorruptedStoredSelection() { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("association-pin-historical-corrupt"); + AttemptClaim claim = fixture.reserveAndAttach(tuple); + fixture.pin(claim, result(tuple, claim, new InitialConfigured(), UUID.randomUUID())); + + fixture.dsl.execute( + "ALTER TABLE game_session_start_session_template_association_pin " + + "DISABLE TRIGGER gs_start_session_template_association_pin_immutable"); + try { + fixture.dsl.execute( + "UPDATE game_session_start_session_template_association_pin " + + "SET selected_commit_id = ? WHERE target_namespace = ? " + + "AND control_plane_request_id = ?", + UUID.fromString("66666666-6666-4666-8666-666666666666"), + tuple.preAuthorizationTuple().action().scope().targetNamespace(), + tuple.controlPlaneRequestId()); + } finally { + fixture.dsl.execute( + "ALTER TABLE game_session_start_session_template_association_pin " + + "ENABLE TRIGGER gs_start_session_template_association_pin_immutable"); + } + + assertThatThrownBy(() -> fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("columns differ"); + assertThat(fixture.attemptCount()).isEqualTo(1); + assertThat(fixture.pinCount()).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(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) + .isZero(); + } + @Test void concurrentInitialSelectionsCannotReplaceTheFirstCommittedPin() throws Exception { Fixture fixture = fixture(); @@ -895,6 +1016,10 @@ private static String sha256(byte[] value) { } private static Fixture fixture() { + return fixture(Duration.ofSeconds(30)); + } + + private static Fixture fixture(Duration ownerClaimLease) { String schema = "gs_template_association_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); @@ -913,8 +1038,7 @@ private static Fixture fixture() { var transactions = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - var attempts = - new GameSessionStartSessionOperatorAttemptRepository(dsl, Duration.ofSeconds(30)); + var attempts = new GameSessionStartSessionOperatorAttemptRepository(dsl, ownerClaimLease); return new Fixture( dsl, transactions, @@ -951,6 +1075,47 @@ java.util.Optional find(AttemptClaim claim) { transactions.execute(status -> pins.findPinned(claim)), "template association read"); } + Optional historicalAttempt( + StartSessionPostAuthorizationExecutionTuple tuple, UUID ownerAttemptId, long ownerFence) { + return attempts.readHistoricalOwnerAttempt(tuple, ownerAttemptId, ownerFence); + } + + Optional historical( + StartSessionPostAuthorizationExecutionTuple tuple, UUID ownerAttemptId, long ownerFence) { + return pins.readHistoricalPinnedAssociation(tuple, ownerAttemptId, ownerFence); + } + + org.jooq.Record ownerClaimRow(String requestId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT owner_attempt_id, owner_mutation_id, claim_owner_id, owner_fence, " + + "phase_state, lease_expires_at " + + "FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + requestId), + "persisted owner attempt row"); + } + + boolean leaseExpired(String requestId) { + var row = + dsl.fetchOne( + "SELECT lease_expires_at <= clock_timestamp() AS expired " + + "FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + requestId); + if (row == null) { + throw new IllegalStateException("persisted owner attempt row missing while checking lease"); + } + Boolean expired = row.get("expired", Boolean.class); + return Boolean.TRUE.equals(expired); + } + + int attemptCount() { + return dsl.fetchCount(DSL.table(DSL.name("game_session_start_session_operator_attempt"))); + } + int pinCount() { return dsl.fetchCount( DSL.table(DSL.name("game_session_start_session_template_association_pin"))); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java new file mode 100644 index 0000000000..b44bc28746 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java @@ -0,0 +1,615 @@ +package net.firedevops.firemud.gamesession.client; + +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 io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +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 io.grpc.stub.StreamObserver; +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.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 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.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldServiceGrpc; +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; + +/** Physical mTLS proof for the opt-in Game Session to World hold identity client. */ +class WorldCanonicalInitialAdmissionHoldClientTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String WRONG_WORLD_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final String REQUEST_ID = "gs-initial-admission-17"; + private static final String LAUNCH_CONTROL_PLANE_REQUEST_ID = "launch-control-plane-42"; + private static final String REQUEST_DIGEST = "a".repeat(64); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private Server server; + private WorldCanonicalInitialAdmissionHoldClient client; + private AtomicInteger applicationCalls; + private AtomicInteger serverCallStarts; + private AtomicReference receivedPeerUri; + private AtomicReference receivedAcquire; + private AtomicReference receivedRead; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void acquiresAndReadsOnlyTheExactImmutableIdentityOverPhysicalMtls() throws Exception { + Request request = request(); + HoldIdentity expected = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + startServer(pki.worldServer(), ResponseMode.EXACT, request); + client = newClient(server); + client.init(); + + HoldIdentity acquired = client.acquire(request, lifecycleRequest()); + HoldIdentity historical = client.readIdentity(request); + + assertThat(acquired).isEqualTo(expected); + assertThat(historical).isEqualTo(expected); + assertThat(lifecycleRequest().controlPlaneRequestId()) + .isNotEqualTo(request.initialAdmissionRequestId()); + assertThat(applicationCalls).hasValue(2); + assertThat(serverCallStarts).hasValue(2); + assertThat(receivedPeerUri).hasValue(GAME_SESSION_URI); + assertThat( + WorldCanonicalInitialAdmissionHold.Request.fromStored( + receivedAcquire.get().getCanonicalHoldRequestBytes().toByteArray())) + .isEqualTo(request); + assertThat( + WorldCanonicalInstanceLifecycleEvidence.Request.fromStored( + receivedAcquire.get().getCanonicalLifecycleReadRequestBytes().toByteArray())) + .isEqualTo(lifecycleRequest()); + assertThat(Request.fromStored(receivedRead.get().getCanonicalHoldRequestBytes().toByteArray())) + .isEqualTo(request); + UUID readRequestId = UUID.fromString(receivedRead.get().getReadRequestId()); + assertThat(readRequestId).isNotEqualTo(new UUID(0L, 0L)); + assertThat(receivedRead.get().getReadRequestId()).isEqualTo(readRequestId.toString()); + } + + @Test + void rejectsWrongServerWorkloadBeforeRequestAndRejectsEmptyOrUnknownResponses() throws Exception { + Request request = request(); + startServer(pki.wrongWorldServer(), ResponseMode.EXACT, request); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.readIdentity(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(serverCallStarts).hasValue(0); + assertThat(applicationCalls).hasValue(0); + stopTransport(); + + startServer(pki.worldServer(), ResponseMode.EMPTY_IDENTITY, request); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.acquire(request, lifecycleRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical initial-admission hold identity"); + assertThat(applicationCalls).hasValue(1); + stopTransport(); + + startServer(pki.worldServer(), ResponseMode.WRONG_READ_REQUEST_ID, request); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.readIdentity(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid historical initial-admission hold identity"); + assertThat(applicationCalls).hasValue(1); + stopTransport(); + + startServer(pki.worldServer(), ResponseMode.OTHER_REQUEST, request); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.acquire(request, lifecycleRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical initial-admission hold identity"); + assertThat(applicationCalls).hasValue(1); + stopTransport(); + + startServer(pki.worldServer(), ResponseMode.UNKNOWN_RESPONSE_FIELD, request); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.readIdentity(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid historical initial-admission hold identity"); + assertThat(applicationCalls).hasValue(1); + } + + @Test + void requiresExplicitInitializationConfiguredNamespaceMatchingAndNoAmbientTransaction() + throws Exception { + Request request = request(); + client = newClientPropertiesOnly(); + + assertThatThrownBy(() -> client.acquire(request, lifecycleRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.readIdentity(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.acquire(request, lifecycleRequest("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact initial-admission target"); + assertThatThrownBy(() -> lifecycleRequest(NAMESPACE, false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires public-production evidence"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.readIdentity(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + } + + private void startServer(TestIdentity identity, ResponseMode mode, Request expectedRequest) + throws Exception { + applicationCalls = new AtomicInteger(); + serverCallStarts = new AtomicInteger(); + receivedPeerUri = new AtomicReference<>(); + receivedAcquire = new AtomicReference<>(); + receivedRead = new AtomicReference<>(); + var service = + new WorldCanonicalInitialAdmissionHoldServiceGrpc + .WorldCanonicalInitialAdmissionHoldServiceImplBase() { + @Override + public void acquireCanonicalInitialAdmissionHold( + AcquireCanonicalInitialAdmissionHoldRequest request, + StreamObserver observer) { + applicationCalls.incrementAndGet(); + capturePeer(); + receivedAcquire.set(request); + AcquireCanonicalInitialAdmissionHoldResponse.Builder response = + AcquireCanonicalInitialAdmissionHoldResponse.newBuilder(); + responseIdentity(expectedRequest, mode) + .ifPresent(bytes -> response.setHoldIdentityBytes(ByteString.copyFrom(bytes))); + if (mode == ResponseMode.UNKNOWN_RESPONSE_FIELD) { + response.setUnknownFields(unknownFields()); + } + observer.onNext(response.build()); + observer.onCompleted(); + } + + @Override + public void readCanonicalInitialAdmissionHoldIdentity( + ReadCanonicalInitialAdmissionHoldIdentityRequest request, + StreamObserver observer) { + applicationCalls.incrementAndGet(); + capturePeer(); + receivedRead.set(request); + ReadCanonicalInitialAdmissionHoldIdentityResponse.Builder response = + ReadCanonicalInitialAdmissionHoldIdentityResponse.newBuilder() + .setReadRequestId( + mode == ResponseMode.WRONG_READ_REQUEST_ID + ? uuid("ffffffff-ffff-4fff-8fff-ffffffffffff").toString() + : request.getReadRequestId()); + responseIdentity(expectedRequest, mode) + .ifPresent(bytes -> response.setHoldIdentityBytes(ByteString.copyFrom(bytes))); + if (mode == ResponseMode.UNKNOWN_RESPONSE_FIELD) { + response.setUnknownFields(unknownFields()); + } + observer.onNext(response.build()); + observer.onCompleted(); + } + + private void capturePeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + receivedPeerUri.set(peer == null ? null : peer.uri()); + } + }; + ServerInterceptor countApplicationHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + serverCallStarts.incrementAndGet(); + return next.startCall(call, headers); + } + }; + server = + 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( + service, countApplicationHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private WorldCanonicalInitialAdmissionHoldClient newClient(Server target) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + target.getPort()); + return new WorldCanonicalInitialAdmissionHoldClient( + endpoints, pki.clientProperties(tempDirectory), new GrpcChannelFactory(), NAMESPACE); + } + + private WorldCanonicalInitialAdmissionHoldClient newClientPropertiesOnly() throws Exception { + return new WorldCanonicalInitialAdmissionHoldClient( + new ServiceEndpointsProperties(), + pki.clientProperties(tempDirectory), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static java.util.Optional responseIdentity(Request request, ResponseMode mode) { + if (mode == ResponseMode.EMPTY_IDENTITY) { + return java.util.Optional.empty(); + } + Request returned = + mode == ResponseMode.OTHER_REQUEST ? request("prod", "other-initial-admission") : request; + return java.util.Optional.of(new HoldIdentity(returned, HOLD_ID, HOLD_FENCE).canonicalBytes()); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static Request request() { + return request(NAMESPACE, REQUEST_ID); + } + + private static Request request(String namespace) { + return request(namespace, REQUEST_ID); + } + + private static Request request(String namespace, String requestId) { + return new Request( + namespace, + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + VERSION, + 7L, + requestId, + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest() { + return lifecycleRequest(NAMESPACE, true); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( + String namespace) { + return lifecycleRequest(namespace, true); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( + String namespace, boolean publicProduction) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + namespace, + TENANT, + "green-hollow", + GAME_INSTANCE, + PLAYABLE_NAMESPACE, + "SHARED", + publicProduction, + LAUNCH_CONTROL_PLANE_REQUEST_ID, + VERSION, + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private enum ResponseMode { + EXACT, + EMPTY_IDENTITY, + UNKNOWN_RESPONSE_FIELD, + WRONG_READ_REQUEST_ID, + OTHER_REQUEST + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity worldServer, + TestIdentity wrongWorldServer, + TestIdentity gameSessionClient) { + 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 initial-admission 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"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "world-server", WORLD_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-world-server", WRONG_WORLD_URI, true), + issueIdentity( + directory, caStore, caFile, "game-session-client", GAME_SESSION_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) throws Exception { + Path clientCertificate = + writePem( + directory.resolve("game-session-client.crt"), + "CERTIFICATE", + gameSessionClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-session-client.key"), + "PRIVATE KEY", + gameSessionClient.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + 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()); + } + PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()); + X509Certificate x509Certificate = (X509Certificate) keyStore.getCertificate(alias); + writePem(directory.resolve(alias + "-leaf.crt"), "CERTIFICATE", x509Certificate.getEncoded()); + writePem(directory.resolve(alias + "-leaf.key"), "PRIVATE KEY", privateKey.getEncoded()); + return new TestIdentity(privateKey, x509Certificate); + } + + 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 java.util.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", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java new file mode 100644 index 0000000000..b579516f27 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java @@ -0,0 +1,132 @@ +package unit.net.firedevops.firemud.gamesession.repository; + +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.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalInitialAdmissionIntentRepositoryTest { + private static final String NAMESPACE = "intent-unit"; + private static final UUID TENANT = uuid(1); + private static final UUID REALM = uuid(2); + private static final UUID PLAYABLE_NAMESPACE = uuid(3); + private static final UUID INSTANCE = uuid(4); + private static final UUID VERSION = uuid(5); + private static final String SHA256 = "sha256:" + "a".repeat(64); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void reserveRejectsAnIdentityBeyondTheV28IntentWidthBeforeOwnerReads() { + DSLContext dsl = mock(DSLContext.class); + var catalog = mock(GameSessionCanonicalRealmCatalogRepository.class); + var launch = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + var repository = new CanonicalInitialAdmissionIntentRepository(dsl, catalog, launch); + String requestId = "r".repeat(121); + + assertThatThrownBy(() -> repository.reserve(holdRequest(requestId), lifecycleRequest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("120-character intent column"); + + verifyNoInteractions(dsl, catalog, launch); + } + + @Test + void mutationRequiresWritableOwnerTransactionBeforeOwnerReads() { + DSLContext dsl = mock(DSLContext.class); + var catalog = mock(GameSessionCanonicalRealmCatalogRepository.class); + var launch = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + var repository = new CanonicalInitialAdmissionIntentRepository(dsl, catalog, launch); + + assertThatThrownBy(() -> repository.reserve(holdRequest("request-1"), lifecycleRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl, catalog, launch); + } + + @Test + void readRejectsAnAmbientTransactionBeforeQueryingTheIntentLedger() { + DSLContext dsl = mock(DSLContext.class); + var catalog = mock(GameSessionCanonicalRealmCatalogRepository.class); + var launch = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + var repository = new CanonicalInitialAdmissionIntentRepository(dsl, catalog, launch); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.read(NAMESPACE, "request-1")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed owner read"); + + verifyNoInteractions(dsl, catalog, launch); + } + + private static WorldCanonicalInitialAdmissionHold.Request holdRequest(String requestId) { + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + NAMESPACE, + TENANT, + "world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 2L, + 1L, + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + requestId); + return new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 2L, + requestId, + requestDigest, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest() { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + uuid(6), + NAMESPACE, + TENANT, + "world", + INSTANCE, + PLAYABLE_NAMESPACE, + "SHARED", + true, + "control-request-1", + VERSION, + SHA256, + SHA256, + SHA256); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparationTest.java new file mode 100644 index 0000000000..dce51a8bcd --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparationTest.java @@ -0,0 +1,434 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +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.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.client.WorldCanonicalInitialAdmissionHoldClient; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot.IntentState; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot.SourceBinding; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; +import net.firedevops.firemud.gamesession.service.impl.CanonicalInitialAdmissionHoldPreparation; +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; + +class CanonicalInitialAdmissionHoldPreparationTest { + private static final String NAMESPACE = "hold-unit"; + private static final UUID TENANT = uuid(1); + private static final UUID REALM = uuid(2); + private static final UUID PLAYABLE_NAMESPACE = uuid(3); + private static final UUID INSTANCE = uuid(4); + private static final UUID VERSION = uuid(5); + private static final String SHA256 = "sha256:" + "a".repeat(64); + private static final Request HOLD_REQUEST = holdRequest("request-1"); + private static final WorldCanonicalInstanceLifecycleEvidence.Request LIFECYCLE_REQUEST = + lifecycleRequest(); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void commitsIntentBeforeWorldAndAttachesInASeparateWritableReadCommittedTransaction() + throws Exception { + List events = new ArrayList<>(); + Fixtures fixtures = new Fixtures(events); + HoldIdentity identity = identity(HOLD_REQUEST, 7); + when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .thenAnswer( + invocation -> { + assertWritableTransaction(); + events.add("reserve"); + return snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST); + }); + when(fixtures.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + events.add("world"); + return identity; + }); + when(fixtures.repository.attach(HOLD_REQUEST, identity)) + .thenAnswer( + invocation -> { + assertWritableTransaction(); + events.add("attach"); + return snapshot(IntentState.HOLD_ATTACHED, identity, HOLD_REQUEST, LIFECYCLE_REQUEST); + }); + + CanonicalInitialAdmissionIntentSnapshot result = + fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST); + + assertThat(result.state()).isEqualTo(IntentState.HOLD_ATTACHED); + assertThat(events) + .containsExactly("begin", "reserve", "commit", "world", "begin", "attach", "commit"); + assertThat(fixtures.transactionManager.transactionDefinitions) + .allSatisfy( + definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); + } + + @Test + void reserveFailurePreventsWorldAcquisition() throws Exception { + Fixtures fixtures = new Fixtures(new ArrayList<>()); + when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .thenThrow(new IllegalStateException("reserve failed")); + + assertThatThrownBy(() -> fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .hasMessage("reserve failed"); + + verifyNoInteractions(fixtures.worldClient); + verify(fixtures.repository, never()) + .attach(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + } + + @Test + void reserveCommitFailurePreventsWorldAcquisitionAndAttachment() throws Exception { + Fixtures fixtures = new Fixtures(new ArrayList<>(), true); + when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .thenReturn(snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST)); + + assertThatThrownBy(() -> fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("reserve commit failed"); + + verifyNoInteractions(fixtures.worldClient); + verify(fixtures.repository, never()) + .attach(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + assertThat(fixtures.transactionManager.transactionDefinitions).hasSize(1); + } + + @Test + void remoteFailureLeavesPendingIntentAndRetryUsesTheSameExactRequest() throws Exception { + Fixtures fixtures = new Fixtures(new ArrayList<>()); + HoldIdentity identity = identity(HOLD_REQUEST, 8); + when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .thenReturn(snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST)); + when(fixtures.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .thenThrow(new IllegalStateException("World unavailable")) + .thenReturn(identity); + when(fixtures.repository.attach(HOLD_REQUEST, identity)) + .thenReturn(snapshot(IntentState.HOLD_ATTACHED, identity, HOLD_REQUEST, LIFECYCLE_REQUEST)); + + assertThatThrownBy(() -> fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .hasMessage("World unavailable"); + assertThat(fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST).state()) + .isEqualTo(IntentState.HOLD_ATTACHED); + + verify(fixtures.repository, org.mockito.Mockito.times(2)) + .reserve(HOLD_REQUEST, LIFECYCLE_REQUEST); + verify(fixtures.worldClient, org.mockito.Mockito.times(2)) + .acquire(HOLD_REQUEST, LIFECYCLE_REQUEST); + verify(fixtures.repository).attach(HOLD_REQUEST, identity); + } + + @Test + void attachFailurePropagatesWithoutReplacingRequestOrCallingAnyCompensation() throws Exception { + Fixtures fixtures = new Fixtures(new ArrayList<>()); + HoldIdentity identity = identity(HOLD_REQUEST, 9); + when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .thenReturn(snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST)); + when(fixtures.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)).thenReturn(identity); + when(fixtures.repository.attach(HOLD_REQUEST, identity)) + .thenThrow(new IllegalStateException("attach changed")); + + assertThatThrownBy(() -> fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .hasMessage("attach changed"); + + verify(fixtures.worldClient).acquire(HOLD_REQUEST, LIFECYCLE_REQUEST); + verify(fixtures.repository).attach(HOLD_REQUEST, identity); + verify(fixtures.repository, never()) + .reserve( + org.mockito.ArgumentMatchers.argThat(r -> r != HOLD_REQUEST), + org.mockito.ArgumentMatchers.any()); + } + + @Test + void exactAttachedOrTerminalReplayReturnsHistoricalSnapshotWithoutWorldCall() throws Exception { + for (IntentState state : List.of(IntentState.HOLD_ATTACHED, IntentState.TERMINAL)) { + Fixtures fixtures = new Fixtures(new ArrayList<>()); + HoldIdentity retained = identity(HOLD_REQUEST, 10); + CanonicalInitialAdmissionIntentSnapshot historical = + snapshot(state, retained, HOLD_REQUEST, LIFECYCLE_REQUEST); + when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)).thenReturn(historical); + + assertThat(fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .isSameAs(historical); + + verifyNoInteractions(fixtures.worldClient); + verify(fixtures.repository, never()) + .attach(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + } + } + + @Test + void wrongWorldIdentityAndChangedSnapshotTupleAreDenied() throws Exception { + Fixtures wrongIdentity = new Fixtures(new ArrayList<>()); + when(wrongIdentity.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .thenReturn(snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST)); + when(wrongIdentity.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .thenReturn(identity(holdRequest("different-request"), 11)); + + assertThatThrownBy(() -> wrongIdentity.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("did not echo"); + verify(wrongIdentity.repository, never()) + .attach(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + + Fixtures changedSnapshot = new Fixtures(new ArrayList<>()); + when(changedSnapshot.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .thenReturn( + snapshot( + IntentState.PENDING_HOLD, + null, + HOLD_REQUEST, + lifecycleRequestWithChangedIdentity())); + assertThatThrownBy(() -> changedSnapshot.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed the exact request tuple"); + verifyNoInteractions(changedSnapshot.worldClient); + + Fixtures changedAttach = new Fixtures(new ArrayList<>()); + HoldIdentity acquired = identity(HOLD_REQUEST, 12); + when(changedAttach.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .thenReturn(snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST)); + when(changedAttach.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)).thenReturn(acquired); + when(changedAttach.repository.attach(HOLD_REQUEST, acquired)) + .thenReturn( + snapshot( + IntentState.HOLD_ATTACHED, + identity(HOLD_REQUEST, 14), + HOLD_REQUEST, + LIFECYCLE_REQUEST)); + assertThatThrownBy(() -> changedAttach.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact World hold identity"); + } + + @Test + void ambientTransactionOrSynchronizationDeniesBeforeRepositoryOrWorldAccess() throws Exception { + Fixtures transaction = new Fixtures(new ArrayList<>()); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> transaction.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + verifyNoInteractions(transaction.repository, transaction.worldClient); + + TransactionSynchronizationManager.clear(); + Fixtures synchronization = new Fixtures(new ArrayList<>()); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> synchronization.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + verifyNoInteractions(synchronization.repository, synchronization.worldClient); + } + + private static void assertWritableTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static CanonicalInitialAdmissionIntentSnapshot snapshot( + IntentState state, + HoldIdentity identity, + Request holdRequest, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + return new CanonicalInitialAdmissionIntentSnapshot( + holdRequest, + lifecycleRequest, + state, + identity, + new SourceBinding( + NAMESPACE, + TENANT, + "world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + true, + true, + 1L, + uuid(20), + SHA256, + SHA256, + uuid(21), + 1L, + INSTANCE, + 1L, + VERSION, + 1L, + "control-request-1", + "launch-descriptor-1", + 1L, + 1L, + SHA256, + SHA256, + SHA256), + java.time.Instant.parse("2026-01-01T00:00:00Z"), + java.time.Instant.parse("2026-01-01T00:00:00Z"), + state == IntentState.TERMINAL ? java.time.Instant.parse("2026-01-01T00:01:00Z") : null); + } + + private static Request holdRequest(String requestId) { + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + NAMESPACE, + TENANT, + "world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 2L, + 1L, + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + requestId); + return new Request( + NAMESPACE, + TENANT, + "world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 2L, + requestId, + requestDigest, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest() { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + uuid(6), + NAMESPACE, + TENANT, + "world", + INSTANCE, + PLAYABLE_NAMESPACE, + "SHARED", + true, + "control-request-1", + VERSION, + SHA256, + SHA256, + SHA256); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request + lifecycleRequestWithChangedIdentity() { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + uuid(7), + NAMESPACE, + TENANT, + "world", + INSTANCE, + PLAYABLE_NAMESPACE, + "SHARED", + true, + "control-request-1", + VERSION, + SHA256, + SHA256, + SHA256); + } + + private static HoldIdentity identity(Request request, int id) { + return new WorldCanonicalInitialAdmissionHold.HoldIdentity(request, uuid(id), uuid(id + 1)); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private static final class Fixtures { + private final CanonicalInitialAdmissionIntentRepository repository = + mock(CanonicalInitialAdmissionIntentRepository.class); + private final WorldCanonicalInitialAdmissionHoldClient worldClient = + mock(WorldCanonicalInitialAdmissionHoldClient.class); + private final RecordingTransactionManager transactionManager; + private final CanonicalInitialAdmissionHoldPreparation preparation; + + private Fixtures(List events) { + this(events, false); + } + + private Fixtures(List events, boolean failFirstCommit) { + this.transactionManager = new RecordingTransactionManager(events, failFirstCommit); + this.preparation = + new CanonicalInitialAdmissionHoldPreparation(repository, worldClient, transactionManager); + } + } + + private static final class RecordingTransactionManager + extends AbstractPlatformTransactionManager { + private final List events; + private final List transactionDefinitions = new ArrayList<>(); + private final boolean failFirstCommit; + private int commitCount; + + private RecordingTransactionManager(List events, boolean failFirstCommit) { + this.events = events; + this.failFirstCommit = failFirstCommit; + } + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + transactionDefinitions.add(definition); + events.add("begin"); + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commitCount++; + events.add("commit"); + if (failFirstCommit && commitCount == 1) { + throw new IllegalStateException("reserve commit failed"); + } + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + events.add("rollback"); + } + } +} From d4302ec59a904bc999574ef97cb9e474749e813f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:07:48 +1300 Subject: [PATCH 05/22] Prove inactive World hold-state reads and canonical admission storage --- .../game-session-service/api-contracts.md | 4 +- .../player-access-and-session.md | 4 +- ...rld_canonical_initial_admission_hold.proto | 21 ++ .../common-platform-core/build.gradle.kts | 3 + ...rldCanonicalInitialAdmissionHoldState.java | 205 +++++++++++++ ...anonicalInitialAdmissionHoldStateTest.java | 202 +++++++++++++ .../common/testing/AuthoringFixtures.java | 112 ++++++++ .../game-session-service/build.gradle.kts | 1 + ...ldCanonicalInitialAdmissionHoldClient.java | 71 +++++ ...meInstanceLaunchAssociationRepository.java | 17 +- ...al_initial_admission_fresh_scope_guard.sql | 143 ++++++++++ ...ialAdmissionRepositoryIntegrationTest.java | 61 ++++ ...SessionAssociationReadIntegrationTest.java | 3 + ...ratorAttemptRepositoryIntegrationTest.java | 3 +- ...eAssociationRepositoryIntegrationTest.java | 4 +- ...nonicalInitialAdmissionHoldClientTest.java | 269 +++++++++++++++++- 16 files changed, 1114 insertions(+), 9 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java rename services/common-platform-core/src/{test => testFixtures}/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java (80%) create mode 100644 services/game-session-service/src/main/resources/db/migration/V39__canonical_initial_admission_fresh_scope_guard.sql diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 5b187456d2..cc6ad32011 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,7 +8,7 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -The canonical initial-admission preparation is inactive: the durable pre-hold intent repository and coordinator, exact World hold client, and lifecycle read client are not registered for runtime use. The coordinator commits the immutable intent before the remote hold request, then attaches only the exact World-issued identity in a separate owner transaction; an attached or terminal intent replay is historical evidence, not permission to admit. Authenticated live-hold validation, continuous protection through the pointer/audit commit, and cross-owner terminal reconciliation remain required. The narrower historical original-operation read is described under [restricted original-claim evidence continuation](#restricted-original-claim-evidence-continuation); neither that read nor a lifecycle snapshot supplies those missing guarantees. +The canonical initial-admission preparation is inactive: the durable pre-hold intent repository and coordinator, exact World hold client, and lifecycle read client are not registered for runtime use. The coordinator commits the immutable intent before the remote hold request, then attaches only the exact World-issued identity in a separate owner transaction; an attached or terminal intent replay is historical evidence, not permission to admit. The hold client can also read a closed same-snapshot hold status and lifecycle over exact workload mTLS, retaining both immutable identity and complete lifecycle-request correlation. A pending snapshot is observational, not continuous protection or commit authority. Genuine deployed owner readback, continuous protection through the pointer/audit commit, and cross-owner terminal reconciliation remain required. The narrower historical original-operation read is described under [restricted original-claim evidence continuation](#restricted-original-claim-evidence-continuation); neither that read nor a lifecycle snapshot supplies those missing guarantees. `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` currently fail closed at their authenticated internal receiving boundary with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable`, before command, coordinator, follow-up, or queue mutation. The retained lower-level admission implementation does not prove the cross-service Automation admission-epoch fence required by [ADR 0106](../../decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md). A separate receiver-fence successor must durably serialize installation against receiving admission, preserve exact retry outcomes, and prove that a handoff whose intent committed before an Automation pause cannot create live work under the displaced admission epoch afterward. This gate preserves ordinary gameplay APIs and does not claim the successor implemented. @@ -135,7 +135,7 @@ Under approved original-claim continuation decision `ae27ed99`, this narrowly bo The continuation is restricted to reading and exact replay of an existing immutable association pin. It must not replay redemption, create or reselect an association, create a claim, attempt, fence, or authorization reference, renew or transfer ownership, mutate domain state, or admit a player. Remote Account/source reads occur outside SQL; Game Session then locks and rechecks the same owner state before returning the association. The actual pin/read statement enforces claim expiry using the database clock. Missing or unattached projections, absent or changed pins, changed tuples, expired claims, and ambiguous outcomes remain reconciliation-only and cannot be treated as authorization or admission. -Historical original-operation reconciliation is separate from that live continuation. The unregistered owner repositories can read the complete retained StartSession tuple, actual original attempt/fence, exact attached Account projection and existing immutable first-selection pin after lease or reference expiry. These reads create no claim, renewal, redemption, reselection, pointer/audit mutation or admission authority; missing or mismatched retained evidence fails closed. The authenticated World-facing producer and cross-owner recovery composition remain unimplemented. This historical evidence is not a current World hold or a Game Session terminal outcome. +Historical original-operation reconciliation is separate from that live continuation. The unregistered owner repositories can read the complete retained StartSession tuple, actual original attempt/fence, exact attached Account projection and existing immutable first-selection pin after lease or reference expiry. These reads create no claim, renewal, redemption, reselection, pointer/audit mutation or admission authority; missing or mismatched retained evidence fails closed. The separate current STARTING association read now returns its exact stored tuple alongside the original attempt/fence, but still requires an unexpired pending lease; it is not an after-expiry recovery endpoint. The authenticated World-facing historical producer and cross-owner recovery composition remain unimplemented. This historical evidence is not a current World hold or a Game Session terminal outcome. ### gRPC Outcome Handling 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 36b6764bf5..f186df4238 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,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The latest inactive hold client reads the exact immutable identity, actual hold status and full lifecycle snapshot over workload mTLS. Common authored fixtures are shared rather than duplicated. The original STARTING association read carries the full stored post-authorization tuple and actual owner attempt/fence, but still requires an unexpired pending claim; it is not an after-expiry association endpoint. The composed local gate passed in 1m59s: 287 Common and 2,010 Game Session unit definitions had zero failures (17 Game Session skips); integration definitions executed 18 and skipped 200, while cross-service definitions executed one and skipped 38. Cached task outputs are included. Physical Game Session job `114071452179` on `c79103014c1b991f4caaa3f1fef04652ec1adda8` failed 21 of 218 integration cases: 20 shared fixture timestamp violations and one fresh source-bound tenant guard rejecting a canonical pointer insert. Replacement physical proof remains required after the corrections. Hold snapshots and retained tuples do not supply continuous commit authority; the separately typed authenticated World/Account original-owner producer remains incomplete. + Game Session has an unregistered original-claim evidence-continuation preparation: owner repositories, typed read/pin carriers, before-and-after authenticated Account projection reads outside SQL, and database-clock claim/reference-expiry checks at descriptor pinning. Consolidated Common/Game Session unit and non-container integration checks pass, as do generated-source compilation, formatting, static analysis, and documentation checks. PostgreSQL fixtures cover expiry, exact replay, mismatch, and pin races but remain unexecuted locally without Docker. Genuine Account original-redeemed receiver revalidation and full pointer/audit/live-owner composition remain required; mocked responses do not prove that receiver. This preparation grants no new mutation authorization or admission and does not establish playable closure. The bounded contract is owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). The same inactive preparation includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These repositories, coordinator and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Earlier consolidated local checks passed in 2m36s and after exact parent reconciliation in 54s: 271 Common and 1,992 Game Session unit definitions had zero failures (17 Game Session skips); 208 integration definitions executed 18 and skipped 190 without Docker, while cross-service definitions executed one and skipped 38. These include reused task outputs rather than a claim that every definition executed again. The PostgreSQL fixtures compile but have not physically executed locally. Document's published `2cb445617` supplies the canonical World hold request and immutable identity, including both origin selectors and the request-binding digest; the older numeric hold RPC is not that interface. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. @@ -14,7 +16,7 @@ The newer inactive consumer adds exact mTLS World acquisition/identity and lifec The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. Historical and current bounded proof, failures, and pending physical validation are recorded below. Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Hosted-terms acceptance, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898/#2848 and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). -Proof qualification for the Account source/currentness cut: historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` results remain historical evidence only. Physical Account job `114042562197` on `c69fa3645f3ddf16d2eaafd3838a29a52141736f` executed 98 integration cases with zero skips and one canonical-order Game Logic fixture failure; its correction passed Account job `114050124577` on `fb6ca4dd29fa3f39407f7f2cc32a016fab155403`. The subsequent `f1ed94a42dfdcb1f63bf52c95c60e9e5744af4b7` Account job `114059401680` in run `38001172632`, artifact `11648894382`, executed 101 PostgreSQL integration cases with zero skips and one trigger-catalog fixture failure. The new inspection-lock, immutable TRUNCATE and exact disclosure-source regressions passed. PostgreSQL truncates identifiers to its `name` type's capacity; the catalog assertion now compares through `?::name` while retaining enabled statement-level TRUNCATE checks and actual rejection tests. Final V94 empty optional region/spawn inventory settlement and V97 malformed/missing source-vector rejection regressions require replacement physical CI. The required Validation Gate remains red until that corrected candidate passes. This bounded evidence does not establish runtime activation or playable closure. +Proof qualification for the Account source/currentness cut: historical `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` results remain historical evidence only. Physical Account job `114042562197` on `c69fa3645f3ddf16d2eaafd3838a29a52141736f` executed 98 integration cases with zero skips and one canonical-order Game Logic fixture failure; its correction passed Account job `114050124577` on `fb6ca4dd29fa3f39407f7f2cc32a016fab155403`. The subsequent `f1ed94a42dfdcb1f63bf52c95c60e9e5744af4b7` Account job `114059401680` in run `38001172632`, artifact `11648894382`, executed 101 PostgreSQL integration cases with zero skips and one trigger-catalog fixture failure. The new inspection-lock, immutable TRUNCATE and exact disclosure-source regressions passed. PostgreSQL truncates identifiers to its `name` type's capacity; the catalog assertion now compares through `?::name` while retaining enabled statement-level TRUNCATE checks and actual rejection tests. The final `14eaa6c9568928f0079830159ac66f37ead2c146` Account job `114067421524` in run `38003644164` passed its physical integration task with Docker active, including the corrected settlement/source-vector fixture classes in its aggregate JaCoCo execution inventory. Successful case-level JUnit totals were not retained, so no new exact per-case counts are claimed. All five required exact-head gates and subsequent metadata-preservation gates passed. This bounded evidence does not establish runtime activation or playable closure. Canonical first-JOIN membership-event production requires current public-JOIN entitlement; a bare fresh tenant 1/1 baseline is denied and does not preserve admission. Tenant authority requires Account's exact typed tenant event, fresh Game Design provenance, and matching composite generation/source-version and billing coordinates. No entitlement caller wires this producer, so this does not activate public JOIN or gameplay admission. Historical gate 108 passed 593 Account unit cases and five focused shared World hold cases. Later gate 123 passed 598 Account unit cases, and gate 124 passed 27 focused shared-evidence cases across a broader selection; these are distinct executed snapshots and suite scopes, not conflicting totals. jOOQ generation and integration-test compilation passed. Published checkpoint `b5234acd7f93440170178d1b808e19b4a00ac644` subsequently passed required CI. PostgreSQL-backed integration sources, including the later-generation JOIN and exact outbox replay cases, remain unexecuted locally; neither unit proof nor historical CI establishes fresh-image playable proof for subsequent corrections. diff --git a/protos/world-management/v1/world_canonical_initial_admission_hold.proto b/protos/world-management/v1/world_canonical_initial_admission_hold.proto index f33c447ac0..2f48ee952d 100644 --- a/protos/world-management/v1/world_canonical_initial_admission_hold.proto +++ b/protos/world-management/v1/world_canonical_initial_admission_hold.proto @@ -12,6 +12,8 @@ service WorldCanonicalInitialAdmissionHoldService { returns (AcquireCanonicalInitialAdmissionHoldResponse); rpc ReadCanonicalInitialAdmissionHoldIdentity(ReadCanonicalInitialAdmissionHoldIdentityRequest) returns (ReadCanonicalInitialAdmissionHoldIdentityResponse); + rpc ReadCanonicalInitialAdmissionHoldState(ReadCanonicalInitialAdmissionHoldStateRequest) + returns (ReadCanonicalInitialAdmissionHoldStateResponse); } message AcquireCanonicalInitialAdmissionHoldRequest { @@ -43,3 +45,22 @@ message ReadCanonicalInitialAdmissionHoldIdentityResponse { // admission, or an absence checkpoint. bytes hold_identity_bytes = 2; } + +message ReadCanonicalInitialAdmissionHoldStateRequest { + // Fresh non-nil UUID correlation for this read, in canonical lowercase form. + string read_request_id = 1; + + // Complete immutable World-issued hold identity bytes, not merely the acquisition request. + bytes hold_identity_bytes = 2; + + // Complete closed canonical World lifecycle read request for the same target and read UUID. + bytes canonical_lifecycle_read_request_bytes = 3; +} + +message ReadCanonicalInitialAdmissionHoldStateResponse { + // Exact correlation echoed from this read request. + string read_request_id = 1; + + // Closed canonical same-snapshot hold status and complete lifecycle evidence. + bytes hold_state_bytes = 2; +} diff --git a/services/common-platform-core/build.gradle.kts b/services/common-platform-core/build.gradle.kts index 8f5694b6ca..33363ac22c 100644 --- a/services/common-platform-core/build.gradle.kts +++ b/services/common-platform-core/build.gradle.kts @@ -1,5 +1,6 @@ plugins { `java-library` + `java-test-fixtures` } apply(from = "${rootDir}/gradle/proto-convention.gradle") @@ -27,4 +28,6 @@ dependencies { compileOnly(libs.spotbugs.annotations) testImplementation(libs.grpc.spring.boot.starter) testImplementation(libs.spring.boot.starter.test) + testFixturesApi(platform(libs.spring.boot.dependencies)) + testFixturesApi("tools.jackson.core:jackson-databind") } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java new file mode 100644 index 0000000000..4c72e7064d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java @@ -0,0 +1,205 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed same-snapshot readback of a canonical initial-admission hold and its current lifecycle. + * + *

This is evidence of one observed owner snapshot, not a continuous hold, an admission grant, or + * authorization to mutate either owner's state. + */ +public record WorldCanonicalInitialAdmissionHoldState( + WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity, + HoldStatus holdStatus, + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence) { + public static final String SCHEMA = "world-canonical-initial-admission-hold-state/v1"; + public static final int MAX_CANONICAL_BYTES = 4 * 1024 * 1024; + private static final int MAX_HOLD_IDENTITY_BYTES = 64 * 1024; + private static final int MAX_LIFECYCLE_EVIDENCE_BYTES = 2 * 1024 * 1024; + private static final Set FIELDS = + Set.of("schema", "holdIdentityBytesBase64", "holdStatus", "lifecycleEvidenceBytesBase64"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + public WorldCanonicalInitialAdmissionHoldState { + Objects.requireNonNull(holdIdentity, "holdIdentity"); + Objects.requireNonNull(holdStatus, "holdStatus"); + Objects.requireNonNull(lifecycleEvidence, "lifecycleEvidence"); + requireTargetBinding(holdIdentity, lifecycleEvidence); + if (holdIdentity.canonicalBytes().length > MAX_HOLD_IDENTITY_BYTES + || lifecycleEvidence.canonicalBytes().length > MAX_LIFECYCLE_EVIDENCE_BYTES) { + throw new IllegalArgumentException("Canonical World hold-state evidence exceeds its limit"); + } + } + + /** + * Exact canonical readback bytes, including immutable identity and complete current lifecycle. + */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put( + "holdIdentityBytesBase64", + Base64.getEncoder().encodeToString(holdIdentity.canonicalBytes())); + value.put("holdStatus", holdStatus.name()); + value.put( + "lifecycleEvidenceBytesBase64", + Base64.getEncoder().encodeToString(lifecycleEvidence.canonicalBytes())); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (canonical.length > MAX_CANONICAL_BYTES) { + throw new IllegalStateException("Canonical World hold-state evidence exceeds its limit"); + } + return canonical; + } catch (IOException impossible) { + throw new IllegalStateException( + "Canonical World hold-state evidence cannot be encoded", impossible); + } + } + + /** + * This one read can identify the currently pending hold at its expected active epoch. It does not + * prove that protection remains continuous after this snapshot or authorize a commit. + */ + public boolean isPendingAtExpectedActiveEpoch() { + return holdStatus == HoldStatus.PENDING + && "ACTIVE".equals(lifecycleEvidence.lifecycleStatus()) + && lifecycleEvidence.lifecycleEpoch() == holdIdentity.request().activeLifecycleEpoch(); + } + + /** Decodes only complete, canonical, bounded state and both exact nested owner records. */ + public static WorldCanonicalInitialAdmissionHoldState fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + if (stored.length == 0 || stored.length > MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Canonical World hold-state evidence exceeds its limit"); + } + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root); + if (!SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported canonical World hold-state schema"); + } + byte[] identityBytes = decodeBase64(root, "holdIdentityBytesBase64"); + byte[] lifecycleBytes = decodeBase64(root, "lifecycleEvidenceBytesBase64"); + if (identityBytes.length == 0 + || identityBytes.length > MAX_HOLD_IDENTITY_BYTES + || lifecycleBytes.length == 0 + || lifecycleBytes.length > MAX_LIFECYCLE_EVIDENCE_BYTES) { + throw new IllegalArgumentException( + "Canonical World hold-state component exceeds its limit"); + } + WorldCanonicalInitialAdmissionHold.HoldIdentity identity = + WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(identityBytes); + WorldCanonicalInstanceLifecycleEvidence lifecycle = + WorldCanonicalInstanceLifecycleEvidence.fromStored(lifecycleBytes); + WorldCanonicalInitialAdmissionHoldState state = + new WorldCanonicalInitialAdmissionHoldState( + identity, parseStatus(text(root, "holdStatus")), lifecycle); + if (!Arrays.equals(stored, state.canonicalBytes())) { + throw new IllegalArgumentException("Canonical World hold-state evidence is not canonical"); + } + return state; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Canonical World hold-state evidence is invalid", invalid); + } + } + + private static void requireTargetBinding( + WorldCanonicalInitialAdmissionHold.HoldIdentity identity, + WorldCanonicalInstanceLifecycleEvidence lifecycle) { + var hold = identity.request(); + var current = lifecycle.request(); + if (!hold.targetNamespace().equals(current.targetNamespace()) + || !hold.canonicalTenantId().equals(current.canonicalTenantId()) + || !hold.worldSlug().equals(current.worldSlug()) + || !hold.canonicalGameInstanceId().equals(current.canonicalGameInstanceId()) + || !hold.playableStateNamespaceId().equals(current.playableStateNamespaceId()) + || !hold.playableStateScope().equals(current.playableStateScope()) + || !hold.canonicalVersionId().equals(current.canonicalVersionId()) + || !current.publicProduction()) { + throw new IllegalArgumentException( + "Canonical World hold state differs from the complete lifecycle target scope"); + } + } + + private static HoldStatus parseStatus(String status) { + try { + return HoldStatus.valueOf(status); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Unsupported canonical World initial-admission hold status", invalid); + } + } + + private static byte[] decodeBase64(JsonNode object, String field) { + String encoded = text(object, field); + try { + byte[] decoded = Base64.getDecoder().decode(encoded); + if (!Base64.getEncoder().encodeToString(decoded).equals(encoded)) { + throw new IllegalArgumentException(field + " must use canonical base64"); + } + return decoded; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must use canonical base64", invalid); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "Canonical World hold-state bytes are not strict UTF-8", invalid); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException(field + " must be text"); + } + return value.textValue(); + } + + private static void requireFields(JsonNode object) { + if (object == null || !object.isObject()) { + throw new IllegalArgumentException("Canonical World hold-state evidence must be an object"); + } + Set actual = new java.util.HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(FIELDS)) { + throw new IllegalArgumentException( + "Canonical World hold-state evidence has missing or unsupported fields"); + } + } + + public enum HoldStatus { + PENDING, + RECONCILIATION_REQUIRED, + COMMITTED, + ABORTED + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java new file mode 100644 index 0000000000..061d7b3d0b --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java @@ -0,0 +1,202 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInitialAdmissionHoldStateTest { + private static final UUID REALM = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID HOLD_FENCE = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + + @Test + void completePendingActiveStateRoundTripsExactNestedOwnerBytes() throws Exception { + WorldCanonicalInstanceLifecycleEvidence lifecycle = + AuthoringFixtures.lifecycleEvidence("ACTIVE", 3L); + Request request = holdRequest(lifecycle); + var identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + var state = + new WorldCanonicalInitialAdmissionHoldState( + identity, WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, lifecycle); + + byte[] encoded = state.canonicalBytes(); + var decoded = WorldCanonicalInitialAdmissionHoldState.fromStored(encoded); + + assertThat(decoded).isEqualTo(state); + assertThat(decoded.isPendingAtExpectedActiveEpoch()).isTrue(); + String encodedText = new String(encoded, StandardCharsets.UTF_8); + assertThat(encodedText) + .contains(java.util.Base64.getEncoder().encodeToString(identity.canonicalBytes())); + assertThat(encodedText) + .contains(java.util.Base64.getEncoder().encodeToString(lifecycle.canonicalBytes())); + } + + @Test + void nonterminalAndAdvancedLifecycleSamplesRemainHonestButDoNotQualify() throws Exception { + WorldCanonicalInstanceLifecycleEvidence active = + AuthoringFixtures.lifecycleEvidence("ACTIVE", 3L); + Request request = holdRequest(active); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + + for (var status : + List.of( + WorldCanonicalInitialAdmissionHoldState.HoldStatus.RECONCILIATION_REQUIRED, + WorldCanonicalInitialAdmissionHoldState.HoldStatus.COMMITTED, + WorldCanonicalInitialAdmissionHoldState.HoldStatus.ABORTED)) { + var state = new WorldCanonicalInitialAdmissionHoldState(identity, status, active); + assertThat(state.isPendingAtExpectedActiveEpoch()).isFalse(); + assertThat(WorldCanonicalInitialAdmissionHoldState.fromStored(state.canonicalBytes())) + .isEqualTo(state); + } + + var advanced = AuthoringFixtures.lifecycleEvidence("TERMINATING", 4L); + var observed = + new WorldCanonicalInitialAdmissionHoldState( + identity, WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, advanced); + assertThat(observed.lifecycleEvidence().lifecycleStatus()).isEqualTo("TERMINATING"); + assertThat(observed.lifecycleEvidence().lifecycleEpoch()).isEqualTo(4L); + assertThat(observed.isPendingAtExpectedActiveEpoch()).isFalse(); + assertThat(WorldCanonicalInitialAdmissionHoldState.fromStored(observed.canonicalBytes())) + .isEqualTo(observed); + } + + @Test + void rejectsChangedTargetScopeWithoutEquatingIndependentRequestIds() throws Exception { + WorldCanonicalInstanceLifecycleEvidence lifecycle = + AuthoringFixtures.lifecycleEvidence("ACTIVE", 3L); + Request original = holdRequest(lifecycle); + Request mismatched = + new Request( + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + REALM, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + original.playableStateScope(), + original.canonicalGameInstanceId(), + original.canonicalVersionId(), + original.activeLifecycleEpoch(), + original.initialAdmissionRequestId(), + original.initialAdmissionRequestDigest(), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + + assertThatThrownBy( + () -> + new WorldCanonicalInitialAdmissionHoldState( + new HoldIdentity(mismatched, HOLD_ID, HOLD_FENCE), + WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, + lifecycle)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("target scope"); + + Request independentRequestId = + new Request( + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + original.realmId(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.canonicalGameInstanceId(), + original.canonicalVersionId(), + original.activeLifecycleEpoch(), + "a-distinct-initial-admission-request-id", + original.initialAdmissionRequestDigest(), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + assertThat( + new WorldCanonicalInitialAdmissionHoldState( + new HoldIdentity(independentRequestId, HOLD_ID, HOLD_FENCE), + WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, + lifecycle) + .lifecycleEvidence() + .request() + .controlPlaneRequestId()) + .isEqualTo(lifecycle.request().controlPlaneRequestId()); + assertThat(independentRequestId.initialAdmissionRequestId()) + .isNotEqualTo(lifecycle.request().controlPlaneRequestId()); + } + + @Test + void rejectsUnknownDuplicateNoncanonicalMalformedAndOversizedState() throws Exception { + var lifecycle = AuthoringFixtures.lifecycleEvidence("ACTIVE", 3L); + var state = + new WorldCanonicalInitialAdmissionHoldState( + new HoldIdentity(holdRequest(lifecycle), HOLD_ID, HOLD_FENCE), + WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, + lifecycle); + String canonical = new String(state.canonicalBytes(), StandardCharsets.UTF_8); + + assertInvalid(canonical.replace("\"schema\":", "\"extra\":true,\"schema\":")); + String duplicateSchema = + "\"schema\":\"" + + WorldCanonicalInitialAdmissionHoldState.SCHEMA + + "\",\"schema\":\"" + + WorldCanonicalInitialAdmissionHoldState.SCHEMA + + "\""; + assertInvalid( + canonical.replace( + "\"schema\":\"" + WorldCanonicalInitialAdmissionHoldState.SCHEMA + "\"", + duplicateSchema)); + assertInvalid(canonical.replace("PENDING", "UNKNOWN")); + assertInvalid(canonical.replace(",\"holdStatus\":\"PENDING\"", "")); + assertInvalid( + canonical.replace( + java.util.Base64.getEncoder().encodeToString(state.holdIdentity().canonicalBytes()), + "!")); + assertInvalid(canonical + " "); + assertThatThrownBy( + () -> + WorldCanonicalInitialAdmissionHoldState.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strict UTF-8"); + assertThatThrownBy( + () -> + WorldCanonicalInitialAdmissionHoldState.fromStored( + new byte[WorldCanonicalInitialAdmissionHoldState.MAX_CANONICAL_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("limit"); + } + + private static void assertInvalid(String value) { + assertThatThrownBy( + () -> + WorldCanonicalInitialAdmissionHoldState.fromStored( + value.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Request holdRequest(WorldCanonicalInstanceLifecycleEvidence lifecycle) { + var request = lifecycle.request(); + return new Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + REALM, + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + 3L, + "initial-admission-independent-from-preparation-request", + "a".repeat(64), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java similarity index 80% rename from services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java rename to services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java index 897e2d90f4..5ed99a5545 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java @@ -18,7 +18,12 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.node.ObjectNode; @@ -99,6 +104,113 @@ public static WorldPublishedStartLocationEvidence startLocationEvidence() throws request, receipt, committed.fullBinding(), committed.result()); } + public static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence(String status, long epoch) + throws Exception { + WorldPublishedStartLocationEvidence selector = startLocationEvidence(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + selectorReceipt.startLocation(), + 1042L, + status, + epoch, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64), + Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + public static byte[] accountBinding(DraftCommitBinding draft) { byte[] draftBytes = draft.canonicalBytes(); return new DraftAuthorizationFenceBinding( diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 046cb29776..2d0112cfc8 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -93,6 +93,7 @@ dependencies { testFixturesCompileOnly(libs.testcontainers.postgresql) testFixturesCompileOnly(libs.testcontainers) testImplementation(libs.grpc.inprocess) + testImplementation(testFixtures(project(":common-platform-core"))) testImplementation(testFixtures(project(":game-session-service"))) testImplementation(project(":game-logic-service")) } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java index 2e69052bc5..a29ab3f7eb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java @@ -20,9 +20,11 @@ import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldRequest; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldStateRequest; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldServiceGrpc; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -131,6 +133,54 @@ public HoldIdentity readIdentity(Request holdRequest) { } } + /** + * Reads one authenticated World snapshot for the exact immutable hold and lifecycle request. The + * returned state is observational only; it does not prove continuing protection or authorize an + * admission-pointer commit. + */ + public WorldCanonicalInitialAdmissionHoldState readState( + HoldIdentity holdIdentity, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + requireNoAmbientOwnerTransaction(); + Objects.requireNonNull(holdIdentity, "holdIdentity"); + Request holdRequest = holdIdentity.request(); + requireConfiguredNamespace(holdRequest); + requireLifecycleStateReadRequestMatches(holdRequest, lifecycleRequest); + + UUID readRequestId = lifecycleRequest.readRequestId(); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readCanonicalInitialAdmissionHoldState( + ReadCanonicalInitialAdmissionHoldStateRequest.newBuilder() + .setReadRequestId(readRequestId.toString()) + .setHoldIdentityBytes(ByteString.copyFrom(holdIdentity.canonicalBytes())) + .setCanonicalLifecycleReadRequestBytes( + ByteString.copyFrom(lifecycleRequest.canonicalBytes())) + .build()); + try { + requireNoUnknownFields(response, "ReadCanonicalInitialAdmissionHoldStateResponse"); + if (!readRequestId.toString().equals(response.getReadRequestId())) { + throw new IllegalArgumentException( + "World initial-admission state read changed its correlation UUID"); + } + WorldCanonicalInitialAdmissionHoldState state = + WorldCanonicalInitialAdmissionHoldState.fromStored( + response.getHoldStateBytes().toByteArray()); + if (!holdIdentity.equals(state.holdIdentity())) { + throw new IllegalArgumentException( + "World initial-admission state changed the exact immutable hold identity"); + } + if (!lifecycleRequest.equals(state.lifecycleEvidence().request())) { + throw new IllegalArgumentException( + "World initial-admission state changed the complete lifecycle read request"); + } + return state; + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid canonical initial-admission hold state", invalid); + } + } + @Override protected String configuredTarget(ServiceEndpointsProperties endpoints) { return endpoints.getWorldManagementService(); @@ -200,6 +250,27 @@ private void requireLifecycleRequestMatches( } } + private void requireLifecycleStateReadRequestMatches( + Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); + if (!lifecycleRequest.publicProduction()) { + throw new IllegalArgumentException( + "World initial-admission hold-state reads require public-production lifecycle evidence"); + } + if (!workloadNamespace.equals(lifecycleRequest.targetNamespace()) + || !holdRequest.canonicalTenantId().equals(lifecycleRequest.canonicalTenantId()) + || !holdRequest.worldSlug().equals(lifecycleRequest.worldSlug()) + || !holdRequest.canonicalGameInstanceId().equals(lifecycleRequest.canonicalGameInstanceId()) + || !holdRequest + .playableStateNamespaceId() + .equals(lifecycleRequest.playableStateNamespaceId()) + || !holdRequest.playableStateScope().equals(lifecycleRequest.playableStateScope()) + || !holdRequest.canonicalVersionId().equals(lifecycleRequest.canonicalVersionId())) { + throw new IllegalArgumentException( + "World lifecycle request must bind the exact initial-admission target"); + } + } + private static HoldIdentity decodeIdentity(byte[] encoded) { if (encoded.length == 0) { throw new IllegalArgumentException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java index 4b29e3106d..62db57c2fe 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java @@ -419,7 +419,7 @@ private OriginalStartSessionAssociation decodeOriginalStartSessionAssociation(Re throw new IllegalStateException( "Original StartSession descriptor or association pin differs from the STARTING binding"); } - return new OriginalStartSessionAssociation(association, ownerAttemptId, ownerFence); + return new OriginalStartSessionAssociation(association, tuple, ownerAttemptId, ownerFence); } private static Result decodeAssociationPin( @@ -1242,11 +1242,24 @@ private record GameInstanceRow( /** Owner-derived association readback; deliberately not an AttemptClaim or continuation token. */ public record OriginalStartSessionAssociation( - CanonicalGameInstanceLaunchAssociation association, UUID ownerAttemptId, long ownerFence) { + CanonicalGameInstanceLaunchAssociation association, + StartSessionPostAuthorizationExecutionTuple postAuthorizationExecutionTuple, + UUID ownerAttemptId, + long ownerFence) { public OriginalStartSessionAssociation { Objects.requireNonNull(association, "association"); + Objects.requireNonNull(postAuthorizationExecutionTuple, "postAuthorizationExecutionTuple"); requireNonNil(ownerAttemptId, "ownerAttemptId"); requirePositive(ownerFence, "ownerFence"); + var scope = postAuthorizationExecutionTuple.preAuthorizationTuple().action().scope(); + if (!association.targetNamespace().equals(scope.targetNamespace()) + || !association.canonicalTenantId().equals(scope.tenantId()) + || !association + .controlPlaneRequestId() + .equals(postAuthorizationExecutionTuple.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Original StartSession tuple differs from its retained association scope"); + } } } diff --git a/services/game-session-service/src/main/resources/db/migration/V39__canonical_initial_admission_fresh_scope_guard.sql b/services/game-session-service/src/main/resources/db/migration/V39__canonical_initial_admission_fresh_scope_guard.sql new file mode 100644 index 0000000000..b185fd698f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V39__canonical_initial_admission_fresh_scope_guard.sql @@ -0,0 +1,143 @@ +-- Forward-only correction; preserve the already published V28 migration bytes. +-- [jooq ignore start] +-- Fresh source-bound tenant keys may back canonical OPEN pointer and audit rows only when the +-- exact pending initial-admission ledger entry, source-qualified tenant association, and launch +-- binding all agree. Numeric-only tenant writes retain the V25/V26 denial. +CREATE OR REPLACE FUNCTION reserve_game_session_tenant_scope() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + current_kind VARCHAR(32); +BEGIN + IF TG_OP = 'UPDATE' AND NEW.tenant_id IS NOT DISTINCT FROM OLD.tenant_id THEN + RETURN NEW; + END IF; + IF NEW.tenant_id IS NULL THEN + RETURN NEW; + END IF; + IF NEW.tenant_id <= 0 THEN + RAISE EXCEPTION 'Game Session tenant scope must be positive' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_tenant_scope_reservation_positive'; + END IF; + + INSERT INTO game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind) + VALUES (NEW.tenant_id, 'LEGACY_OCCUPIED') + ON CONFLICT (game_session_tenant_id) DO NOTHING; + + SELECT reservation_kind INTO current_kind + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = NEW.tenant_id + FOR KEY SHARE; + + IF current_kind = 'FRESH_SOURCE_BOUND' AND TG_TABLE_NAME = 'game_instances' + AND EXISTS ( + SELECT 1 + FROM game_session_tenant_canonical_claim claim + JOIN game_session_fresh_tenant_association association + ON association.target_namespace = claim.target_namespace + AND association.canonical_tenant_id = claim.canonical_tenant_id + AND association.legacy_game_session_tenant_id = claim.legacy_game_session_tenant_id + AND association.association_operation_id = claim.association_operation_id + AND association.association_kind = claim.association_kind + WHERE claim.legacy_game_session_tenant_id = NEW.tenant_id + AND claim.association_kind = 'FRESH_SOURCE_BOUND' + AND association.association_kind = 'FRESH_SOURCE_BOUND' + ) THEN + RETURN NEW; + END IF; + + IF current_kind = 'FRESH_SOURCE_BOUND' + AND TG_TABLE_NAME IN ('gameplay_admission_pointer', 'gameplay_admission_pointer_event') THEN + IF NEW.representation_version = 3 + AND NEW.admission_state = 'OPEN' + AND EXISTS ( + SELECT 1 + FROM game_session_canonical_initial_admission_attempt attempt + JOIN game_session_canonical_instance_launch launch + ON launch.target_namespace = attempt.target_namespace + AND launch.canonical_tenant_id = attempt.canonical_tenant_id + AND launch.canonical_realm_id = attempt.realm_id + AND launch.world_slug = attempt.world_slug + AND launch.playable_state_namespace_id = attempt.playable_state_namespace_id + AND launch.playable_state_scope = attempt.playable_state_scope + AND launch.game_session_tenant_id = attempt.game_session_tenant_id + AND launch.game_instance_id = attempt.game_instance_id + AND launch.game_instance_uuid = attempt.canonical_game_instance_id + AND launch.version_id = attempt.runtime_version_id + AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = attempt.canonical_version_id::text + JOIN game_session_tenant_canonical_claim claim + ON claim.target_namespace = launch.target_namespace + AND claim.canonical_tenant_id = launch.canonical_tenant_id + AND claim.legacy_game_session_tenant_id = launch.game_session_tenant_id + AND claim.association_operation_id = launch.tenant_association_operation_id + AND claim.association_request_id = launch.tenant_association_request_id + AND claim.association_kind = launch.tenant_association_kind + AND claim.association_kind = 'FRESH_SOURCE_BOUND' + AND claim.reservation_kind = 'FRESH_SOURCE_BOUND' + JOIN game_session_fresh_tenant_association source_association + ON source_association.target_namespace = claim.target_namespace + AND source_association.canonical_tenant_id = claim.canonical_tenant_id + AND source_association.legacy_game_session_tenant_id = claim.legacy_game_session_tenant_id + AND source_association.association_operation_id = claim.association_operation_id + AND source_association.association_request_id = launch.tenant_association_request_id + AND source_association.source_schema_version = launch.tenant_source_schema_version + AND source_association.source_target_namespace = launch.tenant_source_target_namespace + AND source_association.source_request_id = launch.tenant_source_request_id + AND source_association.source_canonical_tenant_id = launch.tenant_source_canonical_tenant_id + AND source_association.source_game_row_id = launch.tenant_source_game_row_id + AND source_association.source_game_tenant_key = launch.tenant_source_game_tenant_key + AND source_association.provenance_kind = launch.tenant_source_provenance_kind + AND source_association.association_kind = launch.tenant_association_kind + WHERE attempt.status = 'PENDING' + AND attempt.target_namespace = NEW.target_namespace + AND attempt.initial_admission_request_id = NEW.initial_admission_request_id + AND attempt.request_digest = NEW.initial_admission_request_digest + AND attempt.canonical_tenant_id = NEW.canonical_tenant_id + AND attempt.world_slug = NEW.world_slug + AND attempt.realm_id = NEW.realm_id + AND attempt.playable_state_namespace_id = NEW.playable_state_namespace_id + AND attempt.playable_state_scope = NEW.state_scope + AND attempt.canonical_game_instance_id = NEW.canonical_game_instance_id + AND attempt.canonical_version_id = NEW.canonical_version_id + AND attempt.game_session_tenant_id = NEW.tenant_id + AND attempt.game_instance_id = NEW.game_instance_id + AND attempt.runtime_version_id = NEW.runtime_version_id + AND attempt.expected_catalog_revision = NEW.catalog_revision + AND attempt.origin_kind = NEW.initial_admission_origin_kind + AND attempt.expected_prior_pointer_version IS NOT DISTINCT FROM + NEW.initial_admission_prior_pointer_version + AND attempt.active_lifecycle_epoch = NEW.initial_admission_active_epoch + AND attempt.hold_id = NEW.initial_admission_hold_id + AND attempt.hold_fence = NEW.initial_admission_hold_fence + AND attempt.hold_binding_digest = NEW.initial_admission_hold_binding_digest + ) THEN + IF TG_TABLE_NAME = 'gameplay_admission_pointer' THEN + IF NEW.last_updated_by IS DISTINCT FROM 'game-session-canonical-initial-admission' + OR NEW.last_update_reason IS DISTINCT FROM 'World-held initial admission' THEN + RAISE EXCEPTION 'Canonical OPEN pointer requires its exact initial-admission owner audit identity' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_canonical_initial_admission_owner_write'; + END IF; + END IF; + IF TG_TABLE_NAME = 'gameplay_admission_pointer_event' THEN + IF NEW.control_plane_request_id IS DISTINCT FROM NEW.initial_admission_request_id + OR NEW.actor_principal IS DISTINCT FROM 'game-session-canonical-initial-admission' + OR NEW.reason IS DISTINCT FROM 'World-held initial admission' THEN + RAISE EXCEPTION 'Canonical OPEN audit event requires its exact initial-admission owner identity' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_canonical_initial_admission_owner_write'; + END IF; + END IF; + RETURN NEW; + END IF; + END IF; + + IF current_kind IS DISTINCT FROM 'LEGACY_OCCUPIED' THEN + RAISE EXCEPTION 'Numeric-only tenant scope cannot use a fresh source-bound key' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_numeric_fresh_tenant_scope_denied'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index 8bbd9b58b6..99de8fdb19 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -157,6 +157,67 @@ void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { .get(0, Long.class))) .isZero(); + UUID mismatchedGameInstance = uuid(998); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "INSERT INTO gameplay_admission_pointer_event (" + + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, actor_principal, reason, " + + "control_plane_request_id, occurred_at, prepared_version_upgrade_id, " + + "public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state, canonical_game_instance_id, " + + "canonical_version_id, runtime_version_id, initial_admission_request_id, " + + "initial_admission_request_digest, initial_admission_origin_kind, " + + "initial_admission_prior_pointer_version, initial_admission_active_epoch, " + + "initial_admission_hold_id, initial_admission_hold_fence, " + + "initial_admission_hold_binding_digest) " + + "SELECT attempt.world_slug, catalog.realm_slug, catalog.source_world_display_name, " + + "catalog.realm_display_name, attempt.game_session_tenant_id, attempt.game_instance_id, " + + "CASE WHEN attempt.origin_kind = 'NO_PRIOR_POINTER' THEN 1 " + + "ELSE attempt.expected_prior_pointer_version + 1 END, catalog.visible, NULL, " + + "attempt.playable_state_scope, catalog.character_creation_policy, " + + "'game-session-canonical-initial-admission', 'World-held initial admission', " + + "attempt.initial_admission_request_id, CURRENT_TIMESTAMP, NULL, " + + "catalog.public_production, attempt.expected_catalog_revision, attempt.realm_id, " + + "attempt.playable_state_namespace_id, 3, attempt.target_namespace, " + + "attempt.canonical_tenant_id, 'OPEN', ?, attempt.canonical_version_id, " + + "attempt.runtime_version_id, attempt.initial_admission_request_id, " + + "attempt.request_digest, attempt.origin_kind, attempt.expected_prior_pointer_version, " + + "attempt.active_lifecycle_epoch, attempt.hold_id, attempt.hold_fence, " + + "attempt.hold_binding_digest " + + "FROM game_session_canonical_initial_admission_attempt attempt " + + "JOIN game_session_canonical_realm_catalog catalog " + + "ON catalog.target_namespace = attempt.target_namespace " + + "AND catalog.canonical_tenant_id = attempt.canonical_tenant_id " + + "AND catalog.realm_id = attempt.realm_id " + + "AND catalog.catalog_revision = attempt.expected_catalog_revision " + + "JOIN game_session_canonical_instance_launch launch " + + "ON launch.target_namespace = attempt.target_namespace " + + "AND launch.canonical_tenant_id = attempt.canonical_tenant_id " + + "AND launch.canonical_realm_id = attempt.realm_id " + + "AND launch.game_session_tenant_id = attempt.game_session_tenant_id " + + "AND launch.game_instance_id = attempt.game_instance_id " + + "AND launch.game_instance_uuid = attempt.canonical_game_instance_id " + + "AND launch.version_id = attempt.runtime_version_id " + + "WHERE attempt.target_namespace = ? " + + "AND attempt.initial_admission_request_id = ? AND attempt.status = 'PENDING'", + mismatchedGameInstance, + NAMESPACE, + request.initialAdmissionRequestId())) + .hasMessageContaining("Numeric-only tenant scope cannot use a fresh source-bound key"); + assertThat( + fixture.initialAdmissionRepository.read(NAMESPACE, request.initialAdmissionRequestId())) + .map(CanonicalInitialAdmissionOwnerProof::outcome) + .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_admission_pointer_event")), + DSL.field(DSL.name("representation_version"), Integer.class).eq(3))) + .isZero(); + fixture.transactions.execute( status -> { fixture.initialAdmissionRepository.commit(request, worldProof, null); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java index ef984cca2e..915cb442a1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java @@ -74,6 +74,9 @@ void readsOnlyTheExactRetainedAssociationAndDescriptorForTheOriginalPendingAttem fixture.read(selector(starting.startingInstance().launchAssociation())).orElseThrow(); assertThat(read.association()).isEqualTo(starting.startingInstance().launchAssociation()); + assertThat(read.postAuthorizationExecutionTuple()).isEqualTo(tuple); + assertThat(read.postAuthorizationExecutionTuple().canonicalBytes()) + .containsExactly(tuple.canonicalBytes()); assertThat(read.ownerAttemptId()).isEqualTo(starting.claim().ownerAttemptId()); assertThat(read.ownerFence()).isEqualTo(starting.claim().ownerFence()).isPositive(); assertThat( 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 d595db53ee..270a69dd14 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 @@ -7,6 +7,7 @@ import java.nio.file.Path; import java.time.Duration; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Map; import java.util.Objects; @@ -428,7 +429,7 @@ void expiredOriginalReferenceBlocksContinuationWhileTheOwnerClaimRemainsLive() { void descriptorInsertRechecksOriginalReferenceExpiryAfterContinuationPrechecks() throws Exception { Fixture fixture = fixture(Duration.ofSeconds(30)); - Instant authorityExpiresAt = Instant.now().plusSeconds(15); + Instant authorityExpiresAt = Instant.now().truncatedTo(ChronoUnit.MILLIS).plusSeconds(15); StartSessionPostAuthorizationExecutionTuple tuple = tuple( "operator-attempt-descriptor-reference-expired", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java index 1bb568bb0c..6da7dcf5fc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java @@ -12,6 +12,7 @@ import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Base64; import java.util.HexFormat; @@ -119,7 +120,8 @@ class GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest { private static final ObjectMapper JSON = new ObjectMapper(); private static final String MIGRATION_LOCATION = "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); - private static final Instant AUTHORITY_REFERENCE_TIME = Instant.now(); + private static final Instant AUTHORITY_REFERENCE_TIME = + Instant.now().truncatedTo(ChronoUnit.MILLIS); private static final Instant AUTHORITY_EVALUATED_AT = AUTHORITY_REFERENCE_TIME.minusSeconds(60L); private static final Instant AUTHORITY_EXPIRES_AT = AUTHORITY_REFERENCE_TIME.plus(Duration.ofHours(1)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java index b44bc28746..64a371a80e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java @@ -38,15 +38,19 @@ 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.testing.AuthoringFixtures; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldRequest; import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldResponse; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityRequest; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldStateRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldStateResponse; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldServiceGrpc; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -54,7 +58,7 @@ import org.junit.jupiter.api.io.TempDir; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Physical mTLS proof for the opt-in Game Session to World hold identity client. */ +/** Physical mTLS proof for the opt-in Game Session to World hold identity and state client. */ class WorldCanonicalInitialAdmissionHoldClientTest { private static final String NAMESPACE = "test"; private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; @@ -82,6 +86,7 @@ class WorldCanonicalInitialAdmissionHoldClientTest { private AtomicReference receivedPeerUri; private AtomicReference receivedAcquire; private AtomicReference receivedRead; + private AtomicReference receivedStateRead; @BeforeAll static void createTrustedWorkloadCertificates() throws Exception { @@ -194,17 +199,32 @@ void rejectsWrongServerWorkloadBeforeRequestAndRejectsEmptyOrUnknownResponses() void requiresExplicitInitializationConfiguredNamespaceMatchingAndNoAmbientTransaction() throws Exception { Request request = request(); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); client = newClientPropertiesOnly(); assertThatThrownBy(() -> client.acquire(request, lifecycleRequest())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.readState(identity, lifecycleRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); assertThatThrownBy(() -> client.readIdentity(request("other"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.readState(identity, lifecycleRequest("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact initial-admission target"); assertThatThrownBy(() -> client.acquire(request, lifecycleRequest("other"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact initial-admission target"); + assertThatThrownBy( + () -> + client.readState( + identity, + lifecycleRequest( + NAMESPACE, true, uuid("99999999-9999-4999-8999-999999999999")))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact initial-admission target"); assertThatThrownBy(() -> lifecycleRequest(NAMESPACE, false)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("requires public-production evidence"); @@ -213,15 +233,176 @@ void requiresExplicitInitializationConfiguredNamespaceMatchingAndNoAmbientTransa assertThatThrownBy(() -> client.readIdentity(request)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no ambient owner transaction"); + assertThatThrownBy(() -> client.readState(identity, lifecycleRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + } + + @Test + void stateReadSendsExactIdentityAndLifecycleReadTupleAndRejectsMalformedOwnerBytes() + throws Exception { + Request request = request(); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + WorldCanonicalInstanceLifecycleEvidence.Request lifecycle = lifecycleRequest(); + startServer(pki.worldServer(), ResponseMode.MALFORMED_STATE, request); + client = newClient(server); + client.init(); + + assertThatThrownBy(() -> client.readState(identity, lifecycle)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical initial-admission hold state"); + + assertThat(applicationCalls).hasValue(1); + assertThat(serverCallStarts).hasValue(1); + assertThat(receivedPeerUri).hasValue(GAME_SESSION_URI); + assertThat(receivedStateRead.get().getReadRequestId()) + .isEqualTo(lifecycle.readRequestId().toString()); + assertThat(receivedStateRead.get().getHoldIdentityBytes().toByteArray()) + .containsExactly(identity.canonicalBytes()); + assertThat( + WorldCanonicalInstanceLifecycleEvidence.Request.fromStored( + receivedStateRead.get().getCanonicalLifecycleReadRequestBytes().toByteArray())) + .isEqualTo(lifecycle); + } + + @Test + void stateReadReturnsEveryTypedOwnerStateOverPhysicalMtlsWithoutInferringAdmission() + throws Exception { + WorldCanonicalInstanceLifecycleEvidence lifecycle = + AuthoringFixtures.lifecycleEvidence("ACTIVE", 7L); + Request request = stateHoldRequest(lifecycle); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + + for (WorldCanonicalInitialAdmissionHoldState.HoldStatus status : + List.of( + WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, + WorldCanonicalInitialAdmissionHoldState.HoldStatus.RECONCILIATION_REQUIRED, + WorldCanonicalInitialAdmissionHoldState.HoldStatus.COMMITTED, + WorldCanonicalInitialAdmissionHoldState.HoldStatus.ABORTED)) { + WorldCanonicalInitialAdmissionHoldState expected = + new WorldCanonicalInitialAdmissionHoldState(identity, status, lifecycle); + startServer(pki.worldServer(), ResponseMode.EXACT, request, expected.canonicalBytes()); + client = newClient(server); + client.init(); + + WorldCanonicalInitialAdmissionHoldState observed = + client.readState(identity, lifecycle.request()); + + assertThat(observed).isEqualTo(expected); + assertThat(observed.isPendingAtExpectedActiveEpoch()) + .isEqualTo(status == WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING); + assertThat(applicationCalls).hasValue(1); + assertThat(serverCallStarts).hasValue(1); + assertThat(receivedPeerUri).hasValue(GAME_SESSION_URI); + assertThat(receivedStateRead.get().getReadRequestId()) + .isEqualTo(lifecycle.request().readRequestId().toString()); + assertThat(receivedStateRead.get().getHoldIdentityBytes().toByteArray()) + .containsExactly(identity.canonicalBytes()); + assertThat(receivedStateRead.get().getCanonicalLifecycleReadRequestBytes().toByteArray()) + .containsExactly(lifecycle.request().canonicalBytes()); + stopTransport(); + } + } + + @Test + void stateReadRejectsAlteredIdentityLifecycleRequestAndNoncanonicalState() throws Exception { + WorldCanonicalInstanceLifecycleEvidence lifecycle = + AuthoringFixtures.lifecycleEvidence("ACTIVE", 7L); + Request request = stateHoldRequest(lifecycle); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + var status = WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING; + + var alteredIdentity = + new HoldIdentity(request, HOLD_ID, uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd")); + var identityMismatch = + new WorldCanonicalInitialAdmissionHoldState(alteredIdentity, status, lifecycle); + startServer(pki.worldServer(), ResponseMode.EXACT, request, identityMismatch.canonicalBytes()); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.readState(identity, lifecycle.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical initial-admission hold state"); + stopTransport(); + + var alteredLifecycle = + withReadRequestId(lifecycle, uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")); + var lifecycleMismatch = + new WorldCanonicalInitialAdmissionHoldState(identity, status, alteredLifecycle); + startServer(pki.worldServer(), ResponseMode.EXACT, request, lifecycleMismatch.canonicalBytes()); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.readState(identity, lifecycle.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical initial-admission hold state"); + stopTransport(); + + byte[] noncanonical = + (new String( + new WorldCanonicalInitialAdmissionHoldState(identity, status, lifecycle) + .canonicalBytes(), + StandardCharsets.UTF_8) + + " ") + .getBytes(StandardCharsets.UTF_8); + startServer(pki.worldServer(), ResponseMode.EXACT, request, noncanonical); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.readState(identity, lifecycle.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical initial-admission hold state"); + } + + @Test + void stateReadRejectsWrongPeerCorrelationAndUnknownResponseFieldsBeforeAcceptingState() + throws Exception { + Request request = request(); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + WorldCanonicalInstanceLifecycleEvidence.Request lifecycle = lifecycleRequest(); + + startServer(pki.wrongWorldServer(), ResponseMode.EMPTY_STATE, request); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.readState(identity, lifecycle)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(serverCallStarts).hasValue(0); + assertThat(applicationCalls).hasValue(0); + stopTransport(); + + startServer(pki.worldServer(), ResponseMode.WRONG_READ_REQUEST_ID, request); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.readState(identity, lifecycle)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical initial-admission hold state"); + assertThat(applicationCalls).hasValue(1); + stopTransport(); + + startServer(pki.worldServer(), ResponseMode.UNKNOWN_RESPONSE_FIELD, request); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.readState(identity, lifecycle)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical initial-admission hold state"); + assertThat(applicationCalls).hasValue(1); } private void startServer(TestIdentity identity, ResponseMode mode, Request expectedRequest) throws Exception { + startServer(identity, mode, expectedRequest, null); + } + + private void startServer( + TestIdentity identity, ResponseMode mode, Request expectedRequest, byte[] holdStateBytes) + throws Exception { applicationCalls = new AtomicInteger(); serverCallStarts = new AtomicInteger(); receivedPeerUri = new AtomicReference<>(); receivedAcquire = new AtomicReference<>(); receivedRead = new AtomicReference<>(); + receivedStateRead = new AtomicReference<>(); var service = new WorldCanonicalInitialAdmissionHoldServiceGrpc .WorldCanonicalInitialAdmissionHoldServiceImplBase() { @@ -265,6 +446,31 @@ public void readCanonicalInitialAdmissionHoldIdentity( observer.onCompleted(); } + @Override + public void readCanonicalInitialAdmissionHoldState( + ReadCanonicalInitialAdmissionHoldStateRequest request, + StreamObserver observer) { + applicationCalls.incrementAndGet(); + capturePeer(); + receivedStateRead.set(request); + ReadCanonicalInitialAdmissionHoldStateResponse.Builder response = + ReadCanonicalInitialAdmissionHoldStateResponse.newBuilder() + .setReadRequestId( + mode == ResponseMode.WRONG_READ_REQUEST_ID + ? uuid("ffffffff-ffff-4fff-8fff-ffffffffffff").toString() + : request.getReadRequestId()); + if (mode == ResponseMode.MALFORMED_STATE) { + response.setHoldStateBytes(ByteString.copyFrom(new byte[] {0x01, 0x02, 0x03})); + } else if (holdStateBytes != null) { + response.setHoldStateBytes(ByteString.copyFrom(holdStateBytes)); + } + if (mode == ResponseMode.UNKNOWN_RESPONSE_FIELD) { + response.setUnknownFields(unknownFields()); + } + observer.onNext(response.build()); + observer.onCompleted(); + } + private void capturePeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); receivedPeerUri.set(peer == null ? null : peer.uri()); @@ -350,6 +556,58 @@ private static Request request(String namespace, String requestId) { null); } + private static Request stateHoldRequest(WorldCanonicalInstanceLifecycleEvidence lifecycle) { + var request = lifecycle.request(); + return new Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + REALM, + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + lifecycle.lifecycleEpoch(), + REQUEST_ID, + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null); + } + + private static WorldCanonicalInstanceLifecycleEvidence withReadRequestId( + WorldCanonicalInstanceLifecycleEvidence lifecycle, UUID readRequestId) { + var source = lifecycle.request(); + var alteredRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + source.schemaVersion(), + readRequestId, + source.targetNamespace(), + source.canonicalTenantId(), + source.worldSlug(), + source.canonicalGameInstanceId(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.publicProduction(), + source.controlPlaneRequestId(), + source.canonicalVersionId(), + source.expectedDescriptorRequestDigest(), + source.expectedDescriptorResultDigest(), + source.expectedReleaseAttestationDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + alteredRequest, + lifecycle.launchBinding(), + lifecycle.startLocation(), + lifecycle.runtimeRoomInstanceId(), + lifecycle.lifecycleStatus(), + lifecycle.lifecycleEpoch(), + lifecycle.rowVersion(), + lifecycle.captureId(), + lifecycle.graphSha256(), + lifecycle.preparationInputDigest(), + lifecycle.operationalRegionAssignments()); + } + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest() { return lifecycleRequest(NAMESPACE, true); } @@ -361,13 +619,18 @@ private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( String namespace, boolean publicProduction) { + return lifecycleRequest(namespace, publicProduction, GAME_INSTANCE); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( + String namespace, boolean publicProduction, UUID gameInstanceId) { return new WorldCanonicalInstanceLifecycleEvidence.Request( WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), namespace, TENANT, "green-hollow", - GAME_INSTANCE, + gameInstanceId, PLAYABLE_NAMESPACE, "SHARED", publicProduction, @@ -384,6 +647,8 @@ private static UUID uuid(String value) { private enum ResponseMode { EXACT, + EMPTY_STATE, + MALFORMED_STATE, EMPTY_IDENTITY, UNKNOWN_RESPONSE_FIELD, WRONG_READ_REQUEST_ID, From 05f37d1028102e514e8a38fd10853c352dd9b211 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:39:12 +1300 Subject: [PATCH 06/22] Compare retained StartSession tuple by canonical bytes --- ...essionOriginalStartSessionAssociationReadIntegrationTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java index 915cb442a1..8028222986 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java @@ -74,7 +74,6 @@ void readsOnlyTheExactRetainedAssociationAndDescriptorForTheOriginalPendingAttem fixture.read(selector(starting.startingInstance().launchAssociation())).orElseThrow(); assertThat(read.association()).isEqualTo(starting.startingInstance().launchAssociation()); - assertThat(read.postAuthorizationExecutionTuple()).isEqualTo(tuple); assertThat(read.postAuthorizationExecutionTuple().canonicalBytes()) .containsExactly(tuple.canonicalBytes()); assertThat(read.ownerAttemptId()).isEqualTo(starting.claim().ownerAttemptId()); From efc5cb04acd7f577ff7724fb8f7b70f683c31555 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 14:16:10 +1300 Subject: [PATCH 07/22] feat(game-session): preserve exact historical and terminal owner readback --- .../game-session-service/api-contracts.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 2 + .../v1/game_session_service.proto | 72 ++ ...riginal_start_session_owner_evidence.proto | 60 ++ ...uthoredWorldLaunchDescriptorGrpcCodec.java | 22 + ...nonicalInitialAdmissionOwnerGrpcCodec.java | 178 +++++ ...icalOriginalStartSessionOwnerEvidence.java | 374 +++++++++ ...nalStartSessionOwnerEvidenceGrpcCodec.java | 278 +++++++ ...alStartSessionOwnerEvidenceReadClient.java | 166 ++++ ...tartSessionOwnerEvidenceGrpcCodecTest.java | 148 ++++ ...artSessionOwnerEvidenceReadClientTest.java | 122 +++ ...meInstanceLaunchAssociationRepository.java | 371 +++++++++ ...lInitialAdmissionOwnerReadGrpcService.java | 133 ++++ ...nitialAdmissionOwnerReadWorkloadGuard.java | 36 + ...rtSessionOwnerEvidenceReadGrpcService.java | 72 ++ ...SessionOwnerEvidenceReadWorkloadGuard.java | 47 ++ ...SessionAssociationReadIntegrationTest.java | 249 ++++++ ...stanceLaunchAssociationRepositoryTest.java | 92 +++ ...tialAdmissionOwnerReadGrpcServiceTest.java | 530 +++++++++++++ ...ssionOwnerEvidenceReadGrpcServiceTest.java | 744 ++++++++++++++++++ ...ionOwnerEvidenceReadWorkloadGuardTest.java | 109 +++ 21 files changed, 3806 insertions(+), 1 deletion(-) create mode 100644 protos/game-session/v1/historical_original_start_session_owner_evidence.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalInitialAdmissionOwnerGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuard.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index cc6ad32011..d1c55817e2 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -135,7 +135,7 @@ Under approved original-claim continuation decision `ae27ed99`, this narrowly bo The continuation is restricted to reading and exact replay of an existing immutable association pin. It must not replay redemption, create or reselect an association, create a claim, attempt, fence, or authorization reference, renew or transfer ownership, mutate domain state, or admit a player. Remote Account/source reads occur outside SQL; Game Session then locks and rechecks the same owner state before returning the association. The actual pin/read statement enforces claim expiry using the database clock. Missing or unattached projections, absent or changed pins, changed tuples, expired claims, and ambiguous outcomes remain reconciliation-only and cannot be treated as authorization or admission. -Historical original-operation reconciliation is separate from that live continuation. The unregistered owner repositories can read the complete retained StartSession tuple, actual original attempt/fence, exact attached Account projection and existing immutable first-selection pin after lease or reference expiry. These reads create no claim, renewal, redemption, reselection, pointer/audit mutation or admission authority; missing or mismatched retained evidence fails closed. The separate current STARTING association read now returns its exact stored tuple alongside the original attempt/fence, but still requires an unexpired pending lease; it is not an after-expiry recovery endpoint. The authenticated World-facing historical producer and cross-owner recovery composition remain unimplemented. This historical evidence is not a current World hold or a Game Session terminal outcome. +Historical original-operation reconciliation is separate from that live continuation. The new local, unregistered historical read returns the exact retained StartSession tuple, actual original attempt/fence, attached Account projection, immutable first selection, and existing descriptor/release association after lease or reference expiry. Its producer accepts only exact same-namespace World or Account workload callers without end-user context. The read creates no claim, renewal, redemption, reselection, pointer/audit mutation, admission authority, current-hold proof, or terminal outcome; missing, conflicting, or malformed retained evidence fails closed. The separate current STARTING association read still requires an unexpired pending lease and is not an after-expiry endpoint. Cross-owner recovery composition and deployed recovery remain open. ### gRPC Outcome Handling diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 94bfeb2333..9dde2a0989 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for Game Session runtime and tick This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. +Local Game Session producer code now includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads, plus an unregistered World-only initial-admission owner read bound to the configured namespace and full hold tuple. The latter reports only a nonterminal `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Consolidated Common and Game Session checks passed locally on 2026-10-10, including the producer authorization, correlation, retained-evidence, and terminal-outcome unit tests; the new PostgreSQL integration cases compiled but require execution in container-enabled CI. Neither endpoint is deployed, and their existence does not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. + Gameplay-session context remains on the implementation-local `sessionctx:*` keys and per-instance binding identity. The target authenticated `session:game:{tenantGameplayTag}:...` family, persisted tenant-tag allocation, and namespace-qualified controller uniqueness are not implemented or end-to-end proved; the canonical tenancy and focused-isolation requirements remain in [Multi-Tenancy](../../architecture/system-architecture-multi-tenancy.md#data-separation-per-service). Retained bootstrap correction: V8 recognizes only the unchanged, provenance-backed historical demo/sandbox pair that was seeded with two public-production realms. It changes sandbox's public flag and advances only its catalog revision, retains runtime pointer and durable realm/namespace identity, and appends an immutable repair event in the same transaction. Unknown, operator-edited, incomplete, extra-public, or conflicting-history catalogs remain untouched and fail closed. This is not World-owner lifecycle or initial-bind proof. PostgreSQL execution remains a required separate check; the local environment has no Docker or PostgreSQL runtime. diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index adf1810f08..32ffea91b5 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -4,6 +4,7 @@ package game_session.v1; import "entity-management/v1/entity_management_service.proto"; import "game-design/v1/game_design_service.proto"; +import "google/protobuf/timestamp.proto"; import "shared/v1/errors.proto"; option java_package = "net.firedevops.firemud.gamesession.v1"; @@ -41,6 +42,10 @@ service GameSessionControlPlaneService { // Read exact durable owner proof for a World-owned initial-admission hold. rpc GetInitialAdmissionBindProof(GetInitialAdmissionBindProofRequest) returns (GetInitialAdmissionBindProofResponse); + // Read the exact canonical Game Session-owned initial-admission terminal outcome for World. + rpc GetCanonicalInitialAdmissionOwnerProof( + GetCanonicalInitialAdmissionOwnerProofRequest) + returns (GetCanonicalInitialAdmissionOwnerProofResponse); rpc ValidateBuiltInCommandAlias(ValidateBuiltInCommandAliasRequest) returns (ValidateBuiltInCommandAliasResponse); rpc ListAdmissionPointers(ListAdmissionPointersRequest) @@ -500,6 +505,73 @@ message GetInitialAdmissionBindProofResponse { shared.v1.ErrorDetail error = 20; } +enum CanonicalInitialAdmissionOrigin { + CANONICAL_INITIAL_ADMISSION_ORIGIN_UNSPECIFIED = 0; + CANONICAL_INITIAL_ADMISSION_ORIGIN_NO_PRIOR_POINTER = 1; + CANONICAL_INITIAL_ADMISSION_ORIGIN_EXPECT_CLOSED = 2; +} + +enum CanonicalInitialAdmissionOwnerProofOutcome { + CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_UNSPECIFIED = 0; + CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING = 1; + CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED = 2; + CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED = 3; +} + +// World supplies the complete immutable request it acquired the hold for. No numeric runtime +// identifier is substituted for a canonical UUID, and World's hold digest remains distinct from +// the bare Game Session request digest. +message GetCanonicalInitialAdmissionOwnerProofRequest { + string target_namespace = 1; + string initial_admission_request_id = 2; + string initial_admission_request_digest = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string realm_id = 6; + string playable_state_namespace_id = 7; + string playable_state_scope = 8; + string canonical_game_instance_id = 9; + string canonical_version_id = 10; + int64 active_lifecycle_epoch = 11; + int64 expected_catalog_revision = 12; + CanonicalInitialAdmissionOrigin origin = 13; + optional int64 expected_prior_pointer_version = 14; + string hold_id = 15; + string hold_fence = 16; + string hold_binding_digest = 17; +} + +// Every successful domain result echoes the complete expected operation tuple. Only a COMMITTED +// pointer/audit result or a positively fenced durable ABORTED result is terminal proof. Missing +// owner attempts and reads that cannot establish an exact result use non-OK gRPC status, never a +// NOT_FOUND/UNAVAILABLE outcome or an inferred abort. +message GetCanonicalInitialAdmissionOwnerProofResponse { + string target_namespace = 1; + string initial_admission_request_id = 2; + string initial_admission_request_digest = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string realm_id = 6; + string playable_state_namespace_id = 7; + string playable_state_scope = 8; + string canonical_game_instance_id = 9; + string canonical_version_id = 10; + int64 active_lifecycle_epoch = 11; + int64 expected_catalog_revision = 12; + CanonicalInitialAdmissionOrigin origin = 13; + optional int64 expected_prior_pointer_version = 14; + string hold_id = 15; + string hold_fence = 16; + string hold_binding_digest = 17; + CanonicalInitialAdmissionOwnerProofOutcome outcome = 18; + optional int64 committed_pointer_version = 19; + optional int64 audit_event_id = 20; + // Terminal Game Session proof digest; sha256:-prefixed and distinct from the bare request digest. + string proof_digest = 21; + bool positive_durable_abort = 22; + google.protobuf.Timestamp terminal_at = 23; +} + message GetGameplayCommandStatusRequest { string command_id = 1; string tenant_id = 2; diff --git a/protos/game-session/v1/historical_original_start_session_owner_evidence.proto b/protos/game-session/v1/historical_original_start_session_owner_evidence.proto new file mode 100644 index 0000000000..1fdd11b1bf --- /dev/null +++ b/protos/game-session/v1/historical_original_start_session_owner_evidence.proto @@ -0,0 +1,60 @@ +syntax = "proto3"; + +package game_session.v1; + +import "game-design/v1/game_design_service.proto"; +import "game-design/v1/start_session_template_association_service.proto"; + +option java_package = "net.firedevops.firemud.gamesession.v1"; +option java_multiple_files = true; + +// Unregistered, read-only historical evidence. This endpoint never grants StartSession +// continuation, mutation, current lease, or admission authority. +service HistoricalOriginalStartSessionOwnerEvidenceReadService { + rpc ReadHistoricalOriginalStartSessionOwnerEvidence( + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest) + returns (ReadHistoricalOriginalStartSessionOwnerEvidenceResponse); +} + +message ReadHistoricalOriginalStartSessionOwnerEvidenceRequest { + int32 schema_version = 1; + string read_request_id = 2; + string target_namespace = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string game_instance_uuid = 6; + string control_plane_request_id = 7; + string launch_descriptor_id = 8; + string expected_descriptor_request_digest = 9; + string expected_descriptor_result_digest = 10; + string expected_release_attestation_evidence_digest = 11; + string expected_owner_attempt_id = 12; + int64 expected_owner_fence = 13; +} + +message ReadHistoricalOriginalStartSessionOwnerEvidenceResponse { + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest request = 1; + bytes canonical_post_authorization_tuple = 2; + string owner_attempt_id = 3; + int64 owner_fence = 4; + bytes account_redemption_projection = 5; + game_design.v1.ReadStartSessionTemplateAssociationRequest template_association_request = 6; + game_design.v1.ReadStartSessionTemplateAssociationResponse template_association_response = 7; + string template_association_request_digest = 8; + string template_association_response_digest = 9; + game_design.v1.ResolveStartSessionLaunchDescriptorResponse descriptor_pin_response = 10; + string descriptor_pin_request_digest = 11; + string descriptor_pin_response_digest = 12; + string playable_state_namespace_id = 13; + string playable_state_scope = 14; + bool public_production = 15; + int64 captured_starting_row_version = 16; + gamedesign.v1.LaunchDescriptor launch_descriptor = 17; + gamedesign.v1.AuthoredWorldReleaseAttestationEvidence release_attestation = 18; + string association_target_namespace = 19; + string association_canonical_tenant_id = 20; + string association_world_slug = 21; + string association_game_instance_uuid = 22; + string association_control_plane_request_id = 23; + string association_launch_descriptor_id = 24; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java index ac1740309d..8db53d7fda 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java @@ -179,6 +179,28 @@ public static CompleteLaunchBindingEvidence fromCompleteResponse( } } + /** + * Decodes an already correlated immutable descriptor/attestation pair from another owner read. + */ + public static CompleteLaunchBindingEvidence fromCompleteEvidenceMessages( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, + LaunchDescriptor descriptor, + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence + releaseAttestation) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(releaseAttestation, "releaseAttestation"); + AuthoredWorldLaunchDescriptorEvidence decodedDescriptor = + decodeDescriptor(expectedRequest, descriptor); + AuthoredWorldReleaseAttestationEvidence decodedRelease = + decodeReleaseAttestation(releaseAttestation); + try { + return new CompleteLaunchBindingEvidence(decodedDescriptor, decodedRelease); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Complete launch binding evidence is invalid", invalid); + } + } + /** Encodes and revalidates the exact immutable descriptor and release-attestation pair. */ public static GetCompleteLaunchBindingResponse toCompleteResponse( GetLaunchDescriptorRequest request, CompleteLaunchBindingEvidence evidence) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalInitialAdmissionOwnerGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalInitialAdmissionOwnerGrpcCodec.java new file mode 100644 index 0000000000..837ce660af --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalInitialAdmissionOwnerGrpcCodec.java @@ -0,0 +1,178 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.Timestamp; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOwnerProofOutcome; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofResponse; + +/** Closed Game Session producer codec for the exact World initial-admission owner tuple. */ +public final class CanonicalInitialAdmissionOwnerGrpcCodec { + private CanonicalInitialAdmissionOwnerGrpcCodec() {} + + public static HoldIdentity parseRequest(GetCanonicalInitialAdmissionOwnerProofRequest request) { + Objects.requireNonNull(request, "request"); + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Owner proof request contains unknown fields"); + } + Request identityRequest = + new Request( + request.getTargetNamespace(), + canonicalUuid(request.getCanonicalTenantId(), "canonical_tenant_id"), + request.getWorldSlug(), + canonicalUuid(request.getRealmId(), "realm_id"), + canonicalUuid(request.getPlayableStateNamespaceId(), "playable_state_namespace_id"), + request.getPlayableStateScope(), + canonicalUuid(request.getCanonicalGameInstanceId(), "canonical_game_instance_id"), + canonicalUuid(request.getCanonicalVersionId(), "canonical_version_id"), + request.getActiveLifecycleEpoch(), + request.getInitialAdmissionRequestId(), + request.getInitialAdmissionRequestDigest(), + fromWireOrigin(request.getOrigin()), + request.getExpectedCatalogRevision(), + request.hasExpectedPriorPointerVersion() + ? request.getExpectedPriorPointerVersion() + : null); + HoldIdentity identity = + new HoldIdentity( + identityRequest, + canonicalUuid(request.getHoldId(), "hold_id"), + canonicalUuid(request.getHoldFence(), "hold_fence")); + if (!identity.holdBindingDigest().equals(request.getHoldBindingDigest())) { + throw new IllegalArgumentException("hold_binding_digest does not bind the complete request"); + } + return identity; + } + + public static GetCanonicalInitialAdmissionOwnerProofResponse toResponse( + HoldIdentity expectedIdentity, GameSessionCanonicalInitialAdmissionOwnerProof ownerProof) { + Objects.requireNonNull(expectedIdentity, "expectedIdentity"); + Objects.requireNonNull(ownerProof, "ownerProof"); + if (!expectedIdentity.equals(ownerProof.holdIdentity())) { + throw new IllegalArgumentException("Owner proof changed the requested hold identity"); + } + GameSessionCanonicalInitialAdmissionOwnerProof proof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(ownerProof)); + if (proof.outcome() == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + requireExactNextPointerVersion(expectedIdentity, proof.committedPointerVersion()); + } + + Request request = expectedIdentity.request(); + var builder = + GetCanonicalInitialAdmissionOwnerProofResponse.newBuilder() + .setTargetNamespace(request.targetNamespace()) + .setInitialAdmissionRequestId(request.initialAdmissionRequestId()) + .setInitialAdmissionRequestDigest(request.initialAdmissionRequestDigest()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setRealmId(request.realmId().toString()) + .setPlayableStateNamespaceId(request.playableStateNamespaceId().toString()) + .setPlayableStateScope(request.playableStateScope()) + .setCanonicalGameInstanceId(request.canonicalGameInstanceId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setActiveLifecycleEpoch(request.activeLifecycleEpoch()) + .setExpectedCatalogRevision(request.expectedCatalogRevision()) + .setOrigin(toWireOrigin(request.initialAdmissionOrigin())) + .setHoldId(expectedIdentity.holdId().toString()) + .setHoldFence(expectedIdentity.holdFence().toString()) + .setHoldBindingDigest(expectedIdentity.holdBindingDigest()) + .setOutcome(toWireOutcome(proof.outcome())); + if (request.expectedPriorPointerVersion() != null) { + builder.setExpectedPriorPointerVersion(request.expectedPriorPointerVersion()); + } + if (proof.committedPointerVersion() != null) { + builder.setCommittedPointerVersion(proof.committedPointerVersion()); + } + if (proof.auditEventId() != null) { + builder.setAuditEventId(proof.auditEventId()); + } + if (proof.proofDigest() != null) { + builder.setProofDigest(proof.proofDigest()); + } + if (proof.terminalAt() != null) { + builder.setTerminalAt( + Timestamp.newBuilder() + .setSeconds(proof.terminalAt().getEpochSecond()) + .setNanos(proof.terminalAt().getNano()) + .build()); + } + builder.setPositiveDurableAbort(proof.positiveDurableAbort()); + return builder.build(); + } + + private static void requireExactNextPointerVersion(HoldIdentity identity, Long actualVersion) { + long expectedVersion; + try { + expectedVersion = + switch (identity.request().initialAdmissionOrigin()) { + case NO_PRIOR_POINTER -> 1L; + case EXPECT_CLOSED -> + Math.addExact(identity.request().expectedPriorPointerVersion(), 1L); + }; + } catch (ArithmeticException overflow) { + throw new IllegalArgumentException( + "Expected prior pointer version cannot advance without overflow", overflow); + } + if (actualVersion == null || actualVersion != expectedVersion) { + throw new IllegalArgumentException( + "COMMITTED owner proof does not name the exact next pointer version"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must use canonical UUID text"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must use canonical UUID text", invalid); + } + } + + private static InitialAdmissionOrigin fromWireOrigin( + net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOrigin origin) { + return switch (origin) { + case CANONICAL_INITIAL_ADMISSION_ORIGIN_NO_PRIOR_POINTER -> + InitialAdmissionOrigin.NO_PRIOR_POINTER; + case CANONICAL_INITIAL_ADMISSION_ORIGIN_EXPECT_CLOSED -> InitialAdmissionOrigin.EXPECT_CLOSED; + case CANONICAL_INITIAL_ADMISSION_ORIGIN_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("origin is unsupported"); + }; + } + + private static net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOrigin toWireOrigin( + InitialAdmissionOrigin origin) { + return switch (origin) { + case NO_PRIOR_POINTER -> + net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOrigin + .CANONICAL_INITIAL_ADMISSION_ORIGIN_NO_PRIOR_POINTER; + case EXPECT_CLOSED -> + net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOrigin + .CANONICAL_INITIAL_ADMISSION_ORIGIN_EXPECT_CLOSED; + }; + } + + private static CanonicalInitialAdmissionOwnerProofOutcome toWireOutcome( + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome) { + return switch (outcome) { + case PENDING -> + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING; + case COMMITTED -> + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED; + case ABORTED -> + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED; + }; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java new file mode 100644 index 0000000000..0e7e1e3aed --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java @@ -0,0 +1,374 @@ +package net.firedevops.firemud.common.gamesession; + +import java.io.IOException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import tools.jackson.databind.json.JsonMapper; + +/** + * Read-only historical evidence for one exact original StartSession attempt. + * + *

This carrier proves only the retained original tuple, attached Account projection, first + * association selection, and descriptor/release binding. It does not represent a current owner + * claim, authorization, lease, terminal outcome, hold, or admission decision. + */ +public final class HistoricalOriginalStartSessionOwnerEvidence { + public static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private HistoricalOriginalStartSessionOwnerEvidence() {} + + /** Exact retained launch selector plus the actual original owner attempt and fence. */ + public record Request( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request associationSelector, + UUID expectedOwnerAttemptId, + long expectedOwnerFence) { + public Request { + Objects.requireNonNull(associationSelector, "associationSelector"); + requireNonNil(expectedOwnerAttemptId, "expectedOwnerAttemptId"); + if (expectedOwnerFence <= 0L) { + throw new IllegalArgumentException("expectedOwnerFence must be positive"); + } + } + } + + /** Immutable association row projection. Mutable Game Instance state is intentionally absent. */ + public record LaunchAssociation( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID gameInstanceUuid, + String controlPlaneRequestId, + String launchDescriptorId, + UUID playableStateNamespaceId, + RealmEntryPolicy.StateScope playableStateScope, + boolean publicProduction, + long capturedStartingRowVersion, + CompleteLaunchBindingEvidence launchBindingEvidence) { + public LaunchAssociation { + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(gameInstanceUuid, "gameInstanceUuid"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + Objects.requireNonNull(launchBindingEvidence, "launchBindingEvidence"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 128); + if (playableStateScope != RealmEntryPolicy.StateScope.SHARED || !publicProduction) { + throw new IllegalArgumentException( + "Historical StartSession association must retain public SHARED state"); + } + if (capturedStartingRowVersion < 0L) { + throw new IllegalArgumentException("capturedStartingRowVersion must not be negative"); + } + AuthoredWorldLaunchDescriptorEvidence descriptor = launchBindingEvidence.descriptor(); + descriptor.requireValid(); + launchBindingEvidence.releaseAttestation().requireValid(descriptor); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId())) { + throw new IllegalArgumentException( + "Historical launch association differs from its complete descriptor binding"); + } + } + } + + /** + * Complete immutable readback. The projection bytes are the exact retained Account projection; + * accessors return copies to keep the carrier immutable. + */ + public static final class Result { + private final Request request; + private final StartSessionPostAuthorizationExecutionTuple originalTuple; + private final UUID ownerAttemptId; + private final long ownerFence; + private final byte[] accountRedemptionProjection; + private final StartSessionTemplateAssociationReadEvidence.Result firstSelection; + private final StartSessionLaunchDescriptorGrpcCodec.Resolved descriptorPin; + private final LaunchAssociation launchAssociation; + private final String templateAssociationRequestDigest; + private final String templateAssociationResponseDigest; + private final String descriptorPinRequestDigest; + private final String descriptorPinResponseDigest; + + public Result( + Request request, + StartSessionPostAuthorizationExecutionTuple originalTuple, + UUID ownerAttemptId, + long ownerFence, + byte[] accountRedemptionProjection, + StartSessionTemplateAssociationReadEvidence.Result firstSelection, + StartSessionLaunchDescriptorGrpcCodec.Resolved descriptorPin, + LaunchAssociation launchAssociation, + String templateAssociationRequestDigest, + String templateAssociationResponseDigest, + String descriptorPinRequestDigest, + String descriptorPinResponseDigest) { + this.request = Objects.requireNonNull(request, "request"); + this.originalTuple = Objects.requireNonNull(originalTuple, "originalTuple"); + this.ownerAttemptId = requireNonNil(ownerAttemptId, "ownerAttemptId"); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + this.ownerFence = ownerFence; + this.accountRedemptionProjection = + Objects.requireNonNull(accountRedemptionProjection, "accountRedemptionProjection") + .clone(); + this.firstSelection = Objects.requireNonNull(firstSelection, "firstSelection"); + this.descriptorPin = Objects.requireNonNull(descriptorPin, "descriptorPin"); + this.launchAssociation = Objects.requireNonNull(launchAssociation, "launchAssociation"); + this.templateAssociationRequestDigest = + requireDigest(templateAssociationRequestDigest, "templateAssociationRequestDigest"); + this.templateAssociationResponseDigest = + requireDigest(templateAssociationResponseDigest, "templateAssociationResponseDigest"); + this.descriptorPinRequestDigest = + requireDigest(descriptorPinRequestDigest, "descriptorPinRequestDigest"); + this.descriptorPinResponseDigest = + requireDigest(descriptorPinResponseDigest, "descriptorPinResponseDigest"); + requireCoherentEvidence(); + requirePinDigests(); + } + + public Request request() { + return request; + } + + public StartSessionPostAuthorizationExecutionTuple originalTuple() { + return originalTuple; + } + + public UUID ownerAttemptId() { + return ownerAttemptId; + } + + public long ownerFence() { + return ownerFence; + } + + public byte[] accountRedemptionProjection() { + return accountRedemptionProjection.clone(); + } + + public StartSessionTemplateAssociationReadEvidence.Result firstSelection() { + return firstSelection; + } + + public StartSessionLaunchDescriptorGrpcCodec.Resolved descriptorPin() { + return descriptorPin; + } + + public LaunchAssociation launchAssociation() { + return launchAssociation; + } + + public String templateAssociationRequestDigest() { + return templateAssociationRequestDigest; + } + + public String templateAssociationResponseDigest() { + return templateAssociationResponseDigest; + } + + public String descriptorPinRequestDigest() { + return descriptorPinRequestDigest; + } + + public String descriptorPinResponseDigest() { + return descriptorPinResponseDigest; + } + + private void requireCoherentEvidence() { + var selector = request.associationSelector(); + var action = originalTuple.preAuthorizationTuple().action(); + byte[] tupleBytes = originalTuple.canonicalBytes(); + if (!Arrays.equals( + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes).canonicalBytes(), + tupleBytes) + || !selector.targetNamespace().equals(action.scope().targetNamespace()) + || !selector.canonicalTenantId().equals(action.scope().tenantId()) + || !selector.controlPlaneRequestId().equals(originalTuple.controlPlaneRequestId()) + || !selector.gameInstanceUuid().equals(launchAssociation.gameInstanceUuid()) + || !selector.targetNamespace().equals(launchAssociation.targetNamespace()) + || !selector.canonicalTenantId().equals(launchAssociation.canonicalTenantId()) + || !selector.worldSlug().equals(launchAssociation.worldSlug()) + || !selector.controlPlaneRequestId().equals(launchAssociation.controlPlaneRequestId()) + || !selector.launchDescriptorId().equals(launchAssociation.launchDescriptorId()) + || !request.expectedOwnerAttemptId().equals(ownerAttemptId) + || request.expectedOwnerFence() != ownerFence + || !expectedAccountProjection(originalTuple).equalsBytes(accountRedemptionProjection)) { + throw new IllegalArgumentException( + "Historical StartSession tuple, projection, attempt, or association selector differs"); + } + + var selectionRequest = firstSelection.request(); + if (selectionRequest.schemaVersion() + != StartSessionTemplateAssociationReadEvidence.SCHEMA_VERSION + || !selector.targetNamespace().equals(selectionRequest.targetNamespace()) + || !Arrays.equals(selectionRequest.canonicalPostAuthorizationTuple(), tupleBytes) + || !ownerAttemptId.equals(selectionRequest.ownerAttemptId()) + || ownerFence != selectionRequest.ownerFence() + || !(selectionRequest.selection() + instanceof StartSessionTemplateAssociationReadEvidence.InitialConfigured) + || !selector.canonicalTenantId().equals(firstSelection.association().canonicalTenantId()) + || action.target().gameTemplateId() != firstSelection.association().templateId() + || !selector.worldSlug().equals(firstSelection.association().worldSlug())) { + throw new IllegalArgumentException( + "Historical first selection differs from the complete original StartSession tuple"); + } + + var descriptorRequest = descriptorPin.associationRead().request(); + var firstAssociation = firstSelection.association(); + boolean exactReplay = + descriptorRequest.selection() + instanceof StartSessionTemplateAssociationReadEvidence.ExactReplay replay + && replay.canonicalVersionId().equals(firstAssociation.canonicalVersionId()) + && replay.selectedCommitId().equals(firstAssociation.selectedCommitId()) + && replay.publishWorkflowId().equals(firstAssociation.publishWorkflowId()) + && replay.associationDigest().equals(firstAssociation.associationDigest()); + if (!exactReplay + || !selector.targetNamespace().equals(descriptorRequest.targetNamespace()) + || !Arrays.equals(descriptorRequest.canonicalPostAuthorizationTuple(), tupleBytes) + || !ownerAttemptId.equals(descriptorRequest.ownerAttemptId()) + || ownerFence != descriptorRequest.ownerFence() + || !(descriptorPin.outcome() + instanceof StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome outcome) + || !outcome.descriptor().equals(launchAssociation.launchBindingEvidence().descriptor())) { + throw new IllegalArgumentException( + "Historical descriptor pin differs from the immutable first selection or launch binding"); + } + + AuthoredWorldLaunchDescriptorEvidence descriptor = + launchAssociation.launchBindingEvidence().descriptor(); + var releaseAttestation = launchAssociation.launchBindingEvidence().releaseAttestation(); + if (!selector.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !selector.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !selector + .expectedReleaseAttestationEvidenceDigest() + .equals(releaseAttestation.evidenceDigest())) { + throw new IllegalArgumentException( + "Historical descriptor or release attestation differs from its exact selector"); + } + } + + private void requirePinDigests() { + var associationRequest = firstSelection.request(); + var associationRequestWire = + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .toRequest(associationRequest) + .toByteArray(); + var associationResponseWire = + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .toResponse(firstSelection) + .toByteArray(); + var descriptorRequest = descriptorPin.associationRead().request(); + var descriptorRequestWire = + StartSessionLaunchDescriptorGrpcCodec.toRequest(descriptorRequest).toByteArray(); + var descriptorResponseWire = + StartSessionLaunchDescriptorGrpcCodec.toResponse( + descriptorRequest, descriptorPin.associationRead(), descriptorPin.outcome()) + .toByteArray(); + if (!templateAssociationRequestDigest.equals(sha256(associationRequestWire)) + || !templateAssociationResponseDigest.equals(sha256(associationResponseWire)) + || !descriptorPinRequestDigest.equals(sha256(descriptorRequestWire)) + || !descriptorPinResponseDigest.equals(sha256(descriptorResponseWire))) { + throw new IllegalArgumentException( + "Historical StartSession pin digests differ from their canonical retained evidence"); + } + } + } + + private record ExpectedProjection(byte[] bytes) { + private boolean equalsBytes(byte[] candidate) { + return Arrays.equals(bytes, candidate); + } + } + + private static ExpectedProjection expectedAccountProjection( + StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + long issuanceFence; + try { + issuanceFence = Long.parseLong(tuple.issuanceFence()); + } catch (NumberFormatException malformed) { + throw new IllegalArgumentException( + "Historical Account issuance fence is malformed", malformed); + } + if (issuanceFence <= 0L) { + throw new IllegalArgumentException("Historical Account projection identity is malformed"); + } + Map projection = + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + issuanceFence); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + return new ExpectedProjection(bytes); + } catch (IOException malformed) { + throw new IllegalStateException( + "Could not encode the retained Account projection", malformed); + } + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + return value; + } + + private static void requireText(String value, String name, int maxLength) { + Objects.requireNonNull(value, name); + if (value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(name + " must be non-blank and bounded"); + } + } + + private static String requireDigest(String value, String name) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + return value; + } + + public static String sha256(byte[] value) { + Objects.requireNonNull(value, "value"); + try { + return "sha256:" + + HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.java new file mode 100644 index 0000000000..3a24731d41 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.java @@ -0,0 +1,278 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Request; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Result; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceRequest; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceResponse; + +/** Closed request and response mapping for historical original StartSession evidence. */ +public final class HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec() {} + + public static ReadHistoricalOriginalStartSessionOwnerEvidenceRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var selector = request.associationSelector(); + return ReadHistoricalOriginalStartSessionOwnerEvidenceRequest.newBuilder() + .setSchemaVersion(HistoricalOriginalStartSessionOwnerEvidence.SCHEMA_VERSION) + .setReadRequestId(selector.readRequestId().toString()) + .setTargetNamespace(selector.targetNamespace()) + .setCanonicalTenantId(selector.canonicalTenantId().toString()) + .setWorldSlug(selector.worldSlug()) + .setGameInstanceUuid(selector.gameInstanceUuid().toString()) + .setControlPlaneRequestId(selector.controlPlaneRequestId()) + .setLaunchDescriptorId(selector.launchDescriptorId()) + .setExpectedDescriptorRequestDigest(selector.expectedDescriptorRequestDigest()) + .setExpectedDescriptorResultDigest(selector.expectedDescriptorResultDigest()) + .setExpectedReleaseAttestationEvidenceDigest( + selector.expectedReleaseAttestationEvidenceDigest()) + .setExpectedOwnerAttemptId(request.expectedOwnerAttemptId().toString()) + .setExpectedOwnerFence(request.expectedOwnerFence()) + .build(); + } + + /** Decodes only the closed exact-selector request; decoding does not authenticate its caller. */ + public static Request fromRequest( + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadHistoricalOriginalStartSessionOwnerEvidenceRequest"); + if (request.getSchemaVersion() != HistoricalOriginalStartSessionOwnerEvidence.SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported historical StartSession read schema"); + } + try { + var selector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + parseUuid(request.getReadRequestId(), "readRequestId"), + request.getTargetNamespace(), + parseUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseUuid(request.getGameInstanceUuid(), "gameInstanceUuid"), + request.getControlPlaneRequestId(), + request.getLaunchDescriptorId(), + request.getExpectedDescriptorRequestDigest(), + request.getExpectedDescriptorResultDigest(), + request.getExpectedReleaseAttestationEvidenceDigest()); + Request decoded = + new Request( + selector, + parseUuid(request.getExpectedOwnerAttemptId(), "expectedOwnerAttemptId"), + request.getExpectedOwnerFence()); + if (!toRequest(decoded).equals(request)) { + throw new IllegalArgumentException("Historical StartSession request is not canonical"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Canonical historical original StartSession evidence request required", malformed); + } + } + + public static ReadHistoricalOriginalStartSessionOwnerEvidenceResponse toResponse(Result result) { + Objects.requireNonNull(result, "result"); + var association = result.launchAssociation(); + CompleteLaunchBindingEvidence binding = association.launchBindingEvidence(); + var descriptor = binding.descriptor(); + var attestation = binding.releaseAttestation(); + var associationRead = result.firstSelection(); + var descriptorPin = result.descriptorPin(); + var descriptorRequest = descriptorPin.associationRead().request(); + return ReadHistoricalOriginalStartSessionOwnerEvidenceResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setCanonicalPostAuthorizationTuple( + com.google.protobuf.ByteString.copyFrom(result.originalTuple().canonicalBytes())) + .setOwnerAttemptId(result.ownerAttemptId().toString()) + .setOwnerFence(result.ownerFence()) + .setAccountRedemptionProjection( + com.google.protobuf.ByteString.copyFrom(result.accountRedemptionProjection())) + .setTemplateAssociationRequest( + StartSessionTemplateAssociationReadGrpcCodec.toRequest(associationRead.request())) + .setTemplateAssociationResponse( + StartSessionTemplateAssociationReadGrpcCodec.toResponse(associationRead)) + .setTemplateAssociationRequestDigest(result.templateAssociationRequestDigest()) + .setTemplateAssociationResponseDigest(result.templateAssociationResponseDigest()) + .setDescriptorPinResponse( + StartSessionLaunchDescriptorGrpcCodec.toResponse( + descriptorRequest, descriptorPin.associationRead(), descriptorPin.outcome())) + .setDescriptorPinRequestDigest(result.descriptorPinRequestDigest()) + .setDescriptorPinResponseDigest(result.descriptorPinResponseDigest()) + .setPlayableStateNamespaceId(association.playableStateNamespaceId().toString()) + .setPlayableStateScope(association.playableStateScope().name()) + .setPublicProduction(association.publicProduction()) + .setCapturedStartingRowVersion(association.capturedStartingRowVersion()) + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptor)) + .setReleaseAttestation( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(attestation)) + .setAssociationTargetNamespace(association.targetNamespace()) + .setAssociationCanonicalTenantId(association.canonicalTenantId().toString()) + .setAssociationWorldSlug(association.worldSlug()) + .setAssociationGameInstanceUuid(association.gameInstanceUuid().toString()) + .setAssociationControlPlaneRequestId(association.controlPlaneRequestId()) + .setAssociationLaunchDescriptorId(association.launchDescriptorId()) + .build(); + } + + /** Validates the exact request echo, original pins, projection, and immutable launch binding. */ + public static Result fromResponse( + Request expectedRequest, ReadHistoricalOriginalStartSessionOwnerEvidenceResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadHistoricalOriginalStartSessionOwnerEvidenceResponse"); + if (!response.hasRequest() + || !response.hasTemplateAssociationRequest() + || !response.hasTemplateAssociationResponse() + || !response.hasDescriptorPinResponse() + || !response.hasLaunchDescriptor() + || !response.hasReleaseAttestation()) { + throw new IllegalArgumentException( + "Complete historical original StartSession evidence required"); + } + + Request echoed = fromRequest(response.getRequest()); + if (!expectedRequest.equals(echoed)) { + throw new IllegalArgumentException( + "Game Session changed the exact historical read request echo"); + } + + byte[] tupleBytes = response.getCanonicalPostAuthorizationTuple().toByteArray(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (!java.util.Arrays.equals(tuple.canonicalBytes(), tupleBytes)) { + throw new IllegalArgumentException("Historical original StartSession tuple is not canonical"); + } + + var firstRequest = + StartSessionTemplateAssociationReadGrpcCodec.fromRequest( + response.getTemplateAssociationRequest()); + var firstSelection = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + firstRequest, response.getTemplateAssociationResponse()); + var selector = expectedRequest.associationSelector(); + if (!(firstRequest.selection() + instanceof StartSessionTemplateAssociationReadEvidence.InitialConfigured) + || !selector.targetNamespace().equals(firstRequest.targetNamespace()) + || !java.util.Arrays.equals(firstRequest.canonicalPostAuthorizationTuple(), tupleBytes) + || !expectedRequest.expectedOwnerAttemptId().equals(firstRequest.ownerAttemptId()) + || expectedRequest.expectedOwnerFence() != firstRequest.ownerFence()) { + throw new IllegalArgumentException( + "Historical first selection differs from its exact original attempt and tuple"); + } + + var pinnedAssociation = firstSelection.association(); + var originalSelectionRequest = firstSelection.request(); + var exactReplayRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + originalSelectionRequest.schemaVersion(), + originalSelectionRequest.targetNamespace(), + originalSelectionRequest.readRequestId(), + originalSelectionRequest.canonicalPostAuthorizationTuple(), + originalSelectionRequest.ownerAttemptId(), + originalSelectionRequest.ownerFence(), + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + pinnedAssociation.canonicalVersionId(), + pinnedAssociation.selectedCommitId(), + pinnedAssociation.publishWorkflowId(), + pinnedAssociation.associationDigest())); + var descriptorPin = + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + exactReplayRequest, response.getDescriptorPinResponse()); + + if (!(descriptorPin.outcome() + instanceof StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome descriptorOutcome)) { + throw new IllegalArgumentException( + "Historical StartSession descriptor pin has no descriptor"); + } + AuthoredWorldLaunchDescriptorEvidence.Request expectedDescriptorRequest = + descriptorOutcome.descriptor().request(); + CompleteLaunchBindingEvidence launchBinding = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteEvidenceMessages( + expectedDescriptorRequest, + response.getLaunchDescriptor(), + response.getReleaseAttestation()); + + RealmEntryPolicy.StateScope stateScope; + try { + stateScope = RealmEntryPolicy.StateScope.valueOf(response.getPlayableStateScope()); + } catch (RuntimeException invalidScope) { + throw new IllegalArgumentException( + "Historical playable-state scope is malformed", invalidScope); + } + LaunchAssociation launchAssociation = + new LaunchAssociation( + response.getAssociationTargetNamespace(), + parseUuid(response.getAssociationCanonicalTenantId(), "associationCanonicalTenantId"), + response.getAssociationWorldSlug(), + parseUuid(response.getAssociationGameInstanceUuid(), "associationGameInstanceUuid"), + response.getAssociationControlPlaneRequestId(), + response.getAssociationLaunchDescriptorId(), + parseUuid(response.getPlayableStateNamespaceId(), "playableStateNamespaceId"), + stateScope, + response.getPublicProduction(), + response.getCapturedStartingRowVersion(), + launchBinding); + + Result result = + new Result( + expectedRequest, + tuple, + parseUuid(response.getOwnerAttemptId(), "ownerAttemptId"), + response.getOwnerFence(), + response.getAccountRedemptionProjection().toByteArray(), + firstSelection, + descriptorPin, + launchAssociation, + response.getTemplateAssociationRequestDigest(), + response.getTemplateAssociationResponseDigest(), + response.getDescriptorPinRequestDigest(), + response.getDescriptorPinResponseDigest()); + if (!toResponse(result).equals(response)) { + throw new IllegalArgumentException( + "Historical original StartSession response is not canonical"); + } + return result; + } + + private static UUID parseUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, field)); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) continue; + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java new file mode 100644 index 0000000000..b4603bd61e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.common.gamesession; + +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.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Request; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Result; +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 net.firedevops.firemud.gamesession.v1.HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for the unregistered historical Game Session evidence read. */ +public final class HistoricalOriginalStartSessionOwnerEvidenceReadClient + extends AbstractReloadingBlockingGrpcClient< + HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc + .HistoricalOriginalStartSessionOwnerEvidenceReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final int MAX_INBOUND_MESSAGE_BYTES = 16 * 1024 * 1024; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public HistoricalOriginalStartSessionOwnerEvidenceReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when a consuming owner explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Historical StartSession evidence client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Historical StartSession evidence client has no gRPC stub"); + } + initialized = true; + } + + /** + * Reads immutable evidence outside any owner transaction; the result is not execution authority. + */ + public Result read(Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Historical StartSession evidence read requires no ambient owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.associationSelector().targetNamespace())) { + throw new IllegalArgumentException( + "Historical StartSession request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readHistoricalOriginalStartSessionOwnerEvidence( + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request)); + try { + return HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Session returned invalid historical original StartSession evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc + .HistoricalOriginalStartSessionOwnerEvidenceReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + return HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(MAX_INBOUND_MESSAGE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc + .HistoricalOriginalStartSessionOwnerEvidenceReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Historical StartSession evidence client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Historical StartSession evidence reads require 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( + "Historical StartSession evidence reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Historical StartSession evidence reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Historical StartSession " + label + " must be a readable file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Historical StartSession " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java new file mode 100644 index 0000000000..4054a7c985 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java @@ -0,0 +1,148 @@ +package net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Request; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceResponse; +import org.junit.jupiter.api.Test; + +class HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest { + private static final String NAMESPACE = "gameplay"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID GAME_INSTANCE = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID READ_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID ATTEMPT_ID = uuid("44444444-4444-4444-8444-444444444444"); + + @Test + void requestRoundTripsExactAssociationSelectorAndOriginalAttemptFence() { + Request request = request(); + var wire = HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request); + + assertThat(HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(wire)) + .isEqualTo(request); + } + + @Test + void requestRejectsUnknownFieldsUnsupportedSchemaAndNonPositiveFence() { + var wire = HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request()); + var unknown = + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var unsupported = wire.toBuilder().setSchemaVersion(2).build(); + var noFence = wire.toBuilder().setExpectedOwnerFence(0L).build(); + + assertThatThrownBy( + () -> HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "ReadHistoricalOriginalStartSessionOwnerEvidenceRequest contains unsupported fields"); + assertThatThrownBy( + () -> HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(unsupported)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("schema"); + assertThatThrownBy( + () -> HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(noFence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "Canonical historical original StartSession evidence request required") + .hasRootCauseMessage("expectedOwnerFence must be positive"); + } + + @Test + void responseRequiresTheExactRequestEchoBeforeDecodingEvidence() { + Request request = request(); + var changedEcho = + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request).toBuilder() + .setExpectedOwnerFence(request.expectedOwnerFence() + 1L) + .build(); + var response = + ReadHistoricalOriginalStartSessionOwnerEvidenceResponse.newBuilder() + .setRequest(changedEcho) + .setTemplateAssociationRequest( + net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest + .getDefaultInstance()) + .setTemplateAssociationResponse( + net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse + .getDefaultInstance()) + .setDescriptorPinResponse( + net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse + .getDefaultInstance()) + .setLaunchDescriptor( + net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.getDefaultInstance()) + .setReleaseAttestation( + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence + .getDefaultInstance()) + .build(); + + assertThatThrownBy( + () -> + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse( + request, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("request echo"); + } + + @Test + void responseRejectsUnknownNestedPinFields() { + var request = HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request()); + var response = + ReadHistoricalOriginalStartSessionOwnerEvidenceResponse.newBuilder() + .setRequest(request) + .setTemplateAssociationRequest( + net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest + .newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .setTemplateAssociationResponse( + net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse + .getDefaultInstance()) + .setDescriptorPinResponse( + net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse + .getDefaultInstance()) + .setLaunchDescriptor( + net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.getDefaultInstance()) + .setReleaseAttestation( + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence + .getDefaultInstance()) + .build(); + + assertThatThrownBy( + () -> + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse( + request(), response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "ReadHistoricalOriginalStartSessionOwnerEvidenceResponse.template_association_request contains unsupported fields"); + } + + private static Request request() { + return new Request( + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + READ_ID, + NAMESPACE, + TENANT, + "world", + GAME_INSTANCE, + "start-request-1", + "launch-descriptor-1", + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)), + ATTEMPT_ID, + 17L); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java new file mode 100644 index 0000000000..59ecb44f01 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.common.gamesession; + +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.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Request; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +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; + +class HistoricalOriginalStartSessionOwnerEvidenceReadClientTest { + private static final String NAMESPACE = "gameplay"; + + private HistoricalOriginalStartSessionOwnerEvidenceReadClient client; + + @AfterEach + void closeClientAndClearTransactionContext() throws Exception { + if (client != null) { + client.close(); + client = null; + } + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresFileBackedMtlsAndDoesNotInitializeOrReadWithoutExplicitInit(@TempDir Path dir) + throws Exception { + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = fileBackedMtls(dir); + plaintext.setPlaintext(true); + org.assertj.core.api.Assertions.assertThatThrownBy(() -> newClient(plaintext, factory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + client = newClient(fileBackedMtls(dir), factory); + assertThatThrownBy(() -> client.read(request(NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.read(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request(NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + verifyNoInteractions(factory); + } + + @Test + void initializesOnlyTheConfiguredGameSessionTargetWithFileBackedMtls(@TempDir Path dir) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("game-session.internal:6565"); + CommonGrpcClientProperties tls = fileBackedMtls(dir); + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(factory.buildChannel( + eq("game-session.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + client = + new HistoricalOriginalStartSessionOwnerEvidenceReadClient( + endpoints, tls, factory, NAMESPACE); + + client.init(); + + verify(factory) + .buildChannel( + eq("game-session.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } + + private HistoricalOriginalStartSessionOwnerEvidenceReadClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory factory) { + return new HistoricalOriginalStartSessionOwnerEvidenceReadClient( + new ServiceEndpointsProperties(), tls, factory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws IOException { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + 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("server-ca.crt"), "CA certificate").toString()); + return tls; + } + + private static Request request(String namespace) { + return new Request( + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + namespace, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "start-session-request", + "launch-descriptor", + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + 9L); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java index 62db57c2fe..192b123eab 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java @@ -17,6 +17,8 @@ import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; @@ -196,6 +198,359 @@ public Optional readOriginalStartSessionAssocia } } + /** + * Reads the exact retained original StartSession tuple, attached Account projection, immutable + * first selection, and descriptor association after owner-claim expiry. This is one SQL statement + * over immutable evidence and does not inspect current Game Instance state or lease expiry. + */ + public Optional + readHistoricalOriginalStartSessionOwnerEvidence( + HistoricalOriginalStartSessionOwnerEvidence.Request request) { + requireOutsideTransaction(); + Objects.requireNonNull(request, "request"); + var selector = request.associationSelector(); + if (!workloadNamespace.equals(selector.targetNamespace())) { + throw new IllegalArgumentException( + "Historical StartSession selector targets another Game Session namespace"); + } + Record row = findHistoricalOriginalStartSessionOwnerEvidence(request); + if (row == null) { + return Optional.empty(); + } + try { + return Optional.of(decodeHistoricalOriginalStartSessionOwnerEvidence(request, row)); + } catch (RuntimeException malformed) { + throw new IllegalStateException( + "Persisted historical original StartSession owner evidence is malformed", malformed); + } + } + + private Record findHistoricalOriginalStartSessionOwnerEvidence( + HistoricalOriginalStartSessionOwnerEvidence.Request request) { + var selector = request.associationSelector(); + return dsl.fetchOne( + "SELECT association.*, " + + "attempt.canonical_tenant_id AS owner_canonical_tenant_id, " + + "attempt.owner_attempt_id AS owner_attempt_id, " + + "attempt.owner_fence AS owner_fence, " + + "attempt.post_authorization_execution_tuple AS owner_tuple, " + + "attempt.mutation_digest AS owner_mutation_digest, " + + "attempt.authorization_reference_fingerprint AS owner_authorization_fingerprint, " + + "attempt.account_redemption_projection AS owner_projection, " + + "association_pin.canonical_tenant_id AS pin_canonical_tenant_id, " + + "association_pin.owner_attempt_id AS pin_owner_attempt_id, " + + "association_pin.owner_fence AS pin_owner_fence, " + + "association_pin.post_authorization_execution_tuple AS pin_owner_tuple, " + + "association_pin.post_authorization_tuple_digest AS pin_tuple_digest, " + + "association_pin.account_redemption_projection_digest AS pin_projection_digest, " + + "association_pin.association_request_wire AS pin_association_request_wire, " + + "association_pin.association_response_wire AS pin_association_response_wire, " + + "association_pin.association_request_digest AS pin_association_request_digest, " + + "association_pin.association_response_digest AS pin_association_response_digest, " + + "association_pin.template_id AS pin_template_id, " + + "association_pin.canonical_version_id AS pin_canonical_version_id, " + + "association_pin.selected_commit_id AS pin_selected_commit_id, " + + "association_pin.publish_workflow_id AS pin_publish_workflow_id, " + + "association_pin.publication_selection_digest AS pin_publication_selection_digest, " + + "association_pin.association_digest AS pin_association_digest, " + + "association_pin.world_intake_request_id AS pin_world_intake_request_id, " + + "association_pin.world_operation_id AS pin_world_operation_id, " + + "association_pin.source_operation_id AS pin_source_operation_id, " + + "association_pin.source_evidence_digest AS pin_source_evidence_digest, " + + "descriptor_pin.canonical_tenant_id AS descriptor_canonical_tenant_id, " + + "descriptor_pin.owner_attempt_id AS descriptor_owner_attempt_id, " + + "descriptor_pin.owner_fence AS descriptor_owner_fence, " + + "descriptor_pin.association_request_digest AS descriptor_association_request_digest, " + + "descriptor_pin.association_response_digest AS descriptor_association_response_digest, " + + "descriptor_pin.descriptor_request_wire AS descriptor_request_wire, " + + "descriptor_pin.descriptor_response_wire AS descriptor_response_wire, " + + "descriptor_pin.descriptor_request_digest AS descriptor_request_digest, " + + "descriptor_pin.descriptor_response_digest AS descriptor_response_digest " + + "FROM " + + ASSOCIATION_TABLE + + " association JOIN game_session_start_session_operator_attempt attempt " + + "ON attempt.target_namespace = association.target_namespace " + + "AND attempt.control_plane_request_id = association.control_plane_request_id " + + "AND attempt.canonical_tenant_id = association.canonical_tenant_id " + + "AND attempt.owner_attempt_id = ? AND attempt.owner_fence = ? " + + "AND attempt.account_redemption_projection IS NOT NULL " + + "JOIN game_session_start_session_template_association_pin association_pin " + + "ON association_pin.target_namespace = attempt.target_namespace " + + "AND association_pin.control_plane_request_id = attempt.control_plane_request_id " + + "AND association_pin.canonical_tenant_id = attempt.canonical_tenant_id " + + "AND association_pin.owner_attempt_id = attempt.owner_attempt_id " + + "AND association_pin.owner_fence = attempt.owner_fence " + + "AND association_pin.post_authorization_execution_tuple " + + "= attempt.post_authorization_execution_tuple " + + "JOIN game_session_start_session_launch_descriptor_pin descriptor_pin " + + "ON descriptor_pin.target_namespace = attempt.target_namespace " + + "AND descriptor_pin.control_plane_request_id = attempt.control_plane_request_id " + + "AND descriptor_pin.canonical_tenant_id = attempt.canonical_tenant_id " + + "AND descriptor_pin.owner_attempt_id = attempt.owner_attempt_id " + + "AND descriptor_pin.owner_fence = attempt.owner_fence " + + "AND descriptor_pin.association_request_digest " + + "= association_pin.association_request_digest " + + "AND descriptor_pin.association_response_digest " + + "= association_pin.association_response_digest " + + "WHERE association.target_namespace = ? " + + "AND association.canonical_tenant_id = ? " + + "AND association.world_slug = ? " + + "AND association.game_instance_uuid = ? " + + "AND association.control_plane_request_id = ? " + + "AND association.launch_descriptor_id = ?", + request.expectedOwnerAttemptId(), + request.expectedOwnerFence(), + selector.targetNamespace(), + selector.canonicalTenantId(), + selector.worldSlug(), + selector.gameInstanceUuid(), + selector.controlPlaneRequestId(), + selector.launchDescriptorId()); + } + + private HistoricalOriginalStartSessionOwnerEvidence.Result + decodeHistoricalOriginalStartSessionOwnerEvidence( + HistoricalOriginalStartSessionOwnerEvidence.Request request, Record row) { + var selector = request.associationSelector(); + UUID ownerAttemptId = requiredUuid(row, "owner_attempt_id"); + long ownerFence = requiredLong(row, "owner_fence"); + UUID canonicalTenantId = requiredUuid(row, "owner_canonical_tenant_id"); + byte[] ownerTupleBytes = requiredBytes(row, "owner_tuple"); + byte[] ownerProjectionBytes = requiredBytes(row, "owner_projection"); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(ownerTupleBytes); + if (!Arrays.equals(tuple.canonicalBytes(), ownerTupleBytes) + || !request.expectedOwnerAttemptId().equals(ownerAttemptId) + || request.expectedOwnerFence() != ownerFence + || !workloadNamespace.equals( + tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !selector + .targetNamespace() + .equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !selector + .canonicalTenantId() + .equals(tuple.preAuthorizationTuple().action().scope().tenantId()) + || !selector.controlPlaneRequestId().equals(tuple.controlPlaneRequestId()) + || !canonicalTenantId.equals(tuple.preAuthorizationTuple().action().scope().tenantId()) + || !canonicalTenantId.equals(row.get("canonical_tenant_id", UUID.class)) + || !tuple.mutationDigest().equals(row.get("owner_mutation_digest", String.class)) + || !tuple + .authorizationReferenceFingerprint() + .equals(row.get("owner_authorization_fingerprint", String.class))) { + throw new IllegalStateException( + "Historical StartSession tuple differs from its exact owner or launch selector"); + } + + StartSessionAuthorityEvidenceBundle authority = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + long issuanceFence; + try { + issuanceFence = Long.parseLong(tuple.issuanceFence()); + } catch (NumberFormatException invalid) { + throw new IllegalStateException("Historical Account issuance fence is malformed", invalid); + } + GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection + expectedProjection = + new GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + issuanceFence); + if (!Arrays.equals(expectedProjection.canonicalBytes(), ownerProjectionBytes)) { + throw new IllegalStateException( + "Historical Account projection differs from the complete original StartSession tuple"); + } + + byte[] associationTupleBytes = requiredBytes(row, "pin_owner_tuple"); + byte[] associationRequestWire = requiredBytes(row, "pin_association_request_wire"); + byte[] associationResponseWire = requiredBytes(row, "pin_association_response_wire"); + if (!Arrays.equals(ownerTupleBytes, associationTupleBytes) + || !ownerAttemptId.equals(row.get("pin_owner_attempt_id", UUID.class)) + || ownerFence != requiredLong(row, "pin_owner_fence") + || !canonicalTenantId.equals(row.get("pin_canonical_tenant_id", UUID.class)) + || !sha256(associationTupleBytes).equals(row.get("pin_tuple_digest", String.class)) + || !sha256(ownerProjectionBytes).equals(row.get("pin_projection_digest", String.class)) + || !sha256(associationRequestWire) + .equals(row.get("pin_association_request_digest", String.class)) + || !sha256(associationResponseWire) + .equals(row.get("pin_association_response_digest", String.class))) { + throw new IllegalStateException( + "Historical StartSession association pin differs from the exact owner projection"); + } + Result firstSelection = + decodeAssociationPin( + row, + tuple, + ownerAttemptId, + ownerFence, + associationRequestWire, + associationResponseWire); + + byte[] descriptorRequestWire = requiredBytes(row, "descriptor_request_wire"); + byte[] descriptorResponseWire = requiredBytes(row, "descriptor_response_wire"); + if (!canonicalTenantId.equals(row.get("descriptor_canonical_tenant_id", UUID.class)) + || !ownerAttemptId.equals(row.get("descriptor_owner_attempt_id", UUID.class)) + || ownerFence != requiredLong(row, "descriptor_owner_fence") + || !row.get("pin_association_request_digest", String.class) + .equals(row.get("descriptor_association_request_digest", String.class)) + || !row.get("pin_association_response_digest", String.class) + .equals(row.get("descriptor_association_response_digest", String.class)) + || !sha256(descriptorRequestWire).equals(row.get("descriptor_request_digest", String.class)) + || !sha256(descriptorResponseWire) + .equals(row.get("descriptor_response_digest", String.class))) { + throw new IllegalStateException( + "Historical StartSession descriptor pin differs from the exact first selection"); + } + Resolved descriptorPin = + decodeDescriptorPin(firstSelection, descriptorRequestWire, descriptorResponseWire); + LaunchAssociation launchAssociation = toHistoricalLaunchAssociation(row, selector); + if (!(descriptorPin.outcome() instanceof DescriptorOutcome descriptorOutcome) + || !descriptorOutcome + .descriptor() + .equals(launchAssociation.launchBindingEvidence().descriptor()) + || !firstSelection.association().canonicalTenantId().equals(canonicalTenantId) + || firstSelection.association().templateId() + != tuple.preAuthorizationTuple().action().target().gameTemplateId() + || !firstSelection.association().worldSlug().equals(launchAssociation.worldSlug()) + || !firstSelection + .association() + .sourceOperationId() + .equals( + launchAssociation + .launchBindingEvidence() + .descriptor() + .authoredWorldSourceOperationId()) + || !firstSelection + .association() + .sourceEvidenceDigest() + .equals( + launchAssociation + .launchBindingEvidence() + .descriptor() + .authoredWorldSourceEvidenceDigest())) { + throw new IllegalStateException( + "Historical descriptor pin differs from the immutable launch association"); + } + requireExactHistoricalSelector(selector, launchAssociation); + return new HistoricalOriginalStartSessionOwnerEvidence.Result( + request, + tuple, + ownerAttemptId, + ownerFence, + ownerProjectionBytes, + firstSelection, + descriptorPin, + launchAssociation, + row.get("pin_association_request_digest", String.class), + row.get("pin_association_response_digest", String.class), + row.get("descriptor_request_digest", String.class), + row.get("descriptor_response_digest", String.class)); + } + + private LaunchAssociation toHistoricalLaunchAssociation( + Record row, + net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence + .Request + selector) { + try { + CompleteLaunchBindingEvidence evidence = + JSON.readValue( + row.get("complete_launch_binding_evidence", JSONB.class).data(), + CompleteLaunchBindingEvidence.class); + ValidatedBinding binding = validateBinding(evidence); + UUID canonicalTenantId = requiredUuid(row, "canonical_tenant_id"); + UUID gameInstanceUuid = requiredUuid(row, "game_instance_uuid"); + UUID namespaceId = requiredUuid(row, "playable_state_namespace_id"); + RuntimeTenantIdentityEvidence source = sourceFromRow(row); + requireFreshSourceIdentity( + new FreshGameSessionTenantAssociation( + requiredUuid(row, "tenant_association_operation_id"), + requiredLong(row, "game_session_tenant_id"), + source), + source); + if (!workloadNamespace.equals(row.get("target_namespace", String.class)) + || !workloadNamespace.equals(row.get("tenant_source_target_namespace", String.class)) + || !canonicalTenantId.equals(source.canonicalTenantId()) + || source.schemaVersion() != row.get("tenant_source_schema_version", Integer.class) + || !source.requestId().equals(row.get("tenant_association_request_id", UUID.class)) + || !source.requestId().equals(row.get("tenant_source_request_id", UUID.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("tenant_association_kind", String.class)) + || !selector.targetNamespace().equals(row.get("target_namespace", String.class)) + || !selector.canonicalTenantId().equals(canonicalTenantId) + || !selector.worldSlug().equals(row.get("world_slug", String.class)) + || !selector.gameInstanceUuid().equals(gameInstanceUuid) + || !selector + .controlPlaneRequestId() + .equals(row.get("control_plane_request_id", String.class)) + || !selector.launchDescriptorId().equals(row.get("launch_descriptor_id", String.class)) + || !RealmEntryPolicy.StateScope.SHARED + .name() + .equals(row.get("playable_state_scope", String.class)) + || !Boolean.TRUE.equals(row.get("public_production", Boolean.class)) + || requiredLong(row, "captured_starting_row_version") < 0L + || !binding.descriptor().targetNamespace().equals(workloadNamespace) + || !binding + .descriptor() + .controlPlaneRequestId() + .equals(row.get("control_plane_request_id", String.class)) + || !canonicalTenantId.equals(binding.descriptor().canonicalTenantId()) + || !row.get("world_slug", String.class).equals(binding.descriptor().worldSlug()) + || !row.get("launch_descriptor_id", String.class) + .equals(binding.descriptor().launchDescriptorId()) + || row.get("game_template_id", Long.class) != binding.descriptor().gameTemplateId() + || row.get("version_id", Long.class) != binding.descriptor().versionId() + || row.get("release_bundle_id", Long.class) != binding.descriptor().releaseBundleId() + || !row.get("generation_config_revision", String.class) + .equals(binding.descriptor().generationConfigRevision()) + || row.get("version_state_epoch", Long.class) + != binding.descriptor().versionStateEpoch()) { + throw new IllegalStateException( + "Historical launch association differs from its immutable descriptor binding"); + } + return new LaunchAssociation( + workloadNamespace, + canonicalTenantId, + row.get("world_slug", String.class), + gameInstanceUuid, + row.get("control_plane_request_id", String.class), + row.get("launch_descriptor_id", String.class), + namespaceId, + RealmEntryPolicy.StateScope.SHARED, + true, + requiredLong(row, "captured_starting_row_version"), + binding.evidence()); + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalStateException illegalState) { + throw illegalState; + } + throw new IllegalStateException( + "Persisted historical launch association is malformed", malformed); + } + } + + private static void requireExactHistoricalSelector( + net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence + .Request + selector, + LaunchAssociation association) { + var descriptor = association.launchBindingEvidence().descriptor(); + var attestation = association.launchBindingEvidence().releaseAttestation(); + if (!selector.targetNamespace().equals(association.targetNamespace()) + || !selector.canonicalTenantId().equals(association.canonicalTenantId()) + || !selector.worldSlug().equals(association.worldSlug()) + || !selector.gameInstanceUuid().equals(association.gameInstanceUuid()) + || !selector.controlPlaneRequestId().equals(association.controlPlaneRequestId()) + || !selector.launchDescriptorId().equals(association.launchDescriptorId()) + || !selector.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !selector.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !selector + .expectedReleaseAttestationEvidenceDigest() + .equals(attestation.evidenceDigest())) { + throw new IllegalStateException( + "Historical launch association differs from its exact selector"); + } + } + private Record findOriginalStartSessionAssociation( net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence .Request @@ -654,6 +1009,22 @@ private static byte[] requiredBytes(Record row, String field) { return value.clone(); } + private static UUID requiredUuid(Record row, String field) { + UUID value = row == null ? null : row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalStateException("Persisted owner association is missing " + field); + } + return value; + } + + private static long requiredLong(Record row, String field) { + Long value = row == null ? null : row.get(field, Long.class); + if (value == null) { + throw new IllegalStateException("Persisted owner association is missing " + field); + } + return value; + } + private static String sha256(byte[] value) { try { return "sha256:" diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java new file mode 100644 index 0000000000..826022fa3f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamesession.CanonicalInitialAdmissionOwnerGrpcCodec; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionReconciliationRequiredException; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofResponse; + +/** + * Unregistered read-only producer for exact World initial-admission owner reconciliation. + * + *

This point-in-time read does not acquire or renew a lease and does not guarantee the proof + * remains valid through a later transaction owned by another service. + */ +public final class CanonicalInitialAdmissionOwnerReadGrpcService + extends GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceImplBase { + private final CanonicalInitialAdmissionRepository repository; + private final CanonicalInitialAdmissionOwnerReadWorkloadGuard workloadGuard; + + public CanonicalInitialAdmissionOwnerReadGrpcService( + CanonicalInitialAdmissionRepository repository, + CanonicalInitialAdmissionOwnerReadWorkloadGuard workloadGuard) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.workloadGuard = Objects.requireNonNull(workloadGuard, "workloadGuard"); + } + + @Override + public void getCanonicalInitialAdmissionOwnerProof( + GetCanonicalInitialAdmissionOwnerProofRequest request, + StreamObserver responseObserver) { + Objects.requireNonNull(responseObserver, "responseObserver"); + if (request == null) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Owner proof request is required") + .asRuntimeException()); + return; + } + + HoldIdentity identity; + try { + identity = CanonicalInitialAdmissionOwnerGrpcCodec.parseRequest(request); + } catch (IllegalArgumentException malformed) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Owner proof request is malformed") + .asRuntimeException()); + return; + } + + try { + workloadGuard.requireWorldManagementOwnerReadCaller(identity.request().targetNamespace()); + + Optional readback = + repository.read( + identity.request().targetNamespace(), identity.request().initialAdmissionRequestId()); + if (readback.isEmpty()) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact durable owner proof is not available") + .asRuntimeException()); + return; + } + GameSessionCanonicalInitialAdmissionOwnerProof proof = + toCanonicalProof(identity, readback.get()); + responseObserver.onNext(CanonicalInitialAdmissionOwnerGrpcCodec.toResponse(identity, proof)); + responseObserver.onCompleted(); + } catch (AdminAuthorizationException unauthorized) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Owner proof caller is not authorized") + .asRuntimeException()); + } catch (CanonicalInitialAdmissionReconciliationRequiredException ambiguous) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact durable owner proof is ambiguous") + .asRuntimeException()); + } catch (IllegalArgumentException mismatchedOwnerReadback) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact durable owner proof is ambiguous") + .asRuntimeException()); + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Canonical owner proof read failed") + .asRuntimeException()); + } + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof toCanonicalProof( + HoldIdentity identity, CanonicalInitialAdmissionOwnerProof ownerProof) { + Request request = identity.request(); + if (!request.initialAdmissionRequestId().equals(ownerProof.initialAdmissionRequestId()) + || !request.initialAdmissionRequestDigest().equals(ownerProof.requestDigest()) + || !request.targetNamespace().equals(ownerProof.targetNamespace()) + || !request.canonicalTenantId().equals(ownerProof.canonicalTenantId()) + || !request.worldSlug().equals(ownerProof.worldSlug()) + || !request.realmId().equals(ownerProof.realmId()) + || !request.playableStateNamespaceId().equals(ownerProof.playableStateNamespaceId()) + || !request.playableStateScope().equals(ownerProof.playableStateScope()) + || !request.canonicalGameInstanceId().equals(ownerProof.canonicalGameInstanceId()) + || !request.canonicalVersionId().equals(ownerProof.canonicalVersionId()) + || request.activeLifecycleEpoch() != ownerProof.activeLifecycleEpoch() + || request.expectedCatalogRevision() != ownerProof.expectedCatalogRevision() + || !request.initialAdmissionOrigin().name().equals(ownerProof.originKind().name()) + || !Objects.equals( + request.expectedPriorPointerVersion(), ownerProof.expectedPriorPointerVersion()) + || !identity.holdId().equals(ownerProof.holdId()) + || !identity.holdFence().equals(ownerProof.holdFence()) + || !identity.holdBindingDigest().equals(ownerProof.holdBindingDigest())) { + throw new IllegalArgumentException("Owner readback changed the requested immutable tuple"); + } + return new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.valueOf(ownerProof.outcome().name()), + ownerProof.committedPointerVersion(), + ownerProof.auditEventId(), + ownerProof.proofDigest(), + ownerProof.positiveDurableAbort(), + ownerProof.terminalAt()); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java new file mode 100644 index 0000000000..4d513132e9 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.gamesession.service.impl; + +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.gamesession.v1.GameSessionControlPlaneServiceGrpc; + +/** Exact same-namespace World workload authorization for canonical owner proof readback. */ +public final class CanonicalInitialAdmissionOwnerReadWorkloadGuard { + private static final String WORLD_MANAGEMENT_SERVICE = "world-management-service"; + private final String trustedNamespace; + + public CanonicalInitialAdmissionOwnerReadWorkloadGuard(String trustedNamespace) { + this.trustedNamespace = trustedNamespace; + } + + public void requireWorldManagementOwnerReadCaller(String targetNamespace) { + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + if (!"game_session.v1.GameSessionControlPlaneService/GetCanonicalInitialAdmissionOwnerProof" + .equals( + GameSessionControlPlaneServiceGrpc.getGetCanonicalInitialAdmissionOwnerProofMethod() + .getFullMethodName()) + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || peerIdentity == null + || !WORLD_MANAGEMENT_SERVICE.equals(peerIdentity.service()) + || !trustedNamespace.equals(targetNamespace) + || !trustedNamespace.equals(peerIdentity.namespace()) + || !("spiffe://firemud/ns/" + trustedNamespace + "/sa/" + WORLD_MANAGEMENT_SERVICE) + .equals(peerIdentity.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Canonical initial-admission owner proof requires the same-namespace World Management workload identity"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java new file mode 100644 index 0000000000..1d97fd960d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.v1.HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceRequest; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceResponse; + +/** + * Directly constructible, deliberately unregistered historical evidence producer. + * + *

This service has no Spring registration annotation and is not added to active gRPC wiring. + */ +public final class HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService + extends HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc + .HistoricalOriginalStartSessionOwnerEvidenceReadServiceImplBase { + private final CanonicalGameInstanceLaunchAssociationRepository repository; + private final HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuard workloadGuard; + + public HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService( + CanonicalGameInstanceLaunchAssociationRepository repository, String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.workloadGuard = + new HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuard(trustedNamespace); + } + + @Override + public void readHistoricalOriginalStartSessionOwnerEvidence( + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest request, + StreamObserver responseObserver) { + Objects.requireNonNull(responseObserver, "responseObserver"); + try { + workloadGuard.requireHistoricalOwnerReadCaller(); + var decodedRequest = + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(request); + workloadGuard.requireConfiguredTargetNamespace( + decodedRequest.associationSelector().targetNamespace()); + var evidence = + repository + .readHistoricalOriginalStartSessionOwnerEvidence(decodedRequest) + .orElseThrow( + () -> + new IllegalStateException( + "Exact historical StartSession evidence is unavailable")); + if (!decodedRequest.equals(evidence.request())) { + throw new IllegalStateException( + "Retained historical StartSession evidence changed the exact read request echo"); + } + responseObserver.onNext( + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toResponse(evidence)); + responseObserver.onCompleted(); + } catch (AdminAuthorizationException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED.withDescription(denied.getMessage()).asRuntimeException()); + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT.withDescription(invalid.getMessage()).asRuntimeException()); + } catch (IllegalStateException unavailable) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription(unavailable.getMessage()) + .asRuntimeException()); + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL.withDescription("Historical evidence read failed").asRuntimeException()); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuard.java new file mode 100644 index 0000000000..70c8cad618 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuard.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.util.Set; +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.gamesession.v1.HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc; + +/** Exact same-namespace World or Account workload authorization for the historical read. */ +public final class HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuard { + private static final String METHOD_NAME = + "game_session.v1.HistoricalOriginalStartSessionOwnerEvidenceReadService/" + + "ReadHistoricalOriginalStartSessionOwnerEvidence"; + private static final Set ALLOWED_SERVICES = + Set.of("world-management-service", "account-service"); + + private final String trustedNamespace; + + public HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuard(String trustedNamespace) { + this.trustedNamespace = trustedNamespace; + } + + public void requireHistoricalOwnerReadCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!METHOD_NAME.equals( + HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc + .getReadHistoricalOriginalStartSessionOwnerEvidenceMethod() + .getFullMethodName()) + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || peer == null + || !ALLOWED_SERVICES.contains(peer.service()) + || !trustedNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + trustedNamespace + "/sa/" + peer.service()).equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Historical StartSession evidence requires the exact same-namespace World or Account workload without caller context"); + } + } + + public void requireConfiguredTargetNamespace(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || !trustedNamespace.equals(targetNamespace)) { + throw new AdminAuthorizationException( + "Historical StartSession evidence target namespace is not configured here"); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java index 8028222986..659be9c89b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java @@ -13,6 +13,7 @@ import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; @@ -140,6 +141,179 @@ void expiredOwnerLeaseHidesOtherwiseRetainedAssociationEvidence() throws Excepti assertThat(fixture.read(selector(starting.startingInstance().launchAssociation()))).isEmpty(); } + @Test + void historicalReadReturnsExactEvidenceAfterLeaseExpiryWithoutWritingOwnerState() + throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple( + "historical-original-association-expired"); + Fixture fixture = fixture(tuple, Duration.ofSeconds(5)); + OwnerBackedStarting starting = fixture.startWithOwnerPins(tuple); + HistoricalOriginalStartSessionOwnerEvidence.Request request = historicalRequest(starting); + int attemptsBefore = count(fixture, "game_session_start_session_operator_attempt"); + int selectionPinsBefore = count(fixture, "game_session_start_session_template_association_pin"); + int descriptorPinsBefore = count(fixture, "game_session_start_session_launch_descriptor_pin"); + int associationsBefore = count(fixture, "game_session_canonical_instance_launch"); + Thread.sleep(5_250L); + + var evidence = fixture.historicalRead(request).orElseThrow(); + + assertThat(evidence.originalTuple().canonicalBytes()).containsExactly(tuple.canonicalBytes()); + assertThat(evidence.ownerAttemptId()).isEqualTo(starting.claim().ownerAttemptId()); + assertThat(evidence.ownerFence()).isEqualTo(starting.claim().ownerFence()).isPositive(); + assertThat(evidence.accountRedemptionProjection()) + .containsExactly( + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.projection(tuple) + .canonicalBytes()); + assertThat(evidence.firstSelection().request().selection()) + .isInstanceOf(InitialConfigured.class); + assertThat(evidence.firstSelection().association().templateId()) + .isEqualTo(tuple.preAuthorizationTuple().action().target().gameTemplateId()); + assertThat(evidence.descriptorPin().outcome()) + .isInstanceOf( + net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec + .DescriptorOutcome.class); + assertThat(evidence.launchAssociation().gameInstanceUuid()) + .isEqualTo(starting.startingInstance().gameInstanceUuid()); + assertThat(evidence.launchAssociation().launchBindingEvidence()) + .isEqualTo(starting.startingInstance().launchAssociation().launchBindingEvidence()); + assertThat(count(fixture, "game_session_start_session_operator_attempt")) + .isEqualTo(attemptsBefore); + assertThat(count(fixture, "game_session_start_session_template_association_pin")) + .isEqualTo(selectionPinsBefore); + assertThat(count(fixture, "game_session_start_session_launch_descriptor_pin")) + .isEqualTo(descriptorPinsBefore); + assertThat(count(fixture, "game_session_canonical_instance_launch")) + .isEqualTo(associationsBefore); + } + + @Test + void historicalReadFailsClosedForWrongAttemptFenceTupleAssociationAndMissingProjectionOrPin() { + StartSessionPostAuthorizationExecutionTuple tuple = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple( + "historical-original-association-mismatch"); + Fixture fixture = fixture(tuple, Duration.ofSeconds(30)); + OwnerBackedStarting starting = fixture.startWithOwnerPins(tuple); + var exact = historicalRequest(starting); + var selector = exact.associationSelector(); + + assertThat( + fixture.historicalRead( + new HistoricalOriginalStartSessionOwnerEvidence.Request( + selector, UUID.randomUUID(), exact.expectedOwnerFence()))) + .isEmpty(); + assertThat( + fixture.historicalRead( + new HistoricalOriginalStartSessionOwnerEvidence.Request( + selector, exact.expectedOwnerAttemptId(), exact.expectedOwnerFence() + 1L))) + .isEmpty(); + var wrongAssociation = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + selector.readRequestId(), + selector.targetNamespace(), + selector.canonicalTenantId(), + selector.worldSlug(), + UUID.randomUUID(), + selector.controlPlaneRequestId(), + selector.launchDescriptorId(), + selector.expectedDescriptorRequestDigest(), + selector.expectedDescriptorResultDigest(), + selector.expectedReleaseAttestationEvidenceDigest()); + assertThat( + fixture.historicalRead( + new HistoricalOriginalStartSessionOwnerEvidence.Request( + wrongAssociation, exact.expectedOwnerAttemptId(), exact.expectedOwnerFence()))) + .isEmpty(); + + disableAttemptEvidenceImmutability(fixture); + try { + fixture + .dsl() + .execute( + "UPDATE game_session_start_session_operator_attempt " + + "SET post_authorization_execution_tuple = decode('0102', 'hex') " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + starting.startingInstance().launchAssociation().targetNamespace(), + starting.startingInstance().launchAssociation().controlPlaneRequestId()); + } finally { + enableAttemptEvidenceImmutability(fixture); + } + assertThat(fixture.historicalRead(exact)).isEmpty(); + } + + @Test + void historicalReadDeniesMissingAndCorruptedAttachedAccountProjection() { + StartSessionPostAuthorizationExecutionTuple tuple = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple( + "historical-original-association-projection"); + Fixture missing = fixture(tuple, Duration.ofSeconds(30)); + OwnerBackedStarting missingStarting = missing.startWithOwnerPins(tuple); + var missingRequest = historicalRequest(missingStarting); + disableAttemptEvidenceImmutability(missing); + try { + missing + .dsl() + .execute( + "UPDATE game_session_start_session_operator_attempt " + + "SET account_redemption_projection = NULL " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + missingStarting.startingInstance().launchAssociation().targetNamespace(), + missingStarting.startingInstance().launchAssociation().controlPlaneRequestId()); + } finally { + enableAttemptEvidenceImmutability(missing); + } + assertThat(missing.historicalRead(missingRequest)).isEmpty(); + + Fixture corrupt = fixture(tuple, Duration.ofSeconds(30)); + OwnerBackedStarting corruptStarting = corrupt.startWithOwnerPins(tuple); + var corruptRequest = historicalRequest(corruptStarting); + disableAttemptEvidenceImmutability(corrupt); + try { + corrupt + .dsl() + .execute( + "UPDATE game_session_start_session_operator_attempt " + + "SET account_redemption_projection = decode('00', 'hex') " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + corruptStarting.startingInstance().launchAssociation().targetNamespace(), + corruptStarting.startingInstance().launchAssociation().controlPlaneRequestId()); + } finally { + enableAttemptEvidenceImmutability(corrupt); + } + assertThatThrownBy(() -> corrupt.historicalRead(corruptRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("historical original StartSession owner evidence is malformed"); + } + + @Test + void historicalReadDeniesAnAbsentImmutableSelectionPin() { + StartSessionPostAuthorizationExecutionTuple tuple = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple( + "historical-original-association-no-selection-pin"); + Fixture fixture = fixture(tuple, Duration.ofSeconds(30)); + OwnerBackedStarting starting = fixture.startWithOwnerAttemptWithoutPins(tuple); + + assertThat(fixture.historicalRead(historicalRequest(starting))).isEmpty(); + + Fixture mismatched = fixture(tuple, Duration.ofSeconds(30)); + OwnerBackedStarting mismatchedStarting = mismatched.startWithOwnerPins(tuple); + disableSelectionPinImmutability(mismatched); + try { + mismatched + .dsl() + .execute( + "UPDATE game_session_start_session_template_association_pin " + + "SET association_request_digest = ? " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + "sha256:" + "c".repeat(64), + mismatchedStarting.startingInstance().launchAssociation().targetNamespace(), + mismatchedStarting.startingInstance().launchAssociation().controlPlaneRequestId()); + } finally { + enableSelectionPinImmutability(mismatched); + } + assertThat(mismatched.historicalRead(historicalRequest(mismatchedStarting))).isEmpty(); + } + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector( net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation association) { var binding = association.launchBindingEvidence(); @@ -157,6 +331,50 @@ private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request select binding.releaseAttestation().evidenceDigest()); } + private static HistoricalOriginalStartSessionOwnerEvidence.Request historicalRequest( + OwnerBackedStarting starting) { + return new HistoricalOriginalStartSessionOwnerEvidence.Request( + selector(starting.startingInstance().launchAssociation()), + starting.claim().ownerAttemptId(), + starting.claim().ownerFence()); + } + + private static int count(Fixture fixture, String tableName) { + return fixture.dsl().fetchCount(DSL.table(DSL.name(tableName))); + } + + private static void disableAttemptEvidenceImmutability(Fixture fixture) { + fixture + .dsl() + .execute( + "ALTER TABLE game_session_start_session_operator_attempt " + + "DISABLE TRIGGER game_session_start_session_operator_attempt_immutable"); + } + + private static void enableAttemptEvidenceImmutability(Fixture fixture) { + fixture + .dsl() + .execute( + "ALTER TABLE game_session_start_session_operator_attempt " + + "ENABLE TRIGGER game_session_start_session_operator_attempt_immutable"); + } + + private static void disableSelectionPinImmutability(Fixture fixture) { + fixture + .dsl() + .execute( + "ALTER TABLE game_session_start_session_template_association_pin " + + "DISABLE TRIGGER gs_start_session_template_association_pin_immutable"); + } + + private static void enableSelectionPinImmutability(Fixture fixture) { + fixture + .dsl() + .execute( + "ALTER TABLE game_session_start_session_template_association_pin " + + "ENABLE TRIGGER gs_start_session_template_association_pin_immutable"); + } + private static CompleteLaunchBindingEvidence completeBinding( AuthoredWorldLaunchDescriptorEvidence descriptor, UUID canonicalVersionId) { List participants = @@ -364,6 +582,32 @@ OwnerBackedStarting startWithOwnerPins(StartSessionPostAuthorizationExecutionTup return new OwnerBackedStarting(startingInstance, claim); } + OwnerBackedStarting startWithOwnerAttemptWithoutPins( + StartSessionPostAuthorizationExecutionTuple tuple) { + ReservationResult reservation = + Objects.requireNonNull(transactions.execute(status -> attempts.reserve(tuple))); + AttemptClaim claim = reservation.claim().orElseThrow(); + transactions.executeWithoutResult( + status -> + attempts.attachAccountRedemptionProjection( + claim, + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.projection( + tuple))); + var descriptor = unpinnedDescriptor(tuple, source); + var binding = completeBinding(descriptor, CANONICAL_VERSION); + StartingInstance startingInstance = + Objects.requireNonNull( + transactions.execute( + status -> + starting.createStarting( + tenantAssociation, + binding, + tuple.preAuthorizationTuple().action().target().ownerAccountId(), + tuple.controlPlaneRequestId(), + "f".repeat(64)))); + return new OwnerBackedStarting(startingInstance, claim); + } + StartingInstance startWithoutOwnerPins(StartSessionPostAuthorizationExecutionTuple tuple) { var descriptor = unpinnedDescriptor(tuple, source); var binding = completeBinding(descriptor, CANONICAL_VERSION); @@ -382,6 +626,11 @@ java.util.Optional read( CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector) { return reads.readOriginalStartSessionAssociation(selector); } + + java.util.Optional historicalRead( + HistoricalOriginalStartSessionOwnerEvidence.Request request) { + return reads.readHistoricalOriginalStartSessionOwnerEvidence(request); + } } private record OwnerBackedStarting(StartingInstance startingInstance, AttemptClaim claim) {} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java index 4a6fce5458..05970d7289 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java @@ -1,11 +1,19 @@ package unit.net.firedevops.firemud.gamesession.repository; +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.mock; import static org.mockito.Mockito.verifyNoInteractions; +import java.util.Arrays; +import java.util.List; import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; @@ -73,6 +81,90 @@ void originalStartSessionOwnerReadAlsoRequiresOneCommittedOwnerSnapshot() { verifyNoInteractions(dsl); } + @Test + void historicalReadUsesOneImmutableSnapshotWithoutCurrentStatusOrLeaseAuthority() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + var request = historicalRequest(NAMESPACE); + AtomicReference sql = new AtomicReference<>(); + AtomicReference> bindValues = new AtomicReference<>(); + doAnswer( + invocation -> { + Object[] rawArguments = invocation.getRawArguments(); + sql.set((String) rawArguments[0]); + bindValues.set(List.copyOf(Arrays.asList((Object[]) rawArguments[1]))); + return null; + }) + .when(dsl) + .fetchOne(anyString(), any(Object[].class)); + + assertThat(repository.readHistoricalOriginalStartSessionOwnerEvidence(request)).isEmpty(); + + assertThat(sql.get()) + .contains("FROM game_session_canonical_instance_launch association") + .contains("JOIN game_session_start_session_operator_attempt attempt") + .contains("JOIN game_session_start_session_template_association_pin association_pin") + .contains("JOIN game_session_start_session_launch_descriptor_pin descriptor_pin") + .doesNotContain("game_instances") + .doesNotContain("lease_expires_at") + .doesNotContain("clock_timestamp") + .doesNotContain("phase_state") + .doesNotContain("FOR UPDATE") + .doesNotContain("INSERT ") + .doesNotContain("UPDATE ") + .doesNotContain("DELETE "); + assertThat(bindValues.get()) + .containsExactly( + request.expectedOwnerAttemptId(), + request.expectedOwnerFence(), + NAMESPACE, + request.associationSelector().canonicalTenantId(), + request.associationSelector().worldSlug(), + request.associationSelector().gameInstanceUuid(), + request.associationSelector().controlPlaneRequestId(), + request.associationSelector().launchDescriptorId()); + } + + @Test + void historicalReadRejectsWrongNamespaceAndAmbientTransactionsBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + + assertThatThrownBy( + () -> + repository.readHistoricalOriginalStartSessionOwnerEvidence( + historicalRequest("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("another Game Session namespace"); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy( + () -> + repository.readHistoricalOriginalStartSessionOwnerEvidence( + historicalRequest(NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed owner read"); + + verifyNoInteractions(dsl); + } + + private static HistoricalOriginalStartSessionOwnerEvidence.Request historicalRequest( + String namespace) { + return new HistoricalOriginalStartSessionOwnerEvidence.Request( + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + namespace, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "start-session-request", + "launch-descriptor", + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + 9L); + } + private static FreshGameSessionTenantAssociation freshTenant() { RuntimeTenantIdentityEvidence source = new RuntimeTenantIdentityEvidence( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java new file mode 100644 index 0000000000..42eda16001 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java @@ -0,0 +1,530 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +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.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionReconciliationRequiredException; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOwnerProofOutcome; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class CanonicalInitialAdmissionOwnerReadGrpcServiceTest { + private static final String NAMESPACE = "dev"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final String REQUEST_ID = "initial-admission-1"; + private static final Instant TERMINAL_AT = Instant.parse("2025-02-03T04:05:06.123456Z"); + + @AfterEach + void clearContext() { + SessionContext.clear(); + } + + @Test + void sameNamespaceWorldWorkloadReceivesCompletePendingTupleWithoutTerminalFields() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + HoldIdentity identity = identity(); + when(repository.read(NAMESPACE, REQUEST_ID)) + .thenReturn(Optional.of(ownerProof(identity, "PENDING"))); + var service = service(repository); + + var result = invokeAsWorld(service, request(identity)); + + assertNull(result.status()); + GetCanonicalInitialAdmissionOwnerProofResponse response = result.response(); + assertCompleteTuple(identity, response); + assertEquals( + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING, + response.getOutcome()); + assertFalse(response.hasCommittedPointerVersion()); + assertFalse(response.hasAuditEventId()); + assertEquals("", response.getProofDigest()); + assertFalse(response.getPositiveDurableAbort()); + assertFalse(response.hasTerminalAt()); + verify(repository).read(NAMESPACE, REQUEST_ID); + } + + @Test + void closedOriginReadbackEchoesPriorPointerVersionWithoutTreatingPendingAsTerminal() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + HoldIdentity identity = identity(InitialAdmissionOrigin.EXPECT_CLOSED, 1L); + when(repository.read(NAMESPACE, REQUEST_ID)) + .thenReturn(Optional.of(ownerProof(identity, "PENDING"))); + + var result = invokeAsWorld(service(repository), request(identity)); + + assertNull(result.status()); + assertCompleteTuple(identity, result.response()); + assertEquals( + net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOrigin + .CANONICAL_INITIAL_ADMISSION_ORIGIN_EXPECT_CLOSED, + result.response().getOrigin()); + assertTrue(result.response().hasExpectedPriorPointerVersion()); + assertEquals(1L, result.response().getExpectedPriorPointerVersion()); + assertEquals( + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING, + result.response().getOutcome()); + assertFalse(result.response().hasCommittedPointerVersion()); + } + + @Test + void closedOriginCommitMustAdvanceThePriorPointerExactlyOnce() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + HoldIdentity identity = identity(InitialAdmissionOrigin.EXPECT_CLOSED, 1L); + when(repository.read(NAMESPACE, REQUEST_ID)) + .thenReturn(Optional.of(ownerProof(identity, "COMMITTED"))); + + var result = invokeAsWorld(service(repository), request(identity)); + + assertNull(result.status()); + assertEquals(2L, result.response().getCommittedPointerVersion()); + } + + @Test + void committedReadbackFailsClosedWhenPriorPointerVersionCannotAdvance() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + HoldIdentity identity = identity(InitialAdmissionOrigin.EXPECT_CLOSED, Long.MAX_VALUE); + when(repository.read(NAMESPACE, REQUEST_ID)) + .thenReturn(Optional.of(ownerProof(identity, "COMMITTED", TENANT, 1L))); + + var result = invokeAsWorld(service(repository), request(identity)); + + assertEquals(Status.Code.FAILED_PRECONDITION, result.status().getCode()); + } + + @Test + void committedOwnerReadbackMapsExactPointerAuditAndTerminalProof() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + HoldIdentity identity = identity(); + when(repository.read(NAMESPACE, REQUEST_ID)) + .thenReturn(Optional.of(ownerProof(identity, "COMMITTED"))); + + var result = invokeAsWorld(service(repository), request(identity)); + + assertNull(result.status()); + var response = result.response(); + assertCompleteTuple(identity, response); + assertEquals( + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED, + response.getOutcome()); + assertEquals(1L, response.getCommittedPointerVersion()); + assertEquals(41L, response.getAuditEventId()); + assertEquals("sha256:" + "b".repeat(64), response.getProofDigest()); + assertFalse(response.getPositiveDurableAbort()); + assertEquals(TERMINAL_AT.getEpochSecond(), response.getTerminalAt().getSeconds()); + assertEquals(TERMINAL_AT.getNano(), response.getTerminalAt().getNanos()); + } + + @Test + void durableAbortMapsOnlyPositiveFencingAndTerminalProof() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + HoldIdentity identity = identity(); + when(repository.read(NAMESPACE, REQUEST_ID)) + .thenReturn(Optional.of(ownerProof(identity, "ABORTED"))); + + var result = invokeAsWorld(service(repository), request(identity)); + + assertNull(result.status()); + var response = result.response(); + assertCompleteTuple(identity, response); + assertEquals( + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED, + response.getOutcome()); + assertFalse(response.hasCommittedPointerVersion()); + assertFalse(response.hasAuditEventId()); + assertEquals("sha256:" + "c".repeat(64), response.getProofDigest()); + assertTrue(response.getPositiveDurableAbort()); + assertTrue(response.hasTerminalAt()); + } + + @Test + void refusesWrongWorkloadAndCrossNamespaceBeforeReadingOwnerState() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + var service = service(repository); + var request = request(identity()); + + assertEquals(Status.Code.PERMISSION_DENIED, invoke(service, request).status().getCode()); + assertEquals( + Status.Code.PERMISSION_DENIED, + invokeAsPeer(service, request, "game-session-service", NAMESPACE).status().getCode()); + assertEquals( + Status.Code.PERMISSION_DENIED, + invokeAsPeer(service, request, "world-management-service", "other").status().getCode()); + verifyNoInteractions(repository); + } + + @Test + void refusesForeignWorkloadAndMatchingForeignRequestOutsideTrustedNamespace() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + HoldIdentity foreignIdentity = identity("other", InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + var foreignRequest = request(foreignIdentity); + + var result = + invokeAsPeer(service(repository), foreignRequest, "world-management-service", "other"); + + assertEquals(Status.Code.PERMISSION_DENIED, result.status().getCode()); + verifyNoInteractions(repository); + } + + @Test + void refusesInvalidServerOwnedTrustedNamespace() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + + var result = invokeAsWorld(service(repository, ""), request(identity())); + + assertEquals(Status.Code.PERMISSION_DENIED, result.status().getCode()); + verifyNoInteractions(repository); + } + + @Test + void refusesAuthenticatedEndUserCallerContextEvenWithWorldWorkloadPeer() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + SessionContext.setContext( + "42", java.util.List.of(), java.util.Map.of(), true, "world-management-service", "wms-1"); + + var result = invokeAsWorld(service(repository), request(identity())); + + assertEquals(Status.Code.PERMISSION_DENIED, result.status().getCode()); + verifyNoInteractions(repository); + } + + @Test + void rejectsUnknownFieldsMalformedTupleAndForgedHoldDigestBeforeReading() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + var service = service(repository); + HoldIdentity identity = identity(); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + + assertEquals( + Status.Code.INVALID_ARGUMENT, + invokeAsWorld(service, request(identity).toBuilder().setUnknownFields(unknown).build()) + .status() + .getCode()); + assertEquals( + Status.Code.INVALID_ARGUMENT, + invokeAsWorld( + service, + request(identity).toBuilder().setCanonicalTenantId("not-a-canonical-uuid").build()) + .status() + .getCode()); + assertEquals( + Status.Code.INVALID_ARGUMENT, + invokeAsWorld( + service, + request(identity).toBuilder() + .setHoldBindingDigest("sha256:" + "0".repeat(64)) + .build()) + .status() + .getCode()); + verifyNoInteractions(repository); + } + + @Test + void missingAmbiguousAndMismatchedOwnerReadbacksNeverProduceDomainOutcomes() { + HoldIdentity identity = identity(); + + CanonicalInitialAdmissionRepository missing = mock(CanonicalInitialAdmissionRepository.class); + when(missing.read(NAMESPACE, REQUEST_ID)).thenReturn(Optional.empty()); + assertEquals( + Status.Code.FAILED_PRECONDITION, + invokeAsWorld(service(missing), request(identity)).status().getCode()); + + CanonicalInitialAdmissionRepository ambiguous = mock(CanonicalInitialAdmissionRepository.class); + when(ambiguous.read(NAMESPACE, REQUEST_ID)) + .thenThrow( + new CanonicalInitialAdmissionReconciliationRequiredException("conflicting readback")); + assertEquals( + Status.Code.FAILED_PRECONDITION, + invokeAsWorld(service(ambiguous), request(identity)).status().getCode()); + + CanonicalInitialAdmissionRepository mismatched = + mock(CanonicalInitialAdmissionRepository.class); + when(mismatched.read(NAMESPACE, REQUEST_ID)) + .thenReturn( + Optional.of( + ownerProof(identity, "COMMITTED", uuid("99999999-9999-4999-8999-999999999999")))); + assertEquals( + Status.Code.FAILED_PRECONDITION, + invokeAsWorld(service(mismatched), request(identity)).status().getCode()); + } + + private static void assertCompleteTuple( + HoldIdentity identity, GetCanonicalInitialAdmissionOwnerProofResponse response) { + assertNotNull(response); + Request request = identity.request(); + assertEquals(NAMESPACE, response.getTargetNamespace()); + assertEquals(REQUEST_ID, response.getInitialAdmissionRequestId()); + assertEquals( + request.initialAdmissionRequestDigest(), response.getInitialAdmissionRequestDigest()); + assertNotEquals( + "sha256:" + request.initialAdmissionRequestDigest(), identity.holdBindingDigest()); + assertEquals(TENANT.toString(), response.getCanonicalTenantId()); + assertEquals("demo-world", response.getWorldSlug()); + assertEquals(REALM.toString(), response.getRealmId()); + assertEquals(PLAYABLE_NAMESPACE.toString(), response.getPlayableStateNamespaceId()); + assertEquals("SHARED", response.getPlayableStateScope()); + assertEquals(INSTANCE.toString(), response.getCanonicalGameInstanceId()); + assertEquals(VERSION.toString(), response.getCanonicalVersionId()); + assertEquals(7L, response.getActiveLifecycleEpoch()); + assertEquals(3L, response.getExpectedCatalogRevision()); + assertEquals(toWireOrigin(request.initialAdmissionOrigin()), response.getOrigin()); + if (request.expectedPriorPointerVersion() == null) { + assertFalse(response.hasExpectedPriorPointerVersion()); + } else { + assertTrue(response.hasExpectedPriorPointerVersion()); + assertEquals( + request.expectedPriorPointerVersion(), response.getExpectedPriorPointerVersion()); + } + assertEquals(HOLD_ID.toString(), response.getHoldId()); + assertEquals(HOLD_FENCE.toString(), response.getHoldFence()); + assertEquals(identity.holdBindingDigest(), response.getHoldBindingDigest()); + assertTrue(response.getUnknownFields().asMap().isEmpty()); + } + + private static CanonicalInitialAdmissionOwnerProof ownerProof( + HoldIdentity identity, String outcome) { + return ownerProof(identity, outcome, TENANT); + } + + private static CanonicalInitialAdmissionOwnerProof ownerProof( + HoldIdentity identity, String outcome, UUID tenantId) { + Request request = identity.request(); + long committedPointerVersion = + request.expectedPriorPointerVersion() == null + || request.expectedPriorPointerVersion() == Long.MAX_VALUE + ? 1L + : Math.addExact(request.expectedPriorPointerVersion(), 1L); + return ownerProof(identity, outcome, tenantId, committedPointerVersion); + } + + private static CanonicalInitialAdmissionOwnerProof ownerProof( + HoldIdentity identity, String outcome, UUID tenantId, long committedPointerVersion) { + Request request = identity.request(); + boolean committed = "COMMITTED".equals(outcome); + boolean aborted = "ABORTED".equals(outcome); + return new CanonicalInitialAdmissionOwnerProof( + CanonicalInitialAdmissionOwnerProof.Outcome.valueOf(outcome), + request.initialAdmissionRequestId(), + request.initialAdmissionRequestDigest(), + request.targetNamespace(), + tenantId, + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + request.activeLifecycleEpoch(), + request.expectedCatalogRevision(), + OriginKind.valueOf(request.initialAdmissionOrigin().name()), + request.expectedPriorPointerVersion(), + identity.holdId(), + identity.holdFence(), + identity.holdBindingDigest(), + committed ? committedPointerVersion : null, + committed ? 41L : null, + committed ? "sha256:" + "b".repeat(64) : aborted ? "sha256:" + "c".repeat(64) : null, + aborted, + committed || aborted ? TERMINAL_AT : null); + } + + private static HoldIdentity identity() { + return identity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + } + + private static HoldIdentity identity( + InitialAdmissionOrigin origin, Long expectedPriorPointerVersion) { + return identity(NAMESPACE, origin, expectedPriorPointerVersion); + } + + private static HoldIdentity identity( + String namespace, InitialAdmissionOrigin origin, Long expectedPriorPointerVersion) { + OriginKind originKind = OriginKind.valueOf(origin.name()); + String digest = + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest + .computeRequestDigest( + namespace, + TENANT, + "demo-world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 7L, + 3L, + originKind, + expectedPriorPointerVersion, + REQUEST_ID); + Request request = + new Request( + namespace, + TENANT, + "demo-world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 7L, + REQUEST_ID, + digest, + origin, + 3L, + expectedPriorPointerVersion); + return new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + } + + private static GetCanonicalInitialAdmissionOwnerProofRequest request(HoldIdentity identity) { + Request request = identity.request(); + var builder = + GetCanonicalInitialAdmissionOwnerProofRequest.newBuilder() + .setTargetNamespace(request.targetNamespace()) + .setInitialAdmissionRequestId(request.initialAdmissionRequestId()) + .setInitialAdmissionRequestDigest(request.initialAdmissionRequestDigest()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setRealmId(request.realmId().toString()) + .setPlayableStateNamespaceId(request.playableStateNamespaceId().toString()) + .setPlayableStateScope(request.playableStateScope()) + .setCanonicalGameInstanceId(request.canonicalGameInstanceId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setActiveLifecycleEpoch(request.activeLifecycleEpoch()) + .setExpectedCatalogRevision(request.expectedCatalogRevision()) + .setOrigin(toWireOrigin(request.initialAdmissionOrigin())) + .setHoldId(identity.holdId().toString()) + .setHoldFence(identity.holdFence().toString()) + .setHoldBindingDigest(identity.holdBindingDigest()); + if (request.expectedPriorPointerVersion() != null) { + builder.setExpectedPriorPointerVersion(request.expectedPriorPointerVersion()); + } + return builder.build(); + } + + private static net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOrigin toWireOrigin( + InitialAdmissionOrigin origin) { + return switch (origin) { + case NO_PRIOR_POINTER -> + net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOrigin + .CANONICAL_INITIAL_ADMISSION_ORIGIN_NO_PRIOR_POINTER; + case EXPECT_CLOSED -> + net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOrigin + .CANONICAL_INITIAL_ADMISSION_ORIGIN_EXPECT_CLOSED; + }; + } + + private static CanonicalInitialAdmissionOwnerReadGrpcService service( + CanonicalInitialAdmissionRepository repository) { + return service(repository, NAMESPACE); + } + + private static CanonicalInitialAdmissionOwnerReadGrpcService service( + CanonicalInitialAdmissionRepository repository, String trustedNamespace) { + return new CanonicalInitialAdmissionOwnerReadGrpcService( + repository, new CanonicalInitialAdmissionOwnerReadWorkloadGuard(trustedNamespace)); + } + + private static ReadResult invokeAsWorld( + CanonicalInitialAdmissionOwnerReadGrpcService service, + GetCanonicalInitialAdmissionOwnerProofRequest request) { + return invokeAsPeer(service, request, "world-management-service", NAMESPACE); + } + + private static ReadResult invokeAsPeer( + CanonicalInitialAdmissionOwnerReadGrpcService service, + GetCanonicalInitialAdmissionOwnerProofRequest request, + String peerService, + String peerNamespace) { + AtomicReference result = new AtomicReference<>(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + peerNamespace + "/sa/" + peerService, + peerNamespace, + peerService)) + .run(() -> result.set(invoke(service, request))); + return result.get(); + } + + private static ReadResult invoke( + CanonicalInitialAdmissionOwnerReadGrpcService service, + GetCanonicalInitialAdmissionOwnerProofRequest request) { + AtomicReference response = + new AtomicReference<>(); + AtomicReference status = new AtomicReference<>(); + service.getCanonicalInitialAdmissionOwnerProof( + request, + new StreamObserver<>() { + @Override + public void onNext(GetCanonicalInitialAdmissionOwnerProofResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable throwable) { + status.set(Status.fromThrowable(throwable)); + } + + @Override + public void onCompleted() {} + }); + return new ReadResult(response.get(), status.get()); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record ReadResult( + GetCanonicalInitialAdmissionOwnerProofResponse response, Status status) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java new file mode 100644 index 0000000000..687c4ff3bb --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java @@ -0,0 +1,744 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +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.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.service.impl.HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceRequest; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_SERVICE = "world-management-service"; + private static final String ACCOUNT_SERVICE = "account-service"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final UUID GAME_INSTANCE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID STATE_NAMESPACE = uuid("44444444-4444-4444-8444-444444444444"); + private static final long OWNER_FENCE = 8L; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearEndUserContext() { + SessionContext.clear(); + } + + @Test + void exactSameNamespaceWorldAndAccountHandlersReturnExpiredCanonicalRetainedEvidence() + throws Exception { + Fixture fixture = fixture(); + CanonicalGameInstanceLaunchAssociationRepository repository = mockRepository(); + when(repository.readHistoricalOriginalStartSessionOwnerEvidence(fixture.request())) + .thenReturn(Optional.of(fixture.result())); + var service = + new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService(repository, NAMESPACE); + + RecordingObserver worldResponse = + invokeAs(service, fixture.wireRequest(), WORLD_SERVICE); + RecordingObserver accountResponse = + invokeAs(service, fixture.wireRequest(), ACCOUNT_SERVICE); + + var expected = + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toResponse(fixture.result()); + assertThat(worldResponse.response()).isEqualTo(expected); + assertThat(accountResponse.response()).isEqualTo(expected); + assertThat(worldResponse.error()).isNull(); + assertThat(accountResponse.error()).isNull(); + assertThat(worldResponse.completed()).isTrue(); + assertThat(accountResponse.completed()).isTrue(); + var decoded = + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse( + fixture.request(), worldResponse.response()); + assertThat(decoded.originalTuple().canonicalBytes()) + .containsExactly(fixture.result().originalTuple().canonicalBytes()); + assertThat(decoded.ownerAttemptId()).isEqualTo(ATTEMPT); + assertThat(decoded.ownerFence()).isEqualTo(OWNER_FENCE); + assertThat(decoded.accountRedemptionProjection()) + .containsExactly(fixture.result().accountRedemptionProjection()); + assertThat(decoded.firstSelection().request().selection()) + .isInstanceOf(StartSessionTemplateAssociationReadEvidence.InitialConfigured.class); + verify(repository, times(2)).readHistoricalOriginalStartSessionOwnerEvidence(fixture.request()); + verifyNoMoreInteractions(repository); + } + + @Test + void missingAndMalformedRetainedResultsFailWithoutSendingAResponse() throws Exception { + Fixture fixture = fixture(); + CanonicalGameInstanceLaunchAssociationRepository repository = mockRepository(); + when(repository.readHistoricalOriginalStartSessionOwnerEvidence(fixture.request())) + .thenReturn(Optional.empty()); + var service = + new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService(repository, NAMESPACE); + + var missing = invokeAs(service, fixture.wireRequest(), WORLD_SERVICE); + assertRejected(missing, Status.Code.FAILED_PRECONDITION); + + HistoricalOriginalStartSessionOwnerEvidence.Result malformed = + mock(HistoricalOriginalStartSessionOwnerEvidence.Result.class); + when(malformed.request()).thenReturn(fixture.request()); + when(repository.readHistoricalOriginalStartSessionOwnerEvidence(fixture.request())) + .thenReturn(Optional.of(malformed)); + var corrupt = invokeAs(service, fixture.wireRequest(), WORLD_SERVICE); + assertRejected(corrupt, Status.Code.INTERNAL); + verify(repository, times(2)).readHistoricalOriginalStartSessionOwnerEvidence(fixture.request()); + verifyNoMoreInteractions(repository); + } + + @Test + void changedRepositoryResultEchoFailsBeforeResponseEncoding() throws Exception { + Fixture fixture = fixture(); + var changedSelector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + fixture.request().associationSelector().targetNamespace(), + fixture.request().associationSelector().canonicalTenantId(), + fixture.request().associationSelector().worldSlug(), + fixture.request().associationSelector().gameInstanceUuid(), + fixture.request().associationSelector().controlPlaneRequestId(), + fixture.request().associationSelector().launchDescriptorId(), + fixture.request().associationSelector().expectedDescriptorRequestDigest(), + fixture.request().associationSelector().expectedDescriptorResultDigest(), + fixture.request().associationSelector().expectedReleaseAttestationEvidenceDigest()); + var changedRequest = + new HistoricalOriginalStartSessionOwnerEvidence.Request( + changedSelector, fixture.request().expectedOwnerAttemptId(), OWNER_FENCE); + HistoricalOriginalStartSessionOwnerEvidence.Result mismatched = + mock(HistoricalOriginalStartSessionOwnerEvidence.Result.class); + when(mismatched.request()).thenReturn(changedRequest); + CanonicalGameInstanceLaunchAssociationRepository repository = mockRepository(); + when(repository.readHistoricalOriginalStartSessionOwnerEvidence(fixture.request())) + .thenReturn(Optional.of(mismatched)); + var service = + new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService(repository, NAMESPACE); + + var observer = invokeAs(service, fixture.wireRequest(), WORLD_SERVICE); + + assertRejected(observer, Status.Code.FAILED_PRECONDITION); + verify(repository).readHistoricalOriginalStartSessionOwnerEvidence(fixture.request()); + verifyNoMoreInteractions(repository); + } + + @Test + void invalidAndUnknownWireRequestsAreRejectedBeforeRepositoryAccess() throws Exception { + Fixture fixture = fixture(); + CanonicalGameInstanceLaunchAssociationRepository repository = mockRepository(); + var service = + new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService(repository, NAMESPACE); + var invalid = fixture.wireRequest().toBuilder().setSchemaVersion(2).build(); + var unknown = + fixture.wireRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + + assertRejected(invokeAs(service, invalid, WORLD_SERVICE), Status.Code.INVALID_ARGUMENT); + assertRejected(invokeAs(service, unknown, WORLD_SERVICE), Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void unauthorizedAndEndUserContextsAreRejectedBeforeRepositoryAccess() throws Exception { + Fixture fixture = fixture(); + CanonicalGameInstanceLaunchAssociationRepository repository = mockRepository(); + var service = + new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService(repository, NAMESPACE); + RecordingObserver noPeer = + invoke(service, fixture.wireRequest()); + assertRejected(noPeer, Status.Code.PERMISSION_DENIED); + + assertRejected( + invokeAs(service, fixture.wireRequest(), NAMESPACE, "entity-management-service"), + Status.Code.PERMISSION_DENIED); + assertRejected( + invokeAs(service, fixture.wireRequest(), "other", WORLD_SERVICE), + Status.Code.PERMISSION_DENIED); + + AtomicReference> + userResponse = new AtomicReference<>(); + runAsPeer( + ACCOUNT_SERVICE, + () -> { + SessionContext.setContext("42", List.of("tenantAdmin"), Map.of()); + userResponse.set(invoke(service, fixture.wireRequest())); + }); + assertRejected(userResponse.get(), Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + private static Fixture fixture() throws Exception { + WorldCanonicalInstanceLifecycleEvidence lifecycle = + AuthoringFixtures.lifecycleEvidence("ACTIVE", 1L); + WorldPublishedStartLocationEvidence worldSelection = + lifecycle.launchBinding().releaseAttestation().worldStartLocationEvidence(); + UUID tenant = worldSelection.request().canonicalTenantId(); + AuthoredWorldSourceEvidence source = sourceEvidence(tenant, "synthetic-world"); + AuthoredWorldLaunchDescriptorEvidence descriptor = + descriptor(source, tenant, "synthetic-world"); + AuthoredWorldReleaseAttestationEvidence release = release(descriptor, worldSelection); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + StartSessionPostAuthorizationExecutionTuple tuple = postTuple(descriptor); + UUID intakeRequestId = uuid("55555555-5555-4555-8555-555555555555"); + UUID worldOperationId = uuid("66666666-6666-4666-8666-666666666666"); + var intakeRequest = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + intakeRequestId, + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + var receipt = + new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + NAMESPACE, + intakeRequestId, + worldOperationId, + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intakeRequest), + digest('e'), + source); + var firstSelectionAssociation = + new StartSessionTemplateAssociationReadEvidence.Association( + tenant, + descriptor.gameTemplateId(), + release.canonicalVersionId(), + UUID.fromString(worldSelection.request().appliedCommitId()), + release.publishWorkflowId(), + digest('c'), + digest('d'), + NAMESPACE, + intakeRequestId, + worldOperationId, + source.operationId(), + source.worldSlug(), + source.evidenceDigest(), + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + NAMESPACE, + uuid("77777777-7777-4777-8777-777777777777"), + intakeRequestId, + tenant), + receipt); + var firstRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + NAMESPACE, + uuid("88888888-8888-4888-8888-888888888888"), + tuple.canonicalBytes(), + ATTEMPT, + OWNER_FENCE, + new StartSessionTemplateAssociationReadEvidence.InitialConfigured()); + StartSessionTemplateAssociationReadEvidence.Result firstSelection = + new StartSessionTemplateAssociationReadEvidence.Result( + firstRequest, + firstSelectionAssociation, + releaseBundle(descriptor, release), + worldSelection, + 1L); + var exactReplayRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + firstRequest.schemaVersion(), + firstRequest.targetNamespace(), + firstRequest.readRequestId(), + firstRequest.canonicalPostAuthorizationTuple(), + firstRequest.ownerAttemptId(), + firstRequest.ownerFence(), + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + firstSelectionAssociation.canonicalVersionId(), + firstSelectionAssociation.selectedCommitId(), + firstSelectionAssociation.publishWorkflowId(), + firstSelectionAssociation.associationDigest())); + var exactReplaySelection = + new StartSessionTemplateAssociationReadEvidence.Result( + exactReplayRequest, + firstSelectionAssociation, + releaseBundle(descriptor, release), + worldSelection, + 1L); + var descriptorPin = + new StartSessionLaunchDescriptorGrpcCodec.Resolved( + exactReplaySelection, + new StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome(descriptor)); + var selector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + uuid("99999999-9999-4999-8999-999999999999"), + NAMESPACE, + tenant, + descriptor.worldSlug(), + GAME_INSTANCE, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var request = + new HistoricalOriginalStartSessionOwnerEvidence.Request(selector, ATTEMPT, OWNER_FENCE); + var launchAssociation = + new HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation( + NAMESPACE, + tenant, + descriptor.worldSlug(), + GAME_INSTANCE, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + STATE_NAMESPACE, + RealmEntryPolicy.StateScope.SHARED, + true, + 2L, + binding); + byte[] associationRequestWire = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(firstRequest).toByteArray(); + byte[] associationResponseWire = + StartSessionTemplateAssociationReadGrpcCodec.toResponse(firstSelection).toByteArray(); + byte[] descriptorRequestWire = + StartSessionLaunchDescriptorGrpcCodec.toRequest(exactReplayRequest).toByteArray(); + byte[] descriptorResponseWire = + StartSessionLaunchDescriptorGrpcCodec.toResponse( + exactReplayRequest, exactReplaySelection, descriptorPin.outcome()) + .toByteArray(); + var result = + new HistoricalOriginalStartSessionOwnerEvidence.Result( + request, + tuple, + ATTEMPT, + OWNER_FENCE, + new GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L) + .canonicalBytes(), + firstSelection, + descriptorPin, + launchAssociation, + HistoricalOriginalStartSessionOwnerEvidence.sha256(associationRequestWire), + HistoricalOriginalStartSessionOwnerEvidence.sha256(associationResponseWire), + HistoricalOriginalStartSessionOwnerEvidence.sha256(descriptorRequestWire), + HistoricalOriginalStartSessionOwnerEvidence.sha256(descriptorResponseWire)); + return new Fixture( + request, result, HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request)); + } + + private static AuthoredWorldSourceEvidence sourceEvidence(UUID tenant, String worldSlug) { + UUID registrationId = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID operationId = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + String tenantSlug = "test-tenant"; + String tenantKey = "test-tenant-key"; + String displayName = "Historical Test World"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationId, tenant, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationId, + operationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + 42L, + tenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationId, + operationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + 42L, + tenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptor( + AuthoredWorldSourceEvidence source, UUID tenant, String worldSlug) { + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "historical-start-session-request", + tenant, + worldSlug, + source.operationId(), + source.evidenceDigest(), + 19L, + false, + null, + false, + null, + false, + null, + true, + "{}"); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "historical-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "historical-release-bundle", + false, + null); + } + + private static AuthoredWorldReleaseAttestationEvidence release( + AuthoredWorldLaunchDescriptorEvidence descriptor, + WorldPublishedStartLocationEvidence worldSelection) { + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + worldSelection.request().appliedCommitId(), + worldSelection.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest('f') : null)) + .toList(); + return AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + worldSelection.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + worldSelection.request().publishWorkflowId(), + worldSelection.request().appliedCommitId(), + participants, + digest('a'), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + worldSelection); + } + + private static PublishedReleaseBundle releaseBundle( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence release) { + var builder = + PublishedReleaseBundle.newBuilder() + .setId(descriptor.releaseBundleId()) + .setVersionId(descriptor.versionId()) + .setVersionNumber(1) + .setAttestationSchemaVersion("v" + release.schemaVersion()) + .setPublishWorkflowId(release.publishWorkflowId()) + .setManifestHash(release.manifestHash()) + .setManifestSchemaVersion(release.manifestSchemaVersion()) + .addAllRequiredManifestAssetKeys(release.requiredManifestAssetKeys()) + .setGenerationConfigRevision(release.generationConfigRevision()) + .setPublishedReleaseBundleRef(release.publishedReleaseBundleRef()) + .setCanonicalTenantId(release.canonicalTenantId().toString()) + .setCanonicalVersionId(release.canonicalVersionId().toString()) + .addAllCommandDefinitions(release.commandDefinitions()); + for (var participant : release.participantDigests()) { + ParticipantDigest.Builder value = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigestPresent()) { + value.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + } + builder.addParticipantDigests(value); + } + for (var artifact : release.artifactDigests()) { + builder.addArtifactDigests( + PublishedArtifactDigest.newBuilder() + .setUsageKey(artifact.usageKey()) + .setArtifactKind(artifact.artifactKind()) + .setImmutableObjectKey(artifact.immutableObjectKey()) + .setContentDigest(artifact.contentDigest()) + .setContentType(artifact.contentType()) + .setArtifactSchemaVersion(artifact.artifactSchemaVersion())); + } + return builder.build(); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple( + AuthoredWorldLaunchDescriptorEvidence descriptor) throws IOException { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(descriptor.gameTemplateId(), TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Read exact retained StartSession owner evidence"); + var pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + descriptor.controlPlaneRequestId(), ACTOR, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) + throws IOException { + String tenant = TENANT.toString(); + Instant evaluatedAt = Instant.parse("2020-01-01T00:00:00Z"); + Instant expiresAt = Instant.parse("2020-01-01T00:01:00Z"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + digest('a'), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + evaluatedAt.toString(), + "expiresAt", + expiresAt.toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + ISSUANCE_ID.toString(), + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static RecordingObserver + invokeAs( + HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService service, + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest request, + String serviceName) { + return invokeAs(service, request, NAMESPACE, serviceName); + } + + private static RecordingObserver + invokeAs( + HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService service, + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest request, + String namespace, + String serviceName) { + AtomicReference> + observer = new AtomicReference<>(); + runAsPeer(namespace, serviceName, () -> observer.set(invoke(service, request))); + return observer.get(); + } + + private static RecordingObserver invoke( + HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService service, + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest request) { + var observer = new RecordingObserver(); + service.readHistoricalOriginalStartSessionOwnerEvidence(request, observer); + return observer; + } + + private static void runAsPeer(String serviceName, Runnable action) { + runAsPeer(NAMESPACE, serviceName, action); + } + + private static void runAsPeer(String namespace, String serviceName, Runnable action) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + serviceName, namespace, serviceName); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + SessionContext.clear(); + } + } + + private static void assertRejected(RecordingObserver observer, Status.Code expectedCode) { + assertThat(observer.error()).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(observer.error()).getCode()).isEqualTo(expectedCode); + assertThat(observer.response()).isNull(); + assertThat(observer.completed()).isFalse(); + } + + private static CanonicalGameInstanceLaunchAssociationRepository mockRepository() { + return mock(CanonicalGameInstanceLaunchAssociationRepository.class); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + HistoricalOriginalStartSessionOwnerEvidence.Request request, + HistoricalOriginalStartSessionOwnerEvidence.Result result, + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest wireRequest) {} + + private static final class RecordingObserver implements StreamObserver { + private final AtomicReference response = new AtomicReference<>(); + private final AtomicReference error = new AtomicReference<>(); + private final AtomicBoolean completed = new AtomicBoolean(); + + @Override + public void onNext(T value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() { + completed.set(true); + } + + T response() { + return response.get(); + } + + Throwable error() { + return error.get(); + } + + boolean completed() { + return completed.get(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java new file mode 100644 index 0000000000..115eade73a --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java @@ -0,0 +1,109 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +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.gamesession.service.impl.HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuard; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest { + private static final String NAMESPACE = "gameplay"; + private final HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuard guard = + new HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuard(NAMESPACE); + + @AfterEach + void clearCallerContexts() { + SessionContext.clear(); + } + + @Test + void allowsOnlyExactSameNamespaceWorldAndAccountWorkloads() { + assertThatCode( + () -> + withPeer( + "world-management-service", + NAMESPACE, + () -> { + guard.requireHistoricalOwnerReadCaller(); + guard.requireConfiguredTargetNamespace(NAMESPACE); + })) + .doesNotThrowAnyException(); + assertThatCode( + () -> + withPeer( + "account-service", + NAMESPACE, + () -> { + guard.requireHistoricalOwnerReadCaller(); + guard.requireConfiguredTargetNamespace(NAMESPACE); + })) + .doesNotThrowAnyException(); + } + + @Test + void refusesOtherNamespacesWrongServicesAndAuthenticatedEndUserContext() { + assertThatThrownBy( + () -> + withPeer( + "world-management-service", "other", guard::requireHistoricalOwnerReadCaller)) + .isInstanceOf(AdminAuthorizationException.class); + assertThatThrownBy( + () -> + withPeer( + "entity-management-service", + NAMESPACE, + guard::requireHistoricalOwnerReadCaller)) + .isInstanceOf(AdminAuthorizationException.class); + assertThatThrownBy( + () -> + withPeer( + "world-management-service", + NAMESPACE, + () -> { + SessionContext.setContext( + "42", java.util.List.of("tenantAdmin"), java.util.Map.of()); + guard.requireHistoricalOwnerReadCaller(); + })) + .isInstanceOf(AdminAuthorizationException.class); + } + + @Test + void rejectsInconsistentPeerIdentityBeforeGuardInvocation() { + assertThatThrownBy( + () -> + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/world-management-service", + NAMESPACE, + "world-management-service")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesAConfiguredTargetNamespaceDifferentFromTheProducerNamespace() { + assertThatThrownBy(() -> guard.requireConfiguredTargetNamespace("other")) + .isInstanceOf(AdminAuthorizationException.class); + } + + private static void withPeer(String service, String namespace, Runnable action) { + withPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service, action); + } + + private static void withPeerIdentity( + String uri, String namespace, String service, Runnable action) { + GrpcPeerIdentity peer = new GrpcPeerIdentity(uri, namespace, service); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + SessionContext.clear(); + } + } +} From 54ec5acc589270536d229144f2d935bf7d632d1c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 15:10:11 +1300 Subject: [PATCH 08/22] Authorize canonical owner proof callers before decoding requests --- ...lInitialAdmissionOwnerReadGrpcService.java | 10 ++++++++++ ...nitialAdmissionOwnerReadWorkloadGuard.java | 13 ++++++++++--- ...tialAdmissionOwnerReadGrpcServiceTest.java | 19 +++++++++++++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java index 826022fa3f..ddbeb11d97 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java @@ -39,6 +39,16 @@ public void getCanonicalInitialAdmissionOwnerProof( GetCanonicalInitialAdmissionOwnerProofRequest request, StreamObserver responseObserver) { Objects.requireNonNull(responseObserver, "responseObserver"); + try { + workloadGuard.requireWorldManagementOwnerReadCaller(); + } catch (AdminAuthorizationException unauthorized) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Owner proof caller is not authorized") + .asRuntimeException()); + return; + } + if (request == null) { responseObserver.onError( Status.INVALID_ARGUMENT diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java index 4d513132e9..668891e3c6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java @@ -14,17 +14,15 @@ public CanonicalInitialAdmissionOwnerReadWorkloadGuard(String trustedNamespace) this.trustedNamespace = trustedNamespace; } - public void requireWorldManagementOwnerReadCaller(String targetNamespace) { + public void requireWorldManagementOwnerReadCaller() { GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); if (!"game_session.v1.GameSessionControlPlaneService/GetCanonicalInitialAdmissionOwnerProof" .equals( GameSessionControlPlaneServiceGrpc.getGetCanonicalInitialAdmissionOwnerProofMethod() .getFullMethodName()) || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) - || !GrpcPeerIdentity.isValidNamespace(targetNamespace) || peerIdentity == null || !WORLD_MANAGEMENT_SERVICE.equals(peerIdentity.service()) - || !trustedNamespace.equals(targetNamespace) || !trustedNamespace.equals(peerIdentity.namespace()) || !("spiffe://firemud/ns/" + trustedNamespace + "/sa/" + WORLD_MANAGEMENT_SERVICE) .equals(peerIdentity.uri()) @@ -33,4 +31,13 @@ public void requireWorldManagementOwnerReadCaller(String targetNamespace) { "Canonical initial-admission owner proof requires the same-namespace World Management workload identity"); } } + + public void requireWorldManagementOwnerReadCaller(String targetNamespace) { + requireWorldManagementOwnerReadCaller(); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !trustedNamespace.equals(targetNamespace)) { + throw new AdminAuthorizationException( + "Canonical initial-admission owner proof requires the same-namespace World Management workload identity"); + } + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java index 42eda16001..cca7021e17 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java @@ -195,6 +195,24 @@ void refusesWrongWorkloadAndCrossNamespaceBeforeReadingOwnerState() { verifyNoInteractions(repository); } + @Test + void refusesNullOrMalformedRequestBeforeDecodingForUnauthorizedCaller() { + CanonicalInitialAdmissionRepository repository = + mock(CanonicalInitialAdmissionRepository.class); + var service = service(repository); + var malformed = + GetCanonicalInitialAdmissionOwnerProofRequest.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + + assertEquals(Status.Code.PERMISSION_DENIED, invoke(service, null).status().getCode()); + assertEquals(Status.Code.PERMISSION_DENIED, invoke(service, malformed).status().getCode()); + verifyNoInteractions(repository); + } + @Test void refusesForeignWorkloadAndMatchingForeignRequestOutsideTrustedNamespace() { CanonicalInitialAdmissionRepository repository = @@ -249,6 +267,7 @@ void rejectsUnknownFieldsMalformedTupleAndForgedHoldDigestBeforeReading() { invokeAsWorld(service, request(identity).toBuilder().setUnknownFields(unknown).build()) .status() .getCode()); + assertEquals(Status.Code.INVALID_ARGUMENT, invokeAsWorld(service, null).status().getCode()); assertEquals( Status.Code.INVALID_ARGUMENT, invokeAsWorld( From 1315e4e77d00ac2592959f012c1c1f3b9b0af144 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 15:38:28 +1300 Subject: [PATCH 09/22] fix(game-session): reject blank optional launch identifiers --- ...eateCanonicalLaunchPreparationRequest.java | 4 ++ ...CanonicalLaunchPreparationServiceTest.java | 49 ++++++++++++++++--- 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java index 1b9b7cdded..865dfae981 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java @@ -54,6 +54,10 @@ public record CreateCanonicalLaunchPreparationRequest( requestedScriptPatchVersionPresent, requestedScriptPatchVersion, "requestedScriptPatchVersion"); + if (requestedScriptPatchVersionPresent && requestedScriptPatchVersion.isBlank()) { + throw new IllegalArgumentException( + "requestedScriptPatchVersion must be nonblank when present"); + } requireOptional(sourceVersionIdPresent, sourceVersionId, "sourceVersionId"); if (sourceVersionIdPresent && sourceVersionId <= 0L) { throw new IllegalArgumentException("sourceVersionId must be positive when present"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java index 978f2afe70..baeda58e12 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java @@ -492,7 +492,7 @@ void changedRetryInputConflictsBeforeUpstreamResolutionOrMutation() { SOURCE_INTAKE_OPERATION, 71, true, - "", // Present-empty remains distinct from absence. + "patch-v1", false, null, false, @@ -678,7 +678,7 @@ void requestDigestBindsOptionalPresenceAndDescriptorDigest() { IntakeReceipt intake = intake(source); CanonicalRealmCatalogSnapshot catalog = catalog(intake); AuthoredWorldLaunchDescriptorEvidence absentDescriptor = descriptor(absent, catalog, source); - CreateCanonicalLaunchPreparationRequest presentEmpty = + CreateCanonicalLaunchPreparationRequest present = new CreateCanonicalLaunchPreparationRequest( CONTROL_PLANE_REQUEST, ACTOR, @@ -690,22 +690,21 @@ void requestDigestBindsOptionalPresenceAndDescriptorDigest() { SOURCE_INTAKE_OPERATION, 71, true, - "", + "patch-v1", false, null, false, null, false, null); - AuthoredWorldLaunchDescriptorEvidence presentEmptyDescriptor = - descriptor(presentEmpty, catalog, source); + AuthoredWorldLaunchDescriptorEvidence presentDescriptor = descriptor(present, catalog, source); assertThat( GameSessionCanonicalLaunchPreparationRepository.requestDigest( absent, catalog, intake, absentDescriptor)) .isNotEqualTo( GameSessionCanonicalLaunchPreparationRepository.requestDigest( - presentEmpty, catalog, intake, presentEmptyDescriptor)); + present, catalog, intake, presentDescriptor)); CanonicalRealmCatalogSnapshot changedCatalogPayload = new CanonicalRealmCatalogSnapshot( @@ -734,6 +733,44 @@ void requestDigestBindsOptionalPresenceAndDescriptorDigest() { absent, catalog, intake, absentDescriptor)); } + @Test + void presentScriptPatchIdentifierMustBeNonblank() { + assertThatThrownBy(() -> requestWithScriptPatch(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("presence does not match its value"); + assertThatThrownBy(() -> requestWithScriptPatch("")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be nonblank when present"); + assertThatThrownBy(() -> requestWithScriptPatch(" \t\n")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be nonblank when present"); + + assertThat(requestWithScriptPatch("patch-v1").requestedScriptPatchVersion()) + .isEqualTo("patch-v1"); + assertThat(request().requestedScriptPatchVersionPresent()).isFalse(); + } + + private static CreateCanonicalLaunchPreparationRequest requestWithScriptPatch(String patch) { + return new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + NAMESPACE, + TENANT, + REALM, + CATALOG_REQUEST, + 1, + SOURCE_INTAKE_OPERATION, + 71, + true, + patch, + false, + null, + false, + null, + false, + null); + } + private GameSessionCanonicalLaunchPreparationService authorizedService() { return new GameSessionCanonicalLaunchPreparationService( descriptorClient, From 2814d5c31c03299262022266242d75a4e57040d4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 17:33:38 +1300 Subject: [PATCH 10/22] fix: bind original redemption and retained evidence to exact owners --- .../game-session-service/api-contracts.md | 4 +- .../player-access-and-session.md | 6 +- .../StartSessionOperatorRedemptionClient.java | 31 +- ...rtSessionOwnerEvidenceReadGrpcService.java | 67 +- ...8__start_session_launch_descriptor_pin.sql | 13 +- ...chDescriptorRepositoryIntegrationTest.java | 64 ++ ...ssionOperatorRedemptionClientMtlsTest.java | 604 ++++++++++++++++++ ...rtSessionOperatorRedemptionClientTest.java | 57 +- ...ssionOwnerEvidenceReadGrpcServiceTest.java | 59 +- 9 files changed, 857 insertions(+), 48 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index d1c55817e2..2ef34f3fdf 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -131,11 +131,11 @@ The current proto and admission-pointer mutation flow remain incomplete against #### Restricted original-claim evidence continuation -Under approved original-claim continuation decision `ae27ed99`, this narrowly bounded owner-internal read/pin continuation is separate from mutating operator RPC execution and does not change the ADR-0048 mutation digest, terminal-result, or retry rules above. It may continue only the exact original attached Account authorization projection and complete original tuple under the same stored, unexpired `PENDING` owner claim, attempt, and fence. Account remains the authority for current authorization: under its [operator-authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references), it must revalidate the original actor, `jti`, current source, reference expiry, and original redeemed attempt. The retained projection is not itself permission for another mutation. +This narrowly bounded owner-internal read/pin continuation is separate from mutating operator RPC execution and does not change the [ADR-0048 mutation digest, terminal-result, or retry rules](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md). It may continue only the exact original attached Account authorization projection and complete original tuple under the same stored, unexpired `PENDING` owner claim, attempt, and fence. Account remains the authority for current authorization: under its [operator-authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references), it must revalidate the original actor, `jti`, current source, reference expiry, and original redeemed attempt. The retained projection is not itself permission for another mutation. The continuation is restricted to reading and exact replay of an existing immutable association pin. It must not replay redemption, create or reselect an association, create a claim, attempt, fence, or authorization reference, renew or transfer ownership, mutate domain state, or admit a player. Remote Account/source reads occur outside SQL; Game Session then locks and rechecks the same owner state before returning the association. The actual pin/read statement enforces claim expiry using the database clock. Missing or unattached projections, absent or changed pins, changed tuples, expired claims, and ambiguous outcomes remain reconciliation-only and cannot be treated as authorization or admission. -Historical original-operation reconciliation is separate from that live continuation. The new local, unregistered historical read returns the exact retained StartSession tuple, actual original attempt/fence, attached Account projection, immutable first selection, and existing descriptor/release association after lease or reference expiry. Its producer accepts only exact same-namespace World or Account workload callers without end-user context. The read creates no claim, renewal, redemption, reselection, pointer/audit mutation, admission authority, current-hold proof, or terminal outcome; missing, conflicting, or malformed retained evidence fails closed. The separate current STARTING association read still requires an unexpired pending lease and is not an after-expiry endpoint. Cross-owner recovery composition and deployed recovery remain open. +Historical original-operation reconciliation is separate from that live continuation. The local, unregistered historical read returns the exact retained StartSession tuple, actual original attempt/fence, attached Account projection, immutable first selection, and existing descriptor/release association after lease or reference expiry. Its producer accepts only exact same-namespace World or Account workload callers without end-user context. The read creates no claim, renewal, redemption, reselection, pointer/audit mutation, admission authority, current-hold proof, or terminal outcome; missing, conflicting, or malformed retained evidence fails closed. The separate current STARTING association read still requires an unexpired pending lease and is not an after-expiry endpoint. Cross-owner recovery composition and deployed recovery remain open. ### gRPC Outcome Handling 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 f186df4238..872bd53986 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,13 +6,13 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The latest inactive hold client reads the exact immutable identity, actual hold status and full lifecycle snapshot over workload mTLS. Common authored fixtures are shared rather than duplicated. The original STARTING association read carries the full stored post-authorization tuple and actual owner attempt/fence, but still requires an unexpired pending claim; it is not an after-expiry association endpoint. The composed local gate passed in 1m59s: 287 Common and 2,010 Game Session unit definitions had zero failures (17 Game Session skips); integration definitions executed 18 and skipped 200, while cross-service definitions executed one and skipped 38. Cached task outputs are included. Physical Game Session job `114071452179` on `c79103014c1b991f4caaa3f1fef04652ec1adda8` failed 21 of 218 integration cases: 20 shared fixture timestamp violations and one fresh source-bound tenant guard rejecting a canonical pointer insert. Replacement physical proof remains required after the corrections. Hold snapshots and retained tuples do not supply continuous commit authority; the separately typed authenticated World/Account original-owner producer remains incomplete. +The latest inactive hold client reads the exact immutable identity, actual hold status and full lifecycle snapshot over workload mTLS. Common authored fixtures are shared rather than duplicated. The original STARTING association read carries the full stored post-authorization tuple and actual owner attempt/fence, but still requires an unexpired pending claim; it is not an after-expiry association endpoint. The composed local gate passed in 1m59s: 287 Common and 2,010 Game Session unit definitions had zero failures (17 Game Session skips); integration definitions executed 18 and skipped 200, while cross-service definitions executed one and skipped 38. Cached task outputs are included. Physical Game Session job `114071452179` on `c79103014c1b991f4caaa3f1fef04652ec1adda8` failed 21 of 218 integration cases: 20 shared fixture timestamp violations and one fresh source-bound tenant guard rejecting a canonical pointer insert. Replacement physical proof remains required after the corrections. Hold snapshots and retained tuples do not supply continuous commit authority. The authenticated historical original-owner evidence producer is implemented locally but remains unregistered and undeployed; live hold validation, continuous protection through the pointer/audit commit, and cross-owner terminal reconciliation remain incomplete. Game Session has an unregistered original-claim evidence-continuation preparation: owner repositories, typed read/pin carriers, before-and-after authenticated Account projection reads outside SQL, and database-clock claim/reference-expiry checks at descriptor pinning. Consolidated Common/Game Session unit and non-container integration checks pass, as do generated-source compilation, formatting, static analysis, and documentation checks. PostgreSQL fixtures cover expiry, exact replay, mismatch, and pin races but remain unexecuted locally without Docker. Genuine Account original-redeemed receiver revalidation and full pointer/audit/live-owner composition remain required; mocked responses do not prove that receiver. This preparation grants no new mutation authorization or admission and does not establish playable closure. The bounded contract is owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). -The same inactive preparation includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These repositories, coordinator and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Earlier consolidated local checks passed in 2m36s and after exact parent reconciliation in 54s: 271 Common and 1,992 Game Session unit definitions had zero failures (17 Game Session skips); 208 integration definitions executed 18 and skipped 190 without Docker, while cross-service definitions executed one and skipped 38. These include reused task outputs rather than a claim that every definition executed again. The PostgreSQL fixtures compile but have not physically executed locally. Document's published `2cb445617` supplies the canonical World hold request and immutable identity, including both origin selectors and the request-binding digest; the older numeric hold RPC is not that interface. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. +The same inactive preparation includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These repositories, coordinator and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Earlier consolidated local checks passed in 2m36s and after exact parent reconciliation in 54s: 271 Common and 1,992 Game Session unit definitions had zero failures (17 Game Session skips); 208 integration definitions executed 18 and skipped 190 without Docker, while cross-service definitions executed one and skipped 38. These include reused task outputs rather than a claim that every definition executed again. The PostgreSQL fixtures compile but have not physically executed locally. World Management's published change `2cb445617` supplies the canonical World hold request and immutable identity, including both origin selectors and the request-binding digest; the older numeric hold RPC is not that interface. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. -The newer inactive consumer adds exact mTLS World acquisition/identity and lifecycle read clients, the V28-backed durable pre-hold intent repository, and a coordinator that commits the immutable request before contacting World and attaches only the exact returned hold identity in a separate owner transaction. Remote failure preserves the pending intent for the same request; attached or terminal replay returns historical evidence only. Owner repositories also expose non-mutating historical reads of the complete original StartSession tuple, actual attempt/fence, attached Account projection and immutable first template pin after expiry, separately from the still-unexpired live continuation. Consolidated Common/Game Session checks, generated and integration-source compilation, formatting, Checkstyle, SpotBugs, links and Markdown checks passed in 1m5s. The local snapshot has 283 Common and 2,006 Game Session unit definitions with zero failures and 17 Game Session skips; integration definitions executed 18 and skipped 200, and cross-service executed one and skipped 38 without Docker. Cached task outputs are included, not claimed as fresh re-execution. The new PostgreSQL ordering fixture checks that a separate connection sees the exact committed pending intent before World acquisition and that remote failure/retry preserves one exact intent; it has not physically executed locally. An authenticated World-facing original-owner producer, live hold validation, continuous protection through pointer/audit commit and cross-owner terminal reconciliation remain unimplemented. Neither a historical identity nor a lifecycle snapshot proves those guarantees, and no runtime registration or activation is added. +The newer inactive consumer adds exact mTLS World acquisition/identity and lifecycle read clients, the V28-backed durable pre-hold intent repository, and a coordinator that commits the immutable request before contacting World and attaches only the exact returned hold identity in a separate owner transaction. Remote failure preserves the pending intent for the same request; attached or terminal replay returns historical evidence only. Owner repositories also expose non-mutating historical reads of the complete original StartSession tuple, actual attempt/fence, attached Account projection and immutable first template pin after expiry, separately from the still-unexpired live continuation. Consolidated Common/Game Session checks, generated and integration-source compilation, formatting, Checkstyle, SpotBugs, links and Markdown checks passed in 1m5s. The local snapshot has 283 Common and 2,006 Game Session unit definitions with zero failures and 17 Game Session skips; integration definitions executed 18 and skipped 200, and cross-service executed one and skipped 38 without Docker. Cached task outputs are included, not claimed as fresh re-execution. The new PostgreSQL ordering fixture checks that a separate connection sees the exact committed pending intent before World acquisition and that remote failure/retry preserves one exact intent; it has not physically executed locally. The authenticated historical original-owner evidence producer is implemented locally but remains unregistered and undeployed. Live hold validation, continuous protection through pointer/audit commit, and cross-owner terminal reconciliation remain unimplemented. Neither a historical identity nor a lifecycle snapshot proves those guarantees, and no runtime registration or activation is added. The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. Historical and current bounded proof, failures, and pending physical validation are recorded below. Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Hosted-terms acceptance, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898/#2848 and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java index 0bc51e4aaa..fa9172eb3d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java @@ -20,6 +20,9 @@ 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.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; @@ -47,6 +50,7 @@ public class StartSessionOperatorRedemptionClient Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); private static final UUID NIL_UUID = new UUID(0L, 0L); + private final String workloadNamespace; private final Clock clock; @SuppressFBWarnings( @@ -57,8 +61,9 @@ public StartSessionOperatorRedemptionClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, GrpcChannelFactory channelFactory, - BlockingGrpcStubCustomizer stubCustomizer) { - this(endpoints, tlsProps, channelFactory, stubCustomizer, Clock.systemUTC()); + BlockingGrpcStubCustomizer stubCustomizer, + String workloadNamespace) { + this(endpoints, tlsProps, channelFactory, stubCustomizer, workloadNamespace, Clock.systemUTC()); } @SuppressFBWarnings( @@ -70,6 +75,7 @@ public StartSessionOperatorRedemptionClient( CommonGrpcClientProperties tlsProps, GrpcChannelFactory channelFactory, BlockingGrpcStubCustomizer stubCustomizer, + String workloadNamespace, Clock clock) { super( endpoints, @@ -77,6 +83,10 @@ public StartSessionOperatorRedemptionClient( channelFactory, stubCustomizer, StartSessionOperatorRedemptionClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; this.clock = Objects.requireNonNull(clock, "clock is required"); } @@ -101,9 +111,12 @@ protected String defaultTarget() { protected StartSessionOperatorAuthorizationServiceGrpc .StartSessionOperatorAuthorizationServiceBlockingStub buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; return applyStubCustomizer( - StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel) - .withCompression("gzip")); + StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel) + .withCompression("gzip")) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)); } /** @@ -117,6 +130,7 @@ public RedemptionResult redeem( Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); Objects.requireNonNull(actualGameSessionClaim, "Game Session owner attempt claim is required"); requireExactClaimBinding(tuple, actualGameSessionClaim); + requireConfiguredNamespace(tuple, actualGameSessionClaim); requireOpaqueReference(transientOperatorAuthorizationReference); requireUnexpiredTupleEvidence(tuple); @@ -229,6 +243,15 @@ private static void requireExactClaimBinding( } } + private void requireConfiguredNamespace( + StartSessionPostAuthorizationExecutionTuple tuple, AttemptClaim claim) { + if (!workloadNamespace.equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !workloadNamespace.equals(claim.targetNamespace())) { + throw new IllegalArgumentException( + "Account StartSession redemption must use the configured workload namespace"); + } + } + private static void requireOpaqueReference(String value) { if (value == null || !OPAQUE_REFERENCE.matcher(value).matches() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java index 1d97fd960d..6977d4329c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java @@ -3,6 +3,8 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; @@ -33,40 +35,61 @@ public void readHistoricalOriginalStartSessionOwnerEvidence( ReadHistoricalOriginalStartSessionOwnerEvidenceRequest request, StreamObserver responseObserver) { Objects.requireNonNull(responseObserver, "responseObserver"); + HistoricalOriginalStartSessionOwnerEvidence.Request decodedRequest; try { workloadGuard.requireHistoricalOwnerReadCaller(); - var decodedRequest = - HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(request); + decodedRequest = HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(request); workloadGuard.requireConfiguredTargetNamespace( decodedRequest.associationSelector().targetNamespace()); - var evidence = - repository - .readHistoricalOriginalStartSessionOwnerEvidence(decodedRequest) - .orElseThrow( - () -> - new IllegalStateException( - "Exact historical StartSession evidence is unavailable")); - if (!decodedRequest.equals(evidence.request())) { - throw new IllegalStateException( - "Retained historical StartSession evidence changed the exact read request echo"); - } - responseObserver.onNext( - HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toResponse(evidence)); - responseObserver.onCompleted(); } catch (AdminAuthorizationException denied) { responseObserver.onError( - Status.PERMISSION_DENIED.withDescription(denied.getMessage()).asRuntimeException()); + Status.PERMISSION_DENIED + .withDescription("Historical evidence caller is not authorized") + .asRuntimeException()); + return; } catch (IllegalArgumentException invalid) { responseObserver.onError( - Status.INVALID_ARGUMENT.withDescription(invalid.getMessage()).asRuntimeException()); - } catch (IllegalStateException unavailable) { - responseObserver.onError( - Status.FAILED_PRECONDITION - .withDescription(unavailable.getMessage()) + Status.INVALID_ARGUMENT + .withDescription("Historical evidence request is malformed") .asRuntimeException()); + return; } catch (RuntimeException failure) { responseObserver.onError( Status.INTERNAL.withDescription("Historical evidence read failed").asRuntimeException()); + return; } + + ReadHistoricalOriginalStartSessionOwnerEvidenceResponse response; + boolean unavailable; + try { + Optional retained = + repository.readHistoricalOriginalStartSessionOwnerEvidence(decodedRequest); + unavailable = retained.isEmpty(); + if (unavailable) { + response = null; + } else { + var evidence = retained.orElseThrow(); + unavailable = !decodedRequest.equals(evidence.request()); + response = + unavailable + ? null + : HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toResponse(evidence); + } + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL.withDescription("Historical evidence read failed").asRuntimeException()); + return; + } + + if (unavailable) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact historical StartSession evidence is unavailable") + .asRuntimeException()); + return; + } + + responseObserver.onNext(response); + responseObserver.onCompleted(); } } diff --git a/services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql b/services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql index b6ecb674ee..ba36039e5e 100644 --- a/services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql +++ b/services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql @@ -3,6 +3,10 @@ -- Request storage is the bounded canonical tuple plus 1 KiB closed-request overhead. Response -- storage has a local 8 MiB fail-closed budget and makes no claim about gRPC transport capacity. -- [jooq ignore start] +CREATE UNIQUE INDEX uq_gs_start_session_template_association_pin_binding + ON game_session_start_session_template_association_pin + (target_namespace, control_plane_request_id, owner_attempt_id, owner_fence, canonical_tenant_id); + CREATE TABLE game_session_start_session_launch_descriptor_pin ( target_namespace VARCHAR(63) NOT NULL, control_plane_request_id VARCHAR(128) NOT NULL, @@ -20,9 +24,14 @@ CREATE TABLE game_session_start_session_launch_descriptor_pin ( PRIMARY KEY (target_namespace, control_plane_request_id), CONSTRAINT uq_gs_start_session_launch_descriptor_attempt UNIQUE (owner_attempt_id), CONSTRAINT fk_gs_start_session_launch_descriptor_association - FOREIGN KEY (target_namespace, control_plane_request_id) + FOREIGN KEY ( + target_namespace, + control_plane_request_id, + owner_attempt_id, + owner_fence, + canonical_tenant_id) REFERENCES game_session_start_session_template_association_pin - (target_namespace, control_plane_request_id), + (target_namespace, control_plane_request_id, owner_attempt_id, owner_fence, canonical_tenant_id), CONSTRAINT chk_gs_start_session_launch_descriptor_identity CHECK ( octet_length(target_namespace) BETWEEN 1 AND 63 AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java index 381384c2f7..fd2dad88ed 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java @@ -124,6 +124,36 @@ void pinsCanonicalDescriptorAndExactRepeatReturnsOriginalWireEvidence() { assertThat(fixture.pinCount()).isEqualTo(1); } + @Test + void databaseRejectsDescriptorPinsWithSubstitutedAssociationOwnerTuple() { + Fixture fixture = fixture(); + RetainedAssociation retained = retainAssociation(fixture, "descriptor-pin-owner-tuple"); + var association = retained.association().result(); + var ownerRequest = association.request(); + UUID canonicalTenantId = association.association().canonicalTenantId(); + + assertDescriptorPinRejectedForOwnerTuple( + fixture, + retained, + UUID.randomUUID(), + ownerRequest.ownerAttemptId(), + ownerRequest.ownerFence()); + assertDescriptorPinRejectedForOwnerTuple( + fixture, retained, canonicalTenantId, UUID.randomUUID(), ownerRequest.ownerFence()); + assertDescriptorPinRejectedForOwnerTuple( + fixture, + retained, + canonicalTenantId, + ownerRequest.ownerAttemptId(), + ownerRequest.ownerFence() + 1); + assertThat(fixture.pinCount()).isZero(); + + PinnedLaunchDescriptorSnapshot valid = + fixture.pin(retained.claim(), descriptor(retained, "valid-owner-tuple-descriptor")); + assertThat(fixture.find(retained.claim())).contains(valid); + assertThat(fixture.pinCount()).isOne(); + } + @Test void pinsAClosedApplicationFailureAsTheFinalDescriptorOutcome() { Fixture fixture = fixture(); @@ -410,6 +440,40 @@ private static RetainedAssociation retainAssociation(Fixture fixture, String req return new RetainedAssociation(tuple, claim, fixture.pinAssociation(claim, initial)); } + private static void assertDescriptorPinRejectedForOwnerTuple( + Fixture fixture, + RetainedAssociation retained, + UUID canonicalTenantId, + UUID ownerAttemptId, + long ownerFence) { + assertThatThrownBy( + () -> + fixture.dsl.execute( + "INSERT INTO game_session_start_session_launch_descriptor_pin " + + "(target_namespace, control_plane_request_id, canonical_tenant_id, " + + "owner_attempt_id, owner_fence, association_request_digest, " + + "association_response_digest, descriptor_request_wire, " + + "descriptor_response_wire, descriptor_request_digest, " + + "descriptor_response_digest) " + + "SELECT association.target_namespace, association.control_plane_request_id, " + + "?, ?, ?, association.association_request_digest, " + + "association.association_response_digest, ?, ?, ?, ? " + + "FROM game_session_start_session_template_association_pin association " + + "WHERE association.target_namespace = ? " + + "AND association.control_plane_request_id = ?", + canonicalTenantId, + ownerAttemptId, + ownerFence, + new byte[] {1}, + new byte[] {1}, + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + retained.claim().targetNamespace(), + retained.claim().controlPlaneRequestId())) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("fk_gs_start_session_launch_descriptor_association"); + } + private static boolean continueAndPin( Fixture fixture, RetainedAssociation retained, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java new file mode 100644 index 0000000000..edeb5ae1f7 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java @@ -0,0 +1,604 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.google.protobuf.ByteString; +import io.grpc.CallCredentials; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +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 io.grpc.stub.AbstractStub; +import io.grpc.stub.StreamObserver; +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.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +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.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +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 tools.jackson.databind.json.JsonMapper; + +/** Physical socket proof that redemption reaches only the exact same-namespace Account workload. */ +class StartSessionOperatorRedemptionClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String WRONG_NAMESPACE_URI = "spiffe://firemud/ns/other/sa/account-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String REFERENCE = "A".repeat(43); + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID ACTOR_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID TARGET_OWNER_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("52345678-1234-4234-8234-123456789abc"); + private static final UUID OWNER_MUTATION_ID = + UUID.fromString("62345678-1234-4234-8234-123456789abc"); + private static final UUID CLAIM_OWNER_ID = + UUID.fromString("72345678-1234-4234-8234-123456789abc"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); + private static final UUID CONTROL_UI_JTI = + UUID.fromString("92345678-1234-4234-8234-123456789abc"); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final long RESERVATION_FENCE = 4L; + private static final long OWNER_FENCE = 9L; + private static final long ISSUANCE_FENCE = 23L; + private static final Clock FIXED_CLOCK = + Clock.fixed(Instant.parse("2026-10-09T00:00:00Z"), ZoneOffset.UTC); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir static Path temporaryDirectory; + + private static TestPki pki; + private Server server; + private StartSessionOperatorRedemptionClient client; + private AtomicInteger rpcStarts; + private AtomicInteger applicationCalls; + private AtomicReference receivedPeer; + private AtomicReference receivedRequest; + + @BeforeAll + static void createLocalTestCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void redeemsOverSocketMtlsWithExactSameNamespaceAccountPeer() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(); + startServer(pki.accountServer(), tuple); + client = newClient(server); + client.initialize(); + + var result = client.redeem(tuple, REFERENCE, claim()); + + assertThat(result.gameSessionClaim()).isEqualTo(claim()); + assertThat(result.projection().authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(result.projection().issuanceOperationId()).isEqualTo(ISSUANCE_OPERATION_ID); + assertThat(result.projection().issuanceFence()).isEqualTo(ISSUANCE_FENCE); + assertThat(result.toString()).doesNotContain(REFERENCE); + assertThat(rpcStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + assertThat(receivedPeer.get()) + .isNotNull() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(GAME_SESSION_URI); + assertThat(receivedRequest.get().getOperatorAuthorizationReference()).isEqualTo(REFERENCE); + } + + @Test + void sameCaWrongWorkloadAndWrongNamespaceAccountServersReceiveNoRedemptionRpc() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(); + for (TestIdentity wrongServer : + List.of(pki.wrongWorkloadServer(), pki.wrongNamespaceServer())) { + startServer(wrongServer, tuple); + client = newClient(server); + client.initialize(); + + Throwable failure = catchThrowable(() -> client.redeem(tuple, REFERENCE, claim())); + + assertThat(failure) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + thrown -> + assertThat(((StatusRuntimeException) thrown).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)) + .hasMessageNotContaining(REFERENCE); + assertThat(rpcStarts).hasValue(0); + assertThat(applicationCalls).hasValue(0); + assertThat(receivedRequest.get()).isNull(); + stopTransport(); + } + } + + private void startServer( + TestIdentity serverIdentity, StartSessionPostAuthorizationExecutionTuple tuple) + throws Exception { + rpcStarts = new AtomicInteger(); + applicationCalls = new AtomicInteger(); + receivedPeer = new AtomicReference<>(); + receivedRequest = new AtomicReference<>(); + var service = + new StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceImplBase() { + @Override + public void redeemOperatorAuthorization( + RedeemOperatorAuthorizationRequest request, + StreamObserver observer) { + applicationCalls.incrementAndGet(); + receivedPeer.set(GrpcPeerIdentity.current()); + receivedRequest.set(request); + observer.onNext(response(tuple)); + observer.onCompleted(); + } + }; + ServerInterceptor countRpcStarts = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + rpcStarts.incrementAndGet(); + return next.startCall(call, headers); + } + }; + 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( + service, countRpcStarts, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private StartSessionOperatorRedemptionClient newClient(Server target) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + target.getPort()); + return new StartSessionOperatorRedemptionClient( + endpoints, + pki.clientProperties(temporaryDirectory), + new GrpcChannelFactory(), + customizerThatReplacesCallCredentials(), + NAMESPACE, + FIXED_CLOCK); + } + + private static BlockingGrpcStubCustomizer customizerThatReplacesCallCredentials() { + return new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T stub) { + return stub.withCallCredentials( + new CallCredentials() { + @Override + public void applyRequestMetadata( + RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { + applier.apply(new Metadata()); + } + }); + } + }; + } + + private static RedeemOperatorAuthorizationResponse response( + StartSessionPostAuthorizationExecutionTuple tuple) { + return RedeemOperatorAuthorizationResponse.newBuilder() + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setAuthorityEvidenceBundle(ByteString.copyFrom(tuple.authorityEvidenceBundleBytes())) + .setIssuanceOperationId(ISSUANCE_OPERATION_ID.toString()) + .setIssuanceFence(ISSUANCE_FENCE) + .setReplay(false) + .build(); + } + + private static AttemptClaim claim() { + return new AttemptClaim( + NAMESPACE, + "socket-redemption-request", + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + CLAIM_OWNER_ID, + OWNER_FENCE); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple() { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "socket mTLS redemption peer identity proof"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "socket-redemption-request", ACTOR_ID, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/test/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER_ID, + RESERVATION_FENCE, + authorityEvidenceBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + Long.toString(ISSUANCE_FENCE), + "18446744073709551615")); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = TENANT_ID.toString(); + Map value = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + "2026-10-09T00:00:00Z", + "expiresAt", + "2026-10-10T00:00:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_OPERATION_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", Long.toString(ISSUANCE_FENCE), + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + CONTROL_UI_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException malformed) { + throw new IllegalStateException("could not encode test Account authority bundle", malformed); + } + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity accountServer, + TestIdentity wrongWorkloadServer, + TestIdentity wrongNamespaceServer, + TestIdentity gameSessionClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("redemption-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD redemption client 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("redemption-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-workload-account-server", + WRONG_WORKLOAD_URI, + true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-namespace-account-server", + WRONG_NAMESPACE_URI, + true), + issueIdentity( + directory, caStore, caFile, "game-session-client", GAME_SESSION_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) throws Exception { + Path clientCertificate = + writePem( + directory.resolve("game-session-client.crt"), + "CERTIFICATE", + gameSessionClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-session-client.key"), + "PRIVATE KEY", + gameSessionClient.privateKey().getEncoded()); + Path trustCa = + writePem( + directory.resolve("redemption-client-trust-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(trustCa.toString()); + properties.setPlaintext(false); + return properties; + } + + 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( + (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"); + List 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("keytool timed out"); + } + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (process.exitValue() != 0) { + 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", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java index a70856d0c2..e0f97032bf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java @@ -55,8 +55,6 @@ class StartSessionOperatorRedemptionClientTest { private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); private static final String NAMESPACE = "world-runtime"; private static final String REQUEST_ID = "redemption-client-request"; - private static final String WORKLOAD = - "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); private static final String OPAQUE_REFERENCE = "A".repeat(43); private static final Clock CURRENT_CLOCK = @@ -137,6 +135,23 @@ void rejectsMismatchedClaimAndExpiredAuthorityBeforeCallingAccount() throws Exce verifyNoInteractions(stub); } + @Test + void rejectsTupleAndClaimOutsideConfiguredNamespaceBeforeCallingAccount() { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + StartSessionPostAuthorizationExecutionTuple otherNamespaceTuple = tuple(REQUEST_ID, "other"); + + assertThatThrownBy( + () -> client.redeem(otherNamespaceTuple, OPAQUE_REFERENCE, claim(REQUEST_ID, "other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace") + .hasMessageNotContaining(OPAQUE_REFERENCE); + verifyNoInteractions(stub); + } + @Test void rejectsMalformedMissingUnknownAndSubstitutedAccountProjectionFields() throws Exception { StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); @@ -200,6 +215,7 @@ void refusesPlaintextOrMissingMutualTlsCredentialsAndDoesNotInitializeByConstruc plaintext, mock(GrpcChannelFactory.class), BlockingGrpcStubCustomizer.noop(), + NAMESPACE, CURRENT_CLOCK)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mutual TLS"); @@ -213,6 +229,7 @@ void refusesPlaintextOrMissingMutualTlsCredentialsAndDoesNotInitializeByConstruc missingIdentity, mock(GrpcChannelFactory.class), BlockingGrpcStubCustomizer.noop(), + NAMESPACE, CURRENT_CLOCK)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mutual TLS"); @@ -222,6 +239,18 @@ void refusesPlaintextOrMissingMutualTlsCredentialsAndDoesNotInitializeByConstruc () -> uninitialized.redeem(tuple(REQUEST_ID), OPAQUE_REFERENCE, claim(REQUEST_ID))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("explicitly initialized"); + + assertThatThrownBy( + () -> + new StartSessionOperatorRedemptionClient( + new ServiceEndpointsProperties(), + tlsProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + "Invalid_Namespace", + CURRENT_CLOCK)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); } private static void assertRejected( @@ -254,6 +283,7 @@ private static StartSessionOperatorRedemptionClient newClient( tlsProperties(), mock(GrpcChannelFactory.class), BlockingGrpcStubCustomizer.noop(), + NAMESPACE, clock); if (stub != null) { setStub(client, stub); @@ -285,7 +315,11 @@ private static void setStub( } private static AttemptClaim claim(String requestId) { - return new AttemptClaim(NAMESPACE, requestId, OWNER_ATTEMPT, OWNER_MUTATION, CLAIM_OWNER, 37L); + return claim(requestId, NAMESPACE); + } + + private static AttemptClaim claim(String requestId, String namespace) { + return new AttemptClaim(namespace, requestId, OWNER_ATTEMPT, OWNER_MUTATION, CLAIM_OWNER, 37L); } private static StartSessionPostAuthorizationExecutionTuple tuple(String requestId) { @@ -294,11 +328,21 @@ private static StartSessionPostAuthorizationExecutionTuple tuple(String requestI private static StartSessionPostAuthorizationExecutionTuple tuple( String requestId, String evaluatedAt, String expiresAt) { + return tuple(requestId, evaluatedAt, expiresAt, NAMESPACE); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, String namespace) { + return tuple(requestId, "2026-10-09T00:00:00Z", "2026-10-09T00:05:00Z", namespace); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, String evaluatedAt, String expiresAt, String namespace) { StartSessionOperatorAction action = new StartSessionOperatorAction( StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Scope(TENANT, namespace), new StartSessionOperatorAction.Target(91L, TARGET_OWNER), StartSessionOperatorAction.ExpectedVersion.ABSENT, new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), @@ -307,7 +351,7 @@ private static StartSessionPostAuthorizationExecutionTuple tuple( StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); return StartSessionPostAuthorizationExecutionTuple.createHuman( pre, - WORKLOAD, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", FINGERPRINT, RESERVATION_OWNER, 19L, @@ -336,6 +380,7 @@ private static byte[] bundle( String evaluatedAt, String expiresAt) { String tenantId = TENANT.toString(); + String namespace = tuple.action().scope().targetNamespace(); Map projection = Map.of( "sourceType", @@ -388,7 +433,7 @@ private static byte[] bundle( StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "authorityScope", Map.of( - "scope", Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "scope", Map.of("tenantId", tenantId, "targetNamespace", namespace), "actionFamily", tuple.actionFamily(), "applicableAccountId", ACTOR.toString(), "applicableTenantId", tenantId), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java index 687c4ff3bb..fa7fd4cfa6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java @@ -126,7 +126,10 @@ void missingAndMalformedRetainedResultsFailWithoutSendingAResponse() throws Exce new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService(repository, NAMESPACE); var missing = invokeAs(service, fixture.wireRequest(), WORLD_SERVICE); - assertRejected(missing, Status.Code.FAILED_PRECONDITION); + assertRejected( + missing, + Status.Code.FAILED_PRECONDITION, + "Exact historical StartSession evidence is unavailable"); HistoricalOriginalStartSessionOwnerEvidence.Result malformed = mock(HistoricalOriginalStartSessionOwnerEvidence.Result.class); @@ -134,7 +137,7 @@ void missingAndMalformedRetainedResultsFailWithoutSendingAResponse() throws Exce when(repository.readHistoricalOriginalStartSessionOwnerEvidence(fixture.request())) .thenReturn(Optional.of(malformed)); var corrupt = invokeAs(service, fixture.wireRequest(), WORLD_SERVICE); - assertRejected(corrupt, Status.Code.INTERNAL); + assertRejected(corrupt, Status.Code.INTERNAL, "Historical evidence read failed"); verify(repository, times(2)).readHistoricalOriginalStartSessionOwnerEvidence(fixture.request()); verifyNoMoreInteractions(repository); } @@ -168,7 +171,10 @@ void changedRepositoryResultEchoFailsBeforeResponseEncoding() throws Exception { var observer = invokeAs(service, fixture.wireRequest(), WORLD_SERVICE); - assertRejected(observer, Status.Code.FAILED_PRECONDITION); + assertRejected( + observer, + Status.Code.FAILED_PRECONDITION, + "Exact historical StartSession evidence is unavailable"); verify(repository).readHistoricalOriginalStartSessionOwnerEvidence(fixture.request()); verifyNoMoreInteractions(repository); } @@ -188,8 +194,14 @@ void invalidAndUnknownWireRequestsAreRejectedBeforeRepositoryAccess() throws Exc .build()) .build(); - assertRejected(invokeAs(service, invalid, WORLD_SERVICE), Status.Code.INVALID_ARGUMENT); - assertRejected(invokeAs(service, unknown, WORLD_SERVICE), Status.Code.INVALID_ARGUMENT); + assertRejected( + invokeAs(service, invalid, WORLD_SERVICE), + Status.Code.INVALID_ARGUMENT, + "Historical evidence request is malformed"); + assertRejected( + invokeAs(service, unknown, WORLD_SERVICE), + Status.Code.INVALID_ARGUMENT, + "Historical evidence request is malformed"); verifyNoInteractions(repository); } @@ -201,14 +213,17 @@ void unauthorizedAndEndUserContextsAreRejectedBeforeRepositoryAccess() throws Ex new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService(repository, NAMESPACE); RecordingObserver noPeer = invoke(service, fixture.wireRequest()); - assertRejected(noPeer, Status.Code.PERMISSION_DENIED); + assertRejected( + noPeer, Status.Code.PERMISSION_DENIED, "Historical evidence caller is not authorized"); assertRejected( invokeAs(service, fixture.wireRequest(), NAMESPACE, "entity-management-service"), - Status.Code.PERMISSION_DENIED); + Status.Code.PERMISSION_DENIED, + "Historical evidence caller is not authorized"); assertRejected( invokeAs(service, fixture.wireRequest(), "other", WORLD_SERVICE), - Status.Code.PERMISSION_DENIED); + Status.Code.PERMISSION_DENIED, + "Historical evidence caller is not authorized"); AtomicReference> userResponse = new AtomicReference<>(); @@ -218,10 +233,29 @@ void unauthorizedAndEndUserContextsAreRejectedBeforeRepositoryAccess() throws Ex SessionContext.setContext("42", List.of("tenantAdmin"), Map.of()); userResponse.set(invoke(service, fixture.wireRequest())); }); - assertRejected(userResponse.get(), Status.Code.PERMISSION_DENIED); + assertRejected( + userResponse.get(), + Status.Code.PERMISSION_DENIED, + "Historical evidence caller is not authorized"); verifyNoInteractions(repository); } + @Test + void unexpectedRepositoryStateFailsInternallyWithoutExposingStorageDetails() throws Exception { + Fixture fixture = fixture(); + CanonicalGameInstanceLaunchAssociationRepository repository = mockRepository(); + when(repository.readHistoricalOriginalStartSessionOwnerEvidence(fixture.request())) + .thenThrow(new IllegalStateException("private persisted-row details")); + var service = + new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService(repository, NAMESPACE); + + var observer = invokeAs(service, fixture.wireRequest(), WORLD_SERVICE); + + assertRejected(observer, Status.Code.INTERNAL, "Historical evidence read failed"); + verify(repository).readHistoricalOriginalStartSessionOwnerEvidence(fixture.request()); + verifyNoMoreInteractions(repository); + } + private static Fixture fixture() throws Exception { WorldCanonicalInstanceLifecycleEvidence lifecycle = AuthoringFixtures.lifecycleEvidence("ACTIVE", 1L); @@ -692,6 +726,13 @@ private static void assertRejected(RecordingObserver observer, Status.Code ex assertThat(observer.completed()).isFalse(); } + private static void assertRejected( + RecordingObserver observer, Status.Code expectedCode, String expectedDescription) { + assertRejected(observer, expectedCode); + assertThat(Status.fromThrowable(observer.error()).getDescription()) + .isEqualTo(expectedDescription); + } + private static CanonicalGameInstanceLaunchAssociationRepository mockRepository() { return mock(CanonicalGameInstanceLaunchAssociationRepository.class); } From cbc764baeafbe1b30ba398ba8003faad03349b2f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 18:08:51 +1300 Subject: [PATCH 11/22] fix: repair original-claim owner CI proof and runtime build --- dev-tools/build-compose-service-jars.sh | 9 ++++++++- ...SessionLaunchDescriptorRepositoryIntegrationTest.java | 6 +++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/dev-tools/build-compose-service-jars.sh b/dev-tools/build-compose-service-jars.sh index b5f4c33aba..446dd515ba 100644 --- a/dev-tools/build-compose-service-jars.sh +++ b/dev-tools/build-compose-service-jars.sh @@ -18,4 +18,11 @@ GRADLE_TASKS=( ) echo "Building current boot jars for source-built Docker compose services." -bash "$ROOT_DIR/dev-tools/validation/run-locked-gradle.sh" -PincludeLoadTesting=false "${GRADLE_TASKS[@]}" +# Bound compiler memory for this all-module image build and avoid protobuf task cache-serialization failures. +bash "$ROOT_DIR/dev-tools/validation/run-locked-gradle.sh" \ + --no-configuration-cache \ + --max-workers=1 \ + --no-parallel \ + '-Dorg.gradle.jvmargs=-Xmx2560m -Dfile.encoding=UTF-8' \ + -PincludeLoadTesting=false \ + "${GRADLE_TASKS[@]}" diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java index fd2dad88ed..498d47c7bb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java @@ -150,7 +150,11 @@ void databaseRejectsDescriptorPinsWithSubstitutedAssociationOwnerTuple() { PinnedLaunchDescriptorSnapshot valid = fixture.pin(retained.claim(), descriptor(retained, "valid-owner-tuple-descriptor")); - assertThat(fixture.find(retained.claim())).contains(valid); + PinnedLaunchDescriptorSnapshot read = fixture.find(retained.claim()).orElseThrow(); + assertThat(read.requestWire()).containsExactly(valid.requestWire()); + assertThat(read.responseWire()).containsExactly(valid.responseWire()); + assertThat(read.requestDigest()).isEqualTo(valid.requestDigest()); + assertThat(read.responseDigest()).isEqualTo(valid.responseDigest()); assertThat(fixture.pinCount()).isOne(); } From 146b6e3c47364e91e6065318e6caf427256f4e3e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:43:54 +1300 Subject: [PATCH 12/22] fix(game-session): preserve canonical admission transactions and retry identity --- .../game-session-service/api-contracts.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 2 +- .../player-access-and-session.md | 4 +- .../CreateCanonicalRealmCatalogRequest.java | 18 +- ...nicalInitialAdmissionIntentRepository.java | 47 ++- ...abaseCanonicalInitialAdmissionService.java | 27 +- ...issionIntentRepositoryIntegrationTest.java | 119 ++++++- ...ialAdmissionRepositoryIntegrationTest.java | 63 ++++ ...lInitialAdmissionIntentRepositoryTest.java | 79 ++++- ...RealmCatalogRequestSnapshotBoundsTest.java | 132 ++++++++ ...eCanonicalInitialAdmissionServiceTest.java | 297 +++++++++++++++++- 11 files changed, 759 insertions(+), 31 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CreateCanonicalRealmCatalogRequestSnapshotBoundsTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index ee89c429af..bc02d8a8e7 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,7 +8,7 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -The inactive original-claim preparation is supplied by the prerequisite stage: exact owner repositories, authenticated Account-projection read/pin clients, and descriptor evidence remain unregistered and grant no admission authority. Its fresh-install and explicit V34.3-to-V35/V37/V38 upgrade fixtures retain the original owner rows and validate the installed constraints; physical PostgreSQL execution must be established by the prerequisite’s CI, not inferred from local container skips. +The original-claim preparation is inactive and default-denied: exact owner repositories, authenticated Account-projection read/pin clients, and descriptor evidence remain unregistered and grant no admission authority. Exact-head [CI run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` executed 68 selected physical PostgreSQL tests with zero skips. The 46 launch/owner/history cases included the 12 owner-attempt, 10 association, 12 descriptor, 8 historical-association, 3 coordinator, and 1 run-owned-launch cases; the selected fixtures executed both fresh-schema-to-V39 and the explicit V34.3-to-V39 baseline upgrade. This scoped proof does not activate the preparation or establish the separately required runtime composition, World-backed admission, or historical-owner reconciliation. Regressions added or changed after that exact-head run remain unexecuted until a later physical run. The canonical initial-admission preparation is inactive: the durable pre-hold intent repository and coordinator, exact World hold client, and lifecycle read client are not registered for runtime use. The coordinator commits the immutable intent before the remote hold request, then attaches only the exact World-issued identity in a separate owner transaction; an attached or terminal intent replay is historical evidence, not permission to admit. The hold client can also read a closed same-snapshot hold status and lifecycle over exact workload mTLS, retaining both immutable identity and complete lifecycle-request correlation. A pending snapshot is observational, not continuous protection or commit authority. Genuine deployed owner readback, continuous protection through the pointer/audit commit, and cross-owner terminal reconciliation remain required. The narrower historical original-operation read is described under [restricted original-claim evidence continuation](#restricted-original-claim-evidence-continuation); neither that read nor a lifecycle snapshot supplies those missing guarantees. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 9dde2a0989..0ccac27b9a 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -49,7 +49,7 @@ These links add decision provenance only; they do not upgrade any Game Session i | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation (see [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status)); lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and the opt-in fixture coordinator are wired; general `StartSession` retry integration is not claimed. | `proven` for the front-door and routing seams: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java), [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java), [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java), and [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java); `audited` for the initial-admission sub-boundary: local owner/coordinator tests cover their unit seams, but cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java); [RunOwnedInitialAdmissionFixtureCapability.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [V9 initial-admission owner ledger](../../../services/game-session-service/src/main/resources/db/migration/V9__initial_admission_bind_owner_ledger.sql); [GetInitialAdmissionBindProof](../../../protos/game-session/v1/game_session_service.proto); [InitialAdmissionBindOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java); [InitialAdmissionBindServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [RunOwnedInitialAdmissionFixtureCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java); [RunOwnedInitialAdmissionFixtureCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GrpcGameSessionInitialAdmissionBindProofClientTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java); [InitialAdmissionBindPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; an ambiguous result continues to fence World termination. The API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | +| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation (see [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status)); lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and the opt-in fixture coordinator are wired; the canonical owner service uses explicit owner transactions, and historical original-owner evidence reads remain read-only; general `StartSession` retry integration is not claimed. These owner/history preparations remain inactive and grant no player-admission authority. | `proven` for the front-door and routing seams: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java), [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java), [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java), and [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java); `audited` for the initial-admission sub-boundary: local owner/coordinator and retained-history tests cover unit seams. Exact-head [run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) executed 68 selected PostgreSQL cases with zero skips, including the existing [CanonicalInitialAdmissionRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); that run predates this batch’s direct-construction PostgreSQL regression, which remains physically unrun. The transaction-template unit cases passed the later consolidated local Game Session check; integration sources compiled and static checks passed. Cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [DatabaseCanonicalInitialAdmissionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java); [CanonicalInitialAdmissionIntentRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionStartSessionTemplateAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java); [historical original-owner evidence protobuf](../../../protos/game-session/v1/historical_original_start_session_owner_evidence.proto); [canonical initial-admission owner-proof RPC](../../../protos/game-session/v1/game_session_service.proto); [V28 canonical admission owner and intent ledger](../../../services/game-session-service/src/main/resources/db/migration/V28__canonical_initial_admission_owner_and_intent.sql); [V34.3 request-ID width correction](../../../services/game-session-service/src/main/resources/db/migration/V34.3__canonical_initial_admission_intent_request_id_width.sql); [V35 owner-attempt ledger](../../../services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql); [V37 association pin](../../../services/game-session-service/src/main/resources/db/migration/V37__start_session_template_association_pin.sql); [V38 descriptor pin](../../../services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql); [V39 fresh-scope guard](../../../services/game-session-service/src/main/resources/db/migration/V39__canonical_initial_admission_fresh_scope_guard.sql); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java); [RunOwnedInitialAdmissionFixtureCapability.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [V9 initial-admission owner ledger](../../../services/game-session-service/src/main/resources/db/migration/V9__initial_admission_bind_owner_ledger.sql); [GetInitialAdmissionBindProof](../../../protos/game-session/v1/game_session_service.proto); [InitialAdmissionBindOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java); [InitialAdmissionBindServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [RunOwnedInitialAdmissionFixtureCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java); [RunOwnedInitialAdmissionFixtureCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GrpcGameSessionInitialAdmissionBindProofClientTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java); [InitialAdmissionBindPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java); [DatabaseCanonicalInitialAdmissionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java); [CanonicalInitialAdmissionRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); [CanonicalInitialAdmissionIntentRepositoryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java); [CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java); [CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; an ambiguous result continues to fence World termination. The API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | | `GR-1.2` Tick timelines, action fairness, queues, and scheduling | `partial`: current bounded scheduler, per-entity queue selection, gameplay-command ordering (including timer/automation-origin work only after materialization as gameplay commands with retained provenance/order fields), durable batch/effect staging, pressure signals, and sealed selected-work manifests for gameplay commands are live; directly selected timer/retry/remote-follow-up source-claim manifests remain target-state; it still uses universal work-item selection and does not implement the accepted separate actor-action/passive-effect lane classification, phase budgets, or lane-preserving retry contract; the complete in-place command-status lifecycle accepted by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) is not | `drift-found`: the shipped scheduler and queue/effect seams have focused proof, but lane/source classification, separate lane budgets, and passive/inbound non-actor-turn behavior are not proved; the accepted command-status lifecycle in [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) remains unimplemented and is not fully proved | [ticks](../../architecture/system-architecture-ticks.md); [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | [TickScheduler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [TickServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game-session-service.proto](../../../protos/game-session/v1/game_session_service.proto) | [TickSchedulerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java) | `AS-1.4` timer progress and `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); `GR-1.3` ownership in this tracker | Add the [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) acknowledgement dimensions, authoritative attempt history, bound-tick summary, convergence contract, persistence, and focused proof to `GetGameplayCommandStatus`; separately add TICK-01 source classification, lane/cost metadata, phase budgets, lane-preserving retry identity, and focused actor/passive scheduling proof; adaptive timing and true region-wide scheduling remain separate gaps. | | `GR-1.3` Region leases, fencing, and executor coordination | `partial`: durable runtime ownership, epoch/fence snapshots, pause/resume, stale-owner rejection/requeue, and current runtime-progress publication are live at the game-instance boundary; the TICK-02 Redis lease plus durable executor-fence install/revalidate handshake and true region takeover boundary remain target-state | `proven`: current tests cover fence/scope admission, tick progress, stale execution, and operator reads, but do not prove the TICK-02 lease/fence handshake or takeover reconciliation | [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [RuntimeRegionStatus](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/RuntimeRegionStatus.java); [runtime ownership read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java); [TickRuntimeProgressService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java); [TickRuntimeProgressServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | `GR-1.1` front-end routing in this tracker; `AS-1.1` ingress and `AS-1.4` timers in [Automation runtime tracker](./automation-and-scheduler-runtime.md); Redis lease coordination is the shared infrastructure handoff | The current durable owner row and lease boundary are game-instance scoped. Add proof for Redis lease acquisition/loss before and after durable fence installation, same-token revalidation, stale-fence rejection, and takeover reconciliation; true region-partitioned leases, cluster scheduling, and front-end forwarding remain unimplemented. | | `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, remote result reconciliation, and bounded restart/reset paths are live; startup recovery re-enqueues old accepted-but-unstaged commands under their existing identity and leaves them `ACCEPTED` when Redis, identity, eligibility, or a raced transition prevents safe materialization; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `drift-found`: focused unit recovery tests cover accepted-row re-drive, unchanged retryable state on uncertainty, serializer-free identity/payload-idempotent queue/pending behavior, remote reconciliation, and retryability on Redis/eligibility races, but do not provide combined PostgreSQL/real-Redis restart proof, lane/cost preservation, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake; the real-Redis serializer integration test is present but skipped when Docker is unavailable | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | 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 ef2bed7295..45465dbe18 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,9 +14,9 @@ This inactive owner continuation may read or replay the exact immutable associat Previously recorded focused local unit and transport evidence includes the [authorization coordinator test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java), [continuation service test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java), [redemption client test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java), and [mTLS redemption client test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java). The implementation anchors are [authorization coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java), [owner attempt repository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java), [template association repository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java), and [descriptor continuation service](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java), with schema support in [V35](../../../services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql), [V37](../../../services/game-session-service/src/main/resources/db/migration/V37__start_session_template_association_pin.sql), and [V38](../../../services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql). -Integration sources cover fresh schema, explicit V34.3-to-V35/V37/V38 baseline upgrade, original-claim and reference expiry while writes wait on PostgreSQL locks, and the coordinator boundary: [owner attempt repository integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java), [template association repository integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java), [launch descriptor repository integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java), and [authorization coordinator integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java). On `f23871f6c4`, [CI run 38034433313](https://github.com/benhook1013/FireMUD/actions/runs/38034433313) retained JUnit artifact `11664250444`: its PostgreSQL 18 owner-attempt suite executed 12 cases and its association suite eight, with zero failures or skips, including the explicit V34.3 baseline upgrade and blocked association-insert expiry regression. The descriptor suite executed 12 cases without skips but failed three expiry regressions because two helper calls passed `Boolean.class` as a SQL binding. The narrow helper correction is present; replacement exact-head physical CI remains required, and the failed descriptor regressions are not counted as passing proof. Earlier JaCoCo-only artifacts remain insufficient to attribute individual fixtures. +Integration sources cover fresh schema, explicit V34.3 baseline upgrade, original-claim and reference expiry while writes wait on PostgreSQL locks, and the coordinator boundary: [owner attempt repository integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java), [template association repository integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java), [launch descriptor repository integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java), and [authorization coordinator integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java). The earlier [CI run 38034433313](https://github.com/benhook1013/FireMUD/actions/runs/38034433313) on `f23871f6c4` is historical partial evidence: its owner-attempt and association suites passed, while three descriptor expiry regressions failed and are not counted. The later exact-head [CI run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` executed 68 selected physical PostgreSQL tests with zero skips: 46 launch/owner/history cases (owner attempt 12, association 10, descriptor 12, historical association 8, coordinator 3, run-owned launch 1), 16 admission/pointer cases (intent 4, bind 1, pointer migration 8, CAS 2, request-ID migration 1), and 6 command-history cases. The selected artifacts include fresh-schema-to-V39 and `v34_3BaselineUpgradePreservesLegitimateEvidenceAndCreatesContinuationConstraints` V34.3-to-V39 execution. This closes the physical-proof gap only for those exact source fixtures; regressions added or changed after that run remain unexecuted until a later physical run. -The original-claim preparation prerequisite is separated from the dependent launch/admission/history boundary without changing the composed production implementation. Its classes remain unregistered and default-denied. The extended repository fixture covers an explicit V34.3 baseline upgrade through V35/V37/V38 with retained original-owner evidence and validated constraints; focused local checks pass, but physical PostgreSQL execution remains a prerequisite CI obligation rather than a local Docker proof. +The restricted original-claim continuation remains inactive and default-denied: its owner repositories, typed Account read/pin clients, and descriptor evidence producer remain unregistered, do not alter the composed production implementation, and authorize neither mutation nor player admission. Exact-head [CI run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) provides physical PostgreSQL evidence for the selected existing owner/history fixtures, including fresh-schema-to-V39 and V34.3-to-V39 upgrade paths; it does not prove runtime registration, World-backed admission, historical-owner reconciliation, or playable closure. The later consolidated local Game Session check passed the new unit regressions and compiled the integration sources; new or changed PostgreSQL regressions still require physical execution. The latest inactive hold client reads the exact immutable identity, actual hold status and full lifecycle snapshot over workload mTLS. Common authored fixtures are shared rather than duplicated. The original STARTING association read carries the full stored post-authorization tuple and actual owner attempt/fence, but still requires an unexpired pending claim; it is not an after-expiry association endpoint. The composed local gate passed in 1m59s: 287 Common and 2,010 Game Session unit definitions had zero failures (17 Game Session skips); integration definitions executed 18 and skipped 200, while cross-service definitions executed one and skipped 38. Cached task outputs are included. Physical Game Session job `114071452179` on `c79103014c1b991f4caaa3f1fef04652ec1adda8` failed 21 of 218 integration cases: 20 shared fixture timestamp violations and one fresh source-bound tenant guard rejecting a canonical pointer insert. Replacement physical proof remains required after the corrections. Hold snapshots and retained tuples do not supply continuous commit authority. The authenticated historical original-owner evidence producer is implemented locally but remains unregistered and undeployed; live hold validation, continuous protection through the pointer/audit commit, and cross-owner terminal reconciliation remain incomplete. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java index 8bee96d53e..817388dd87 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java @@ -9,6 +9,7 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; import org.springframework.lang.Nullable; /** Explicit input for one immutable public-production realm catalog creation. */ @@ -40,15 +41,17 @@ public record CreateCanonicalRealmCatalogRequest( throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); } Objects.requireNonNull(realmSlug, "realmSlug"); - if (realmSlug.isBlank() || strictUtf8(realmSlug, "realmSlug").length > 120) { - throw new IllegalArgumentException( - "realmSlug must be a nonblank selector of at most 120 UTF-8 bytes"); + strictUtf8(realmSlug, "realmSlug"); + if (!RealmEntryPolicy.isCanonicalSlug(realmSlug)) { + throw new IllegalArgumentException("realmSlug must be a canonical lower-case slug"); } Objects.requireNonNull(realmDisplayName, "realmDisplayName"); if (realmDisplayName.isBlank() + || !realmDisplayName.equals(realmDisplayName.trim()) || realmDisplayName.codePointCount(0, realmDisplayName.length()) > 100 || strictUtf8(realmDisplayName, "realmDisplayName").length > 400) { - throw new IllegalArgumentException("realmDisplayName must be bounded and nonblank"); + throw new IllegalArgumentException( + "realmDisplayName must be nonblank, trimmed, and within the catalog text bounds"); } if (!visible || !publicProduction) { throw new IllegalArgumentException( @@ -59,11 +62,12 @@ public record CreateCanonicalRealmCatalogRequest( } Objects.requireNonNull(characterCreationPolicy, "characterCreationPolicy"); if (characterCreationPolicy.isBlank() - || characterCreationPolicy.codePointCount(0, characterCreationPolicy.length()) > 64 - || strictUtf8(characterCreationPolicy, "characterCreationPolicy").length > 256) { + || !characterCreationPolicy.equals(characterCreationPolicy.trim()) + || characterCreationPolicy.length() > 32) { throw new IllegalArgumentException( - "characterCreationPolicy must be an explicit bounded nonblank owner value"); + "characterCreationPolicy must be nonblank, trimmed, and at most 32 characters"); } + strictUtf8(characterCreationPolicy, "characterCreationPolicy"); if (playtestLifecycleId != null || playtestStateGeneration != null) { throw new IllegalArgumentException( "Initial public-production creation cannot carry private/playtest lifecycle evidence"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java index 2339c99167..3208bbcbd4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java @@ -19,9 +19,6 @@ import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.exception.DataAccessException; -import org.springframework.transaction.annotation.Isolation; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; /** Durable Game Session intent persisted before an initial-admission request reaches World. */ @@ -44,7 +41,6 @@ public CanonicalInitialAdmissionIntentRepository( } /** Locks both Game Session owner sources and commits exact World request bytes before acquire. */ - @Transactional(isolation = Isolation.READ_COMMITTED) public CanonicalInitialAdmissionIntentSnapshot reserve( Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { Objects.requireNonNull(holdRequest, "holdRequest"); @@ -91,7 +87,6 @@ public CanonicalInitialAdmissionIntentSnapshot reserve( } /** Attaches only World-issued acquisition identity to an already committed exact intent. */ - @Transactional(isolation = Isolation.READ_COMMITTED) public CanonicalInitialAdmissionIntentSnapshot attach( Request exactHoldRequest, HoldIdentity holdIdentity) { Objects.requireNonNull(exactHoldRequest, "exactHoldRequest"); @@ -168,7 +163,6 @@ public CanonicalInitialAdmissionIntentSnapshot attach( } /** Returns one committed immutable intent readback, without asserting live World hold state. */ - @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) public Optional read( String targetNamespace, String initialAdmissionRequestId) { requireSelector(targetNamespace, initialAdmissionRequestId); @@ -384,12 +378,51 @@ private static void requireExactRetry( SourceBinding currentSource) { if (!Arrays.equals(snapshot.holdRequest().canonicalRequestBytes(), expectedHoldBytes) || !Arrays.equals(snapshot.lifecycleRequest().canonicalBytes(), expectedLifecycleBytes) - || !snapshot.sourceBinding().equals(currentSource)) { + || !matchesRetainedSourceBinding(snapshot.sourceBinding(), currentSource)) { throw conflict( "Initial-admission retry differs from its retained request or locked owner source binding"); } } + /** Checks immutable source equality while allowing only a monotonic live runtime-row advance. */ + public static boolean matchesRetainedSourceBinding( + SourceBinding retained, SourceBinding current) { + Objects.requireNonNull(retained, "retained"); + Objects.requireNonNull(current, "current"); + return current.currentRowVersion() >= retained.currentRowVersion() + && current.capturedStartingRowVersion() == retained.capturedStartingRowVersion() + && retained.equals(withCurrentRowVersion(current, retained.currentRowVersion())); + } + + private static SourceBinding withCurrentRowVersion(SourceBinding source, long rowVersion) { + return new SourceBinding( + source.targetNamespace(), + source.canonicalTenantId(), + source.worldSlug(), + source.realmId(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.catalogVisible(), + source.catalogPublicProduction(), + source.catalogRevision(), + source.catalogCreationRequestId(), + source.catalogRequestDigest(), + source.catalogReceiptDigest(), + source.tenantAssociationOperationId(), + source.gameSessionTenantId(), + source.canonicalGameInstanceId(), + source.gameInstanceId(), + source.canonicalVersionId(), + source.runtimeVersionId(), + source.controlPlaneRequestId(), + source.launchDescriptorId(), + source.capturedStartingRowVersion(), + rowVersion, + source.descriptorRequestDigest(), + source.descriptorResultDigest(), + source.releaseAttestationDigest()); + } + private static byte[] boundedRequestBytes(byte[] bytes, String label) { Objects.requireNonNull(bytes, label + " bytes"); if (bytes.length == 0 || bytes.length > REQUEST_BYTES_LIMIT) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java index 6ee3caee75..421f2ea4d5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java @@ -9,32 +9,43 @@ import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.PreparedExpectedClosed; import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionService; import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; /** - * Durable owner operation; remote World proof is acquired before entering its short SQL - * transaction. + * Durable owner operation. Reservation and terminal mutation use short owner transactions; remote + * World proof and owner readbacks run between them outside SQL. */ public final class DatabaseCanonicalInitialAdmissionService implements CanonicalInitialAdmissionService { private final CanonicalInitialAdmissionRepository repository; private final GameSessionCanonicalAdmissionPointerRepository pointerRepository; private final CanonicalInitialAdmissionWorldVerifier worldVerifier; + private final TransactionTemplate ownerWriteTransaction; public DatabaseCanonicalInitialAdmissionService( CanonicalInitialAdmissionRepository repository, GameSessionCanonicalAdmissionPointerRepository pointerRepository, - CanonicalInitialAdmissionWorldVerifier worldVerifier) { + CanonicalInitialAdmissionWorldVerifier worldVerifier, + PlatformTransactionManager transactionManager) { this.repository = Objects.requireNonNull(repository, "repository"); this.pointerRepository = Objects.requireNonNull(pointerRepository, "pointerRepository"); this.worldVerifier = Objects.requireNonNull(worldVerifier, "worldVerifier"); + this.ownerWriteTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + this.ownerWriteTransaction.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerWriteTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerWriteTransaction.setReadOnly(false); } @Override public CanonicalInitialAdmissionOwnerProof bind(CanonicalInitialAdmissionRequest request) { requireNoAmbientTransaction(); Objects.requireNonNull(request, "request"); - repository.reserve(request); + ownerWriteTransaction.executeWithoutResult(status -> repository.reserve(request)); CanonicalInitialAdmissionOwnerProof beforeRemote = requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); if (beforeRemote.outcome() != CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { @@ -49,7 +60,8 @@ public CanonicalInitialAdmissionOwnerProof bind(CanonicalInitialAdmissionRequest throw new IllegalStateException("World initial-admission verifier returned no owner proof"); } worldProof.requireMatches(request); - repository.commit(request, worldProof, preparedOrigin); + ownerWriteTransaction.executeWithoutResult( + status -> repository.commit(request, worldProof, preparedOrigin)); CanonicalInitialAdmissionOwnerProof result = requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); @@ -66,14 +78,15 @@ public CanonicalInitialAdmissionOwnerProof abort( CanonicalInitialAdmissionRequest request, String reason) { requireNoAmbientTransaction(); Objects.requireNonNull(request, "request"); - repository.reserve(request); + ownerWriteTransaction.executeWithoutResult(status -> repository.reserve(request)); CanonicalInitialAdmissionOwnerProof beforeAbort = requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); if (beforeAbort.outcome() != CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { return beforeAbort; } PreparedExpectedClosed preparedOrigin = prepareExpectedClosed(request); - repository.abort(request, preparedOrigin, reason); + ownerWriteTransaction.executeWithoutResult( + status -> repository.abort(request, preparedOrigin, reason)); return requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java index a08cc78b97..6d50e069d6 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java @@ -111,9 +111,20 @@ void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() { target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) .contains(reserved); + harness.transactions.execute( + status -> { + harness.dsl.execute( + "UPDATE game_instances SET row_version = row_version + 1 " + + "WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + return null; + }); CanonicalInitialAdmissionIntentSnapshot retry = harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); assertThat(retry).isEqualTo(reserved); + assertThat(retry.sourceBinding().currentRowVersion()) + .isEqualTo(reserved.sourceBinding().currentRowVersion()); var changedLifecycle = target.lifecycleRequest(uuid(413)); assertThatThrownBy( @@ -152,6 +163,8 @@ void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() { assertThat(attached.state()) .isEqualTo(CanonicalInitialAdmissionIntentSnapshot.IntentState.HOLD_ATTACHED); assertThat(attached.holdIdentity()).isEqualTo(identity); + assertThat(attached.sourceBinding().currentRowVersion()) + .isEqualTo(reserved.sourceBinding().currentRowVersion()); CanonicalInitialAdmissionIntentSnapshot attachedReplay = harness.transactions.execute(status -> target.intents().attach(request, identity)); assertThat(attachedReplay).isEqualTo(attached); @@ -290,7 +303,7 @@ private static void assertPendingIntentVisibleFromSeparateConnection( } @Test - void rollbackLeavesNoIntentAndChangedRuntimeVersionBlocksAttachment() { + void rollbackLeavesNoIntentAndRowVersionRegressionBlocksRetry() { Harness harness = harness(); try { OwnerTarget target = harness.seed(); @@ -310,6 +323,15 @@ void rollbackLeavesNoIntentAndChangedRuntimeVersionBlocksAttachment() { .isEmpty(); assertNoAdmissionMutation(harness.dsl); + harness.transactions.execute( + status -> { + harness.dsl.execute( + "UPDATE game_instances SET row_version = row_version + 1 " + + "WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + return null; + }); CanonicalInitialAdmissionIntentSnapshot reserved = harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); harness.transactions.execute( @@ -321,10 +343,31 @@ void rollbackLeavesNoIntentAndChangedRuntimeVersionBlocksAttachment() { target.gameInstanceId()); return null; }); + CanonicalInitialAdmissionIntentSnapshot monotonicRetry = + harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); + assertThat(monotonicRetry).isEqualTo(reserved); + assertThat(monotonicRetry.sourceBinding().currentRowVersion()) + .isEqualTo(reserved.sourceBinding().currentRowVersion()); + + harness.transactions.execute( + status -> { + harness.dsl.execute( + "UPDATE game_instances SET row_version = ? WHERE tenant_id = ? AND id = ?", + reserved.sourceBinding().currentRowVersion() - 1, + target.gameSessionTenantId(), + target.gameInstanceId()); + return null; + }); var identity = new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( request, uuid(421), uuid(422)); + assertThatThrownBy( + () -> + harness.transactions.execute( + status -> target.intents().reserve(request, lifecycle))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("retained request or locked owner source binding"); assertThatThrownBy( () -> harness.transactions.execute( @@ -340,6 +383,71 @@ void rollbackLeavesNoIntentAndChangedRuntimeVersionBlocksAttachment() { } } + @Test + void retryRejectsRuntimeVersionDescriptorAndCatalogChanges() { + assertRuntimeSourceMutationRejected( + "UPDATE game_instances SET version_id = version_id + 1, " + + "row_version = row_version + 1 WHERE tenant_id = ? AND id = ?"); + assertRuntimeSourceMutationRejected( + "UPDATE game_instances SET launch_descriptor_id = launch_descriptor_id || '-changed', " + + "row_version = row_version + 1 WHERE tenant_id = ? AND id = ?"); + + Harness harness = harness(); + try { + OwnerTarget target = harness.seed(); + var request = holdRequest(target, "intent-catalog-change"); + var lifecycle = target.lifecycleRequest(uuid(423)); + CanonicalInitialAdmissionIntentSnapshot reserved = + harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); + var changedCatalogRequest = + holdRequest( + target, request.initialAdmissionRequestId(), target.catalog().catalogRevision() + 1); + + assertThatThrownBy( + () -> + harness.transactions.execute( + status -> target.intents().reserve(changedCatalogRequest, lifecycle))) + .isInstanceOf( + GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException.class) + .hasMessageContaining("missing or stale"); + assertThat( + target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) + .contains(reserved); + assertNoAdmissionMutation(harness.dsl); + } finally { + harness.close(); + } + } + + private static void assertRuntimeSourceMutationRejected(String updateSql) { + Harness harness = harness(); + try { + OwnerTarget target = harness.seed(); + var request = holdRequest(target, "intent-runtime-source-change"); + var lifecycle = target.lifecycleRequest(uuid(424)); + CanonicalInitialAdmissionIntentSnapshot reserved = + harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); + harness.transactions.execute( + status -> { + harness.dsl.execute(updateSql, target.gameSessionTenantId(), target.gameInstanceId()); + return null; + }); + + assertThatThrownBy( + () -> + harness.transactions.execute( + status -> target.intents().reserve(request, lifecycle))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("complete launch binding"); + assertThat( + target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) + .contains(reserved); + assertNoAdmissionMutation(harness.dsl); + } finally { + harness.close(); + } + } + @Test void competingRequestsSerializeOnTheCatalogAndOnlyOneIntentWins() throws Exception { Harness harness = harness(); @@ -397,6 +505,11 @@ private static boolean raceReserve( private static WorldCanonicalInitialAdmissionHold.Request holdRequest( OwnerTarget target, String requestId) { + return holdRequest(target, requestId, target.catalog().catalogRevision()); + } + + private static WorldCanonicalInitialAdmissionHold.Request holdRequest( + OwnerTarget target, String requestId, long expectedCatalogRevision) { long activeEpoch = 2L; var launch = target.launch().association(); UUID canonicalVersionId = target.launch().canonicalVersionId(); @@ -411,7 +524,7 @@ private static WorldCanonicalInitialAdmissionHold.Request holdRequest( launch.gameInstanceUuid(), canonicalVersionId, activeEpoch, - target.catalog().catalogRevision(), + expectedCatalogRevision, CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, null, requestId); @@ -428,7 +541,7 @@ private static WorldCanonicalInitialAdmissionHold.Request holdRequest( requestId, requestDigest, WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, - target.catalog().catalogRevision(), + expectedCatalogRevision, null); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index 99de8fdb19..3a126350f6 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -34,8 +34,10 @@ import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; +import net.firedevops.firemud.gamesession.service.impl.DatabaseCanonicalInitialAdmissionService; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -46,6 +48,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -427,6 +430,64 @@ void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { .isZero(); } + @Test + void directlyConstructedOwnerServiceRunsMutationsInExplicitPostgresTransactions() { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest preparationRequest = + preparationRequest(source, catalog); + AuthoredWorldLaunchDescriptorClient syntheticGameDesign = + syntheticGameDesignClient(preparationRequest, catalog, source); + GameSessionCanonicalLaunchPreparationService preparationService = + new GameSessionCanonicalLaunchPreparationService( + syntheticGameDesign, + fixture.catalogRepository, + fixture.sourceRepository, + fixture.preparationRepository, + fixture.transactionManager, + NAMESPACE); + CanonicalLaunchPreparationSnapshot preparation = preparationService.prepare(preparationRequest); + CompleteLaunchBindingEvidence completeBinding = + preparationService.readCompleteBinding(preparation); + fixture.createTestOnlyFreshMappingAndRunningLaunch(source, completeBinding); + CanonicalInitialAdmissionRequest request = initialAdmissionRequest(catalog, completeBinding); + CanonicalInitialAdmissionWorldProof worldProof = testWorldProof(request); + CanonicalInitialAdmissionWorldVerifier worldVerifier = + mock(CanonicalInitialAdmissionWorldVerifier.class); + when(worldVerifier.verify(request)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return worldProof; + }); + DatabaseCanonicalInitialAdmissionService service = + new DatabaseCanonicalInitialAdmissionService( + fixture.initialAdmissionRepository, + fixture.pointerRepository, + worldVerifier, + fixture.transactionManager); + + CanonicalInitialAdmissionOwnerProof committed = service.bind(request); + + assertThat(committed.outcome()) + .isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(committed.committedPointerVersion()).isEqualTo(1L); + assertThat(committed.auditEventId()).isPositive(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) + .isEqualTo(1); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_admission_pointer_event")), + DSL.field(DSL.name("initial_admission_request_id"), String.class) + .eq(request.initialAdmissionRequestId()))) + .isEqualTo(1); + } + @Test void exactDefinitivelyAbortedAttemptCannotBeReopenedByRetry() { Fixture fixture = fixture(); @@ -558,6 +619,7 @@ private Fixture fixture() { sourceRepository, catalogRepository, preparationRepository, + pointerRepository, launchRepository, initialAdmissionRepository); } @@ -789,6 +851,7 @@ private record Fixture( GameSessionAuthoredWorldSourceRepository sourceRepository, GameSessionCanonicalRealmCatalogRepository catalogRepository, GameSessionCanonicalLaunchPreparationRepository preparationRepository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, CanonicalGameInstanceLaunchAssociationRepository launchRepository, CanonicalInitialAdmissionRepository initialAdmissionRepository) { IntakeReceipt registerSource() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java index b579516f27..64fbccd3a4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java @@ -1,13 +1,16 @@ package unit.net.firedevops.firemud.gamesession.repository; +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.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot.SourceBinding; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; @@ -53,7 +56,12 @@ void mutationRequiresWritableOwnerTransactionBeforeOwnerReads() { var launch = mock(CanonicalGameInstanceLaunchAssociationRepository.class); var repository = new CanonicalInitialAdmissionIntentRepository(dsl, catalog, launch); - assertThatThrownBy(() -> repository.reserve(holdRequest("request-1"), lifecycleRequest())) + WorldCanonicalInitialAdmissionHold.Request request = holdRequest("request-1"); + assertThatThrownBy(() -> repository.reserve(request, lifecycleRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + assertThatThrownBy( + () -> repository.attach(request, new HoldIdentity(request, uuid(7), uuid(8)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable owner transaction"); @@ -75,6 +83,40 @@ void readRejectsAnAmbientTransactionBeforeQueryingTheIntentLedger() { verifyNoInteractions(dsl, catalog, launch); } + @Test + void retryBindingAllowsOnlyMonotonicRuntimeRowVersionChanges() { + SourceBinding retained = sourceBinding(1, 72, "descriptor-1", 1, 5, SHA256); + + assertThat( + CanonicalInitialAdmissionIntentRepository.matchesRetainedSourceBinding( + retained, sourceBinding(1, 72, "descriptor-1", 1, 8, SHA256))) + .isTrue(); + assertThat( + CanonicalInitialAdmissionIntentRepository.matchesRetainedSourceBinding( + retained, sourceBinding(1, 72, "descriptor-1", 1, 4, SHA256))) + .isFalse(); + assertThat( + CanonicalInitialAdmissionIntentRepository.matchesRetainedSourceBinding( + retained, sourceBinding(1, 73, "descriptor-1", 1, 8, SHA256))) + .isFalse(); + assertThat( + CanonicalInitialAdmissionIntentRepository.matchesRetainedSourceBinding( + retained, sourceBinding(1, 72, "descriptor-2", 1, 8, SHA256))) + .isFalse(); + assertThat( + CanonicalInitialAdmissionIntentRepository.matchesRetainedSourceBinding( + retained, sourceBinding(2, 72, "descriptor-1", 1, 8, SHA256))) + .isFalse(); + assertThat( + CanonicalInitialAdmissionIntentRepository.matchesRetainedSourceBinding( + retained, sourceBinding(1, 72, "descriptor-1", 2, 8, SHA256))) + .isFalse(); + assertThat( + CanonicalInitialAdmissionIntentRepository.matchesRetainedSourceBinding( + retained, sourceBinding(1, 72, "descriptor-1", 1, 8, "sha256:" + "b".repeat(64)))) + .isFalse(); + } + private static WorldCanonicalInitialAdmissionHold.Request holdRequest(String requestId) { String requestDigest = CanonicalInitialAdmissionRequest.computeRequestDigest( @@ -126,6 +168,41 @@ private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( SHA256); } + private static SourceBinding sourceBinding( + long catalogRevision, + long runtimeVersionId, + String launchDescriptorId, + long capturedStartingRowVersion, + long currentRowVersion, + String descriptorResultDigest) { + return new SourceBinding( + NAMESPACE, + TENANT, + "world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + true, + true, + catalogRevision, + uuid(8), + SHA256, + SHA256, + uuid(9), + 10, + INSTANCE, + 11, + VERSION, + runtimeVersionId, + "control-request-1", + launchDescriptorId, + capturedStartingRowVersion, + currentRowVersion, + SHA256, + descriptorResultDigest, + SHA256); + } + private static UUID uuid(int value) { return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CreateCanonicalRealmCatalogRequestSnapshotBoundsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CreateCanonicalRealmCatalogRequestSnapshotBoundsTest.java new file mode 100644 index 0000000000..cb315999a1 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CreateCanonicalRealmCatalogRequestSnapshotBoundsTest.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import org.junit.jupiter.api.Test; + +class CreateCanonicalRealmCatalogRequestSnapshotBoundsTest { + @Test + void rejectsRealmSlugsThatAreNotCanonicalSelectors() { + assertThatThrownBy(() -> request("Production", "Production", "ALLOW_NEW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical lower-case slug"); + assertThatThrownBy(() -> request("production_realm", "Production", "ALLOW_NEW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical lower-case slug"); + } + + @Test + void rejectsTextOutsideCurrentOpenSnapshotBounds() { + assertThatThrownBy(() -> request("production", " Production", "ALLOW_NEW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("realmDisplayName"); + assertThatThrownBy(() -> request("production", "Production ", "ALLOW_NEW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("realmDisplayName"); + assertThatThrownBy(() -> request("production", " ", "ALLOW_NEW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("realmDisplayName"); + assertThatThrownBy(() -> request("production", "Production", " ALLOW_NEW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("characterCreationPolicy"); + assertThatThrownBy(() -> request("production", "Production", "ALLOW_NEW ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("characterCreationPolicy"); + assertThatThrownBy(() -> request("production", "Production", " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("characterCreationPolicy"); + assertThatThrownBy(() -> request("production", "Production", "P".repeat(33))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("at most 32 characters"); + } + + @Test + void acceptsCanonicalMaximumValuesThatTheOpenSnapshotCanRead() { + String maxDisplayName = "\uD83D\uDE00".repeat(100); + CreateCanonicalRealmCatalogRequest request = + request("a".repeat(64), maxDisplayName, "P".repeat(32)); + + assertThat(maxDisplayName.codePointCount(0, maxDisplayName.length())).isEqualTo(100); + assertThat(maxDisplayName.length()).isEqualTo(200); + assertThat(maxDisplayName.getBytes(StandardCharsets.UTF_8)).hasSize(400); + assertThat(CanonicalCurrentOpenPointerSnapshotDigest.digest(projection(request))).hasSize(64); + + String overCodePointLimit = "界".repeat(101); + assertThatThrownBy(() -> request("a".repeat(64), overCodePointLimit, "P".repeat(32))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("realmDisplayName"); + } + + @Test + void rejectsMalformedUtf8Text() { + String malformed = "bad\uD800"; + + assertThatThrownBy(() -> request("production", malformed, "ALLOW_NEW")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy(() -> request("production", "Production", malformed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, String realmDisplayName, String characterCreationPolicy) { + return new CreateCanonicalRealmCatalogRequest( + UUID.randomUUID(), + "gameplay", + UUID.randomUUID(), + UUID.randomUUID(), + realmSlug, + realmDisplayName, + true, + true, + "SHARED", + characterCreationPolicy, + null, + null); + } + + private static CanonicalCurrentOpenPointerSnapshotDigest.Projection projection( + CreateCanonicalRealmCatalogRequest request) { + return new CanonicalCurrentOpenPointerSnapshotDigest.Projection( + 3, + request.targetNamespace(), + request.canonicalTenantId(), + "world", + "World", + UUID.randomUUID(), + request.realmSlug(), + request.realmDisplayName(), + UUID.randomUUID(), + request.stateScope(), + 1L, + 1L, + "OPEN", + request.visible(), + request.publicProduction(), + null, + request.characterCreationPolicy(), + UUID.randomUUID(), + UUID.randomUUID(), + "initial-request", + "a".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + 1L, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "b".repeat(64), + "game-session-canonical-initial-admission", + "World-held initial admission", + null, + "sha256:" + "c".repeat(64), + 1L, + Instant.parse("2026-10-07T00:00:00Z")); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java index 7bc86fd9c5..1a2d6f589d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java @@ -2,23 +2,32 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doAnswer; 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 java.time.Instant; +import java.util.ArrayList; +import java.util.List; import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; import org.springframework.transaction.support.TransactionSynchronizationManager; class DatabaseCanonicalInitialAdmissionServiceTest { @@ -28,14 +37,151 @@ class DatabaseCanonicalInitialAdmissionServiceTest { mock(GameSessionCanonicalAdmissionPointerRepository.class); private final CanonicalInitialAdmissionWorldVerifier worldVerifier = mock(CanonicalInitialAdmissionWorldVerifier.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(0); + private int readbackCount; private final DatabaseCanonicalInitialAdmissionService service = - new DatabaseCanonicalInitialAdmissionService(repository, pointerRepository, worldVerifier); + new DatabaseCanonicalInitialAdmissionService( + repository, pointerRepository, worldVerifier, transactionManager); @AfterEach void clearTransaction() { TransactionSynchronizationManager.clear(); } + @Test + void bindUsesWritableReadCommittedTransactionsAndKeepsRemoteAndReadbackOutside() { + CanonicalInitialAdmissionRequest request = request(); + CanonicalInitialAdmissionOwnerProof pending = pendingProof(request); + CanonicalInitialAdmissionOwnerProof committed = committedProof(request); + CanonicalInitialAdmissionWorldProof worldProof = worldProof(request); + + doAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + return null; + }) + .when(repository) + .reserve(request); + doAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + return null; + }) + .when(repository) + .commit(request, worldProof, null); + when(repository.read(request.targetNamespace(), request.initialAdmissionRequestId())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(); + return Optional.of(readbackCount++ == 0 ? pending : committed); + }); + when(worldVerifier.verify(request)) + .thenAnswer( + invocation -> { + assertOutsideTransaction(); + return worldProof; + }); + + assertThat(service.bind(request)).isEqualTo(committed); + + verify(repository).reserve(request); + verify(repository).commit(request, worldProof, null); + verify(repository, times(2)) + .read(request.targetNamespace(), request.initialAdmissionRequestId()); + verify(worldVerifier).verify(request); + verifyNoInteractions(pointerRepository); + assertThat(transactionManager.settings) + .containsExactly(writableReadCommittedRequiresNew(), writableReadCommittedRequiresNew()); + assertThat(transactionManager.commitCount).isEqualTo(2); + assertThat(transactionManager.rollbackCount).isZero(); + } + + @Test + void abortUsesWritableReadCommittedTransactionsAndReadsTerminalProofAfterCommit() { + CanonicalInitialAdmissionRequest request = request(); + CanonicalInitialAdmissionOwnerProof pending = pendingProof(request); + CanonicalInitialAdmissionOwnerProof aborted = abortedProof(request); + + doAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + return null; + }) + .when(repository) + .reserve(request); + doAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + return null; + }) + .when(repository) + .abort(request, null, "test abort"); + when(repository.read(request.targetNamespace(), request.initialAdmissionRequestId())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(); + return Optional.of(readbackCount++ == 0 ? pending : aborted); + }); + + assertThat(service.abort(request, "test abort")).isEqualTo(aborted); + + verify(repository).reserve(request); + verify(repository).abort(request, null, "test abort"); + verify(repository, times(2)) + .read(request.targetNamespace(), request.initialAdmissionRequestId()); + verifyNoInteractions(pointerRepository, worldVerifier); + assertThat(transactionManager.settings) + .containsExactly(writableReadCommittedRequiresNew(), writableReadCommittedRequiresNew()); + assertThat(transactionManager.commitCount).isEqualTo(2); + assertThat(transactionManager.rollbackCount).isZero(); + } + + @Test + void bindDoesNotReturnSuccessWhenOwnerCommitFails() { + transactionManager.failOnCommitNumber = 2; + CanonicalInitialAdmissionRequest request = request(); + CanonicalInitialAdmissionOwnerProof pending = pendingProof(request); + CanonicalInitialAdmissionWorldProof worldProof = worldProof(request); + + doAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + return null; + }) + .when(repository) + .reserve(request); + doAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + return null; + }) + .when(repository) + .commit(request, worldProof, null); + when(repository.read(request.targetNamespace(), request.initialAdmissionRequestId())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(); + return Optional.of(pending); + }); + when(worldVerifier.verify(request)) + .thenAnswer( + invocation -> { + assertOutsideTransaction(); + return worldProof; + }); + + assertThatThrownBy(() -> service.bind(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("simulated transaction commit failure"); + + verify(repository).reserve(request); + verify(repository).commit(request, worldProof, null); + verify(repository, times(1)) + .read(request.targetNamespace(), request.initialAdmissionRequestId()); + verify(worldVerifier).verify(request); + assertThat(transactionManager.commitCount).isEqualTo(2); + } + @Test void bindRejectsWritableAmbientTransactionBeforeAnyCollaboratorAccess() { assertAmbientTransactionRejected(false, () -> service.bind(request())); @@ -61,13 +207,18 @@ void committedReplayReturnsStoredOwnerProofWithoutWorldVerification() { CanonicalInitialAdmissionRequest request = request(); CanonicalInitialAdmissionOwnerProof committed = committedProof(request); when(repository.read(request.targetNamespace(), request.initialAdmissionRequestId())) - .thenReturn(Optional.of(committed)); + .thenAnswer( + invocation -> { + assertOutsideTransaction(); + return Optional.of(committed); + }); assertThat(service.bind(request)).isEqualTo(committed); verify(repository).reserve(request); verify(repository).read(request.targetNamespace(), request.initialAdmissionRequestId()); verifyNoInteractions(pointerRepository, worldVerifier); + assertThat(transactionManager.settings).containsExactly(writableReadCommittedRequiresNew()); } private void assertAmbientTransactionRejected(boolean readOnly, Runnable operation) { @@ -79,6 +230,26 @@ private void assertAmbientTransactionRejected(boolean readOnly, Runnable operati .hasMessageContaining("ambient transaction"); verifyNoInteractions(repository, pointerRepository, worldVerifier); + assertThat(transactionManager.settings).isEmpty(); + } + + private static void assertWritableReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static void assertOutsideTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static TransactionSettings writableReadCommittedRequiresNew() { + return new TransactionSettings( + TransactionDefinition.PROPAGATION_REQUIRES_NEW, + TransactionDefinition.ISOLATION_READ_COMMITTED, + false); } private static CanonicalInitialAdmissionRequest request() { @@ -130,6 +301,34 @@ private static CanonicalInitialAdmissionRequest request() { "sha256:" + "a".repeat(64)); } + private static CanonicalInitialAdmissionOwnerProof pendingProof( + CanonicalInitialAdmissionRequest request) { + return new CanonicalInitialAdmissionOwnerProof( + Outcome.PENDING, + request.initialAdmissionRequestId(), + request.requestDigest(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + request.activeLifecycleEpoch(), + request.expectedCatalogRevision(), + request.originKind(), + request.expectedPriorPointerVersion(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest(), + null, + null, + null, + false, + null); + } + private static CanonicalInitialAdmissionOwnerProof committedProof( CanonicalInitialAdmissionRequest request) { return new CanonicalInitialAdmissionOwnerProof( @@ -158,7 +357,101 @@ private static CanonicalInitialAdmissionOwnerProof committedProof( Instant.parse("2026-10-10T00:00:00Z")); } + private static CanonicalInitialAdmissionOwnerProof abortedProof( + CanonicalInitialAdmissionRequest request) { + return new CanonicalInitialAdmissionOwnerProof( + Outcome.ABORTED, + request.initialAdmissionRequestId(), + request.requestDigest(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + request.activeLifecycleEpoch(), + request.expectedCatalogRevision(), + request.originKind(), + request.expectedPriorPointerVersion(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest(), + null, + null, + "sha256:" + "c".repeat(64), + true, + Instant.parse("2026-10-10T00:00:00Z")); + } + + private static CanonicalInitialAdmissionWorldProof worldProof( + CanonicalInitialAdmissionRequest request) { + return new CanonicalInitialAdmissionWorldProof( + request.initialAdmissionRequestId(), + request.requestDigest(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + "ACTIVE", + request.activeLifecycleEpoch(), + request.originKind(), + request.expectedCatalogRevision(), + request.expectedPriorPointerVersion(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest()); + } + private static UUID uuid(String value) { return UUID.fromString(value); } + + private record TransactionSettings(int propagation, int isolation, boolean readOnly) {} + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private final List settings = new ArrayList<>(); + private int commitCount; + private int rollbackCount; + private int failOnCommitNumber; + + private RecordingTransactionManager(int failOnCommitNumber) { + this.failOnCommitNumber = failOnCommitNumber; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + settings.add( + new TransactionSettings( + definition.getPropagationBehavior(), + definition.getIsolationLevel(), + definition.isReadOnly())); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commitCount++; + TransactionSynchronizationManager.clear(); + if (commitCount == failOnCommitNumber) { + throw new IllegalStateException("simulated transaction commit failure"); + } + } + + @Override + public void rollback(TransactionStatus status) { + rollbackCount++; + TransactionSynchronizationManager.clear(); + } + } } From 141a7136c95f5bc235f93e93b3860bdf0a274480 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:01:34 +1300 Subject: [PATCH 13/22] test(game-session): assert source mismatch before deferred commit guard --- ...issionIntentRepositoryIntegrationTest.java | 32 +++++++++++++++---- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java index 6d50e069d6..f4e082cb1c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java @@ -427,18 +427,38 @@ private static void assertRuntimeSourceMutationRejected(String updateSql) { var lifecycle = target.lifecycleRequest(uuid(424)); CanonicalInitialAdmissionIntentSnapshot reserved = harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); - harness.transactions.execute( - status -> { - harness.dsl.execute(updateSql, target.gameSessionTenantId(), target.gameInstanceId()); - return null; - }); + Record originalRuntimeSource = + Objects.requireNonNull( + harness.dsl.fetchOne( + "SELECT version_id, launch_descriptor_id, row_version FROM game_instances " + + "WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())); assertThatThrownBy( () -> harness.transactions.execute( - status -> target.intents().reserve(request, lifecycle))) + status -> { + harness.dsl.execute( + updateSql, target.gameSessionTenantId(), target.gameInstanceId()); + target.intents().reserve(request, lifecycle); + return null; + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("complete launch binding"); + Record runtimeSourceAfterRollback = + Objects.requireNonNull( + harness.dsl.fetchOne( + "SELECT version_id, launch_descriptor_id, row_version FROM game_instances " + + "WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())); + assertThat(runtimeSourceAfterRollback.get("version_id", Long.class)) + .isEqualTo(originalRuntimeSource.get("version_id", Long.class)); + assertThat(runtimeSourceAfterRollback.get("launch_descriptor_id", String.class)) + .isEqualTo(originalRuntimeSource.get("launch_descriptor_id", String.class)); + assertThat(runtimeSourceAfterRollback.get("row_version", Long.class)) + .isEqualTo(originalRuntimeSource.get("row_version", Long.class)); assertThat( target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) .contains(reserved); From efcd23e428393e71d10eb406838cee030d283cf6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:44:53 +1300 Subject: [PATCH 14/22] Fix canonical admission reservation and owner-read review findings --- .../game-session-service/api-contracts.md | 4 +- ...e-session-runtime-and-tick-coordination.md | 4 +- .../player-access-and-session.md | 2 +- .../v1/game_session_service.proto | 12 +- .../CanonicalInitialAdmissionRepository.java | 32 ++- ...onCanonicalAdmissionPointerRepository.java | 68 +++++ ...lInitialAdmissionOwnerReadGrpcService.java | 5 +- ...nitialAdmissionOwnerReadWorkloadGuard.java | 7 +- ...ialAdmissionRepositoryIntegrationTest.java | 235 +++++++++++++++++- ...nonicalInitialAdmissionRepositoryTest.java | 30 +++ ...tialAdmissionOwnerReadGrpcServiceTest.java | 24 +- ...eCanonicalInitialAdmissionServiceTest.java | 3 +- 12 files changed, 401 insertions(+), 25 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index bc02d8a8e7..2704db9cea 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,9 +8,9 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -The original-claim preparation is inactive and default-denied: exact owner repositories, authenticated Account-projection read/pin clients, and descriptor evidence remain unregistered and grant no admission authority. Exact-head [CI run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` executed 68 selected physical PostgreSQL tests with zero skips. The 46 launch/owner/history cases included the 12 owner-attempt, 10 association, 12 descriptor, 8 historical-association, 3 coordinator, and 1 run-owned-launch cases; the selected fixtures executed both fresh-schema-to-V39 and the explicit V34.3-to-V39 baseline upgrade. This scoped proof does not activate the preparation or establish the separately required runtime composition, World-backed admission, or historical-owner reconciliation. Regressions added or changed after that exact-head run remain unexecuted until a later physical run. +The original-claim preparation remains inactive and default-denied: the exact owner repositories, authenticated Account-projection read/pin clients, and descriptor evidence are not registered for runtime admission. Earlier exact-head [Validation run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` executed 68 selected physical PostgreSQL cases with zero skips, including fresh-schema-to-V39 and the explicit V34.3-to-V39 baseline upgrade. The later exact-head [Validation run 38046952247](https://github.com/benhook1013/FireMUD/actions/runs/38046952247) on `141a7136c95f5bc235f93e93b3860bdf0a274480` completed the Game Session suites with 2,051 unit, 232 integration, and 39 cross-service cases; all 2,322 cases passed with zero skips, including the current descriptor, association, owner-attempt, and initial-admission migrations/readback cases. These are code and database test results, not runtime activation: production composition, World-backed playable admission, continuous owner authority through commit, and historical-owner reconciliation remain unproved. -The canonical initial-admission preparation is inactive: the durable pre-hold intent repository and coordinator, exact World hold client, and lifecycle read client are not registered for runtime use. The coordinator commits the immutable intent before the remote hold request, then attaches only the exact World-issued identity in a separate owner transaction; an attached or terminal intent replay is historical evidence, not permission to admit. The hold client can also read a closed same-snapshot hold status and lifecycle over exact workload mTLS, retaining both immutable identity and complete lifecycle-request correlation. A pending snapshot is observational, not continuous protection or commit authority. Genuine deployed owner readback, continuous protection through the pointer/audit commit, and cross-owner terminal reconciliation remain required. The narrower historical original-operation read is described under [restricted original-claim evidence continuation](#restricted-original-claim-evidence-continuation); neither that read nor a lifecycle snapshot supplies those missing guarantees. +The canonical initial-admission preparation remains inactive: its durable pre-hold intent repository/coordinator, exact World hold client, lifecycle read client, and method-specific Game Session owner-proof read are wired locally but are not registered for runtime admission. The coordinator commits immutable intent before requesting the World hold and attaches only the exact World-issued identity in a separate owner transaction. The same-namespace World-only proof RPC returns a point-in-time `PENDING` snapshot or a terminal outcome backed by a positive committed pointer and matching audit, or a durable `ABORTED` result; it does not acquire or renew a lease. The hold client reads the exact hold status and lifecycle snapshot over workload mTLS and preserves request correlation. Neither snapshot provides continuous protection through the pointer/audit commit or cross-owner terminal reconciliation. The narrower historical original-operation read is described under [restricted original-claim evidence continuation](#restricted-original-claim-evidence-continuation); neither read establishes those missing guarantees. `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` currently fail closed at their authenticated internal receiving boundary with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable`, before command, coordinator, follow-up, or queue mutation. The retained lower-level admission implementation does not prove the cross-service Automation admission-epoch fence required by [ADR 0106](../../decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md). A separate receiver-fence successor must durably serialize installation against receiving admission, preserve exact retry outcomes, and prove that a handoff whose intent committed before an Automation pause cannot create live work under the displaced admission epoch afterward. This gate preserves ordinary gameplay APIs and does not claim the successor implemented. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 0ccac27b9a..9d63d3a8d2 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for Game Session runtime and tick This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. -Local Game Session producer code now includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads, plus an unregistered World-only initial-admission owner read bound to the configured namespace and full hold tuple. The latter reports only a nonterminal `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Consolidated Common and Game Session checks passed locally on 2026-10-10, including the producer authorization, correlation, retained-evidence, and terminal-outcome unit tests; the new PostgreSQL integration cases compiled but require execution in container-enabled CI. Neither endpoint is deployed, and their existence does not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. +Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads and an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple. The latter returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38046952247](https://github.com/benhook1013/FireMUD/actions/runs/38046952247) on `141a7136c95f5bc235f93e93b3860bdf0a274480` executed 2,051 unit, 232 integration, and 39 cross-service Game Session cases with zero skips or failures, including the owner-proof RPC and PostgreSQL-backed owner/descriptor/association cases. The prior [Validation run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` is earlier-head evidence for 68 selected physical PostgreSQL cases with zero skips. Neither endpoint is deployed; these results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. Gameplay-session context remains on the implementation-local `sessionctx:*` keys and per-instance binding identity. The target authenticated `session:game:{tenantGameplayTag}:...` family, persisted tenant-tag allocation, and namespace-qualified controller uniqueness are not implemented or end-to-end proved; the canonical tenancy and focused-isolation requirements remain in [Multi-Tenancy](../../architecture/system-architecture-multi-tenancy.md#data-separation-per-service). @@ -49,7 +49,7 @@ These links add decision provenance only; they do not upgrade any Game Session i | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation (see [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status)); lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and the opt-in fixture coordinator are wired; the canonical owner service uses explicit owner transactions, and historical original-owner evidence reads remain read-only; general `StartSession` retry integration is not claimed. These owner/history preparations remain inactive and grant no player-admission authority. | `proven` for the front-door and routing seams: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java), [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java), [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java), and [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java); `audited` for the initial-admission sub-boundary: local owner/coordinator and retained-history tests cover unit seams. Exact-head [run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) executed 68 selected PostgreSQL cases with zero skips, including the existing [CanonicalInitialAdmissionRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); that run predates this batch’s direct-construction PostgreSQL regression, which remains physically unrun. The transaction-template unit cases passed the later consolidated local Game Session check; integration sources compiled and static checks passed. Cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [DatabaseCanonicalInitialAdmissionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java); [CanonicalInitialAdmissionIntentRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionStartSessionTemplateAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java); [historical original-owner evidence protobuf](../../../protos/game-session/v1/historical_original_start_session_owner_evidence.proto); [canonical initial-admission owner-proof RPC](../../../protos/game-session/v1/game_session_service.proto); [V28 canonical admission owner and intent ledger](../../../services/game-session-service/src/main/resources/db/migration/V28__canonical_initial_admission_owner_and_intent.sql); [V34.3 request-ID width correction](../../../services/game-session-service/src/main/resources/db/migration/V34.3__canonical_initial_admission_intent_request_id_width.sql); [V35 owner-attempt ledger](../../../services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql); [V37 association pin](../../../services/game-session-service/src/main/resources/db/migration/V37__start_session_template_association_pin.sql); [V38 descriptor pin](../../../services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql); [V39 fresh-scope guard](../../../services/game-session-service/src/main/resources/db/migration/V39__canonical_initial_admission_fresh_scope_guard.sql); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java); [RunOwnedInitialAdmissionFixtureCapability.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [V9 initial-admission owner ledger](../../../services/game-session-service/src/main/resources/db/migration/V9__initial_admission_bind_owner_ledger.sql); [GetInitialAdmissionBindProof](../../../protos/game-session/v1/game_session_service.proto); [InitialAdmissionBindOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java); [InitialAdmissionBindServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [RunOwnedInitialAdmissionFixtureCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java); [RunOwnedInitialAdmissionFixtureCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GrpcGameSessionInitialAdmissionBindProofClientTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java); [InitialAdmissionBindPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java); [DatabaseCanonicalInitialAdmissionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java); [CanonicalInitialAdmissionRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); [CanonicalInitialAdmissionIntentRepositoryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java); [CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java); [CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; an ambiguous result continues to fence World termination. The API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | +| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation, and lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and opt-in fixture coordination are wired locally. Historical original-owner evidence reads are read-only. These preparations remain inactive and grant no player-admission authority; general `StartSession` retry integration is not claimed. | `proven` for front-door routing through the existing WebSocket, normalization, and gRPC tests. The owner-proof producer is covered by [CanonicalInitialAdmissionOwnerReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java), with same-namespace caller checks in [CanonicalInitialAdmissionOwnerReadWorkloadGuard](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java); durable owner behavior is covered by [DatabaseCanonicalInitialAdmissionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java) and [CanonicalInitialAdmissionRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java). Exact-head [Validation run 38046952247](https://github.com/benhook1013/FireMUD/actions/runs/38046952247) on `141a7136c95f5bc235f93e93b3860bdf0a274480` executed 2,051 unit, 232 integration, and 39 cross-service cases with zero skips or failures. Earlier [run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) is prior-head evidence for 68 selected physical PostgreSQL cases with zero skips. Cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [DatabaseCanonicalInitialAdmissionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java); [CanonicalInitialAdmissionIntentRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java); [CanonicalInitialAdmissionOwnerReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java); [CanonicalInitialAdmissionOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java); [canonical initial-admission owner-proof RPC](../../../protos/game-session/v1/game_session_service.proto); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java) | [CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [DatabaseCanonicalInitialAdmissionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java); [CanonicalInitialAdmissionRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); [CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java); [CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; ambiguous outcomes continue to fence World termination. The owner boundary is game-instance scoped and does not implement independently partitioned-region forwarding. | | `GR-1.2` Tick timelines, action fairness, queues, and scheduling | `partial`: current bounded scheduler, per-entity queue selection, gameplay-command ordering (including timer/automation-origin work only after materialization as gameplay commands with retained provenance/order fields), durable batch/effect staging, pressure signals, and sealed selected-work manifests for gameplay commands are live; directly selected timer/retry/remote-follow-up source-claim manifests remain target-state; it still uses universal work-item selection and does not implement the accepted separate actor-action/passive-effect lane classification, phase budgets, or lane-preserving retry contract; the complete in-place command-status lifecycle accepted by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) is not | `drift-found`: the shipped scheduler and queue/effect seams have focused proof, but lane/source classification, separate lane budgets, and passive/inbound non-actor-turn behavior are not proved; the accepted command-status lifecycle in [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) remains unimplemented and is not fully proved | [ticks](../../architecture/system-architecture-ticks.md); [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | [TickScheduler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [TickServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game-session-service.proto](../../../protos/game-session/v1/game_session_service.proto) | [TickSchedulerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java) | `AS-1.4` timer progress and `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); `GR-1.3` ownership in this tracker | Add the [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) acknowledgement dimensions, authoritative attempt history, bound-tick summary, convergence contract, persistence, and focused proof to `GetGameplayCommandStatus`; separately add TICK-01 source classification, lane/cost metadata, phase budgets, lane-preserving retry identity, and focused actor/passive scheduling proof; adaptive timing and true region-wide scheduling remain separate gaps. | | `GR-1.3` Region leases, fencing, and executor coordination | `partial`: durable runtime ownership, epoch/fence snapshots, pause/resume, stale-owner rejection/requeue, and current runtime-progress publication are live at the game-instance boundary; the TICK-02 Redis lease plus durable executor-fence install/revalidate handshake and true region takeover boundary remain target-state | `proven`: current tests cover fence/scope admission, tick progress, stale execution, and operator reads, but do not prove the TICK-02 lease/fence handshake or takeover reconciliation | [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [RuntimeRegionStatus](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/RuntimeRegionStatus.java); [runtime ownership read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java); [TickRuntimeProgressService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java); [TickRuntimeProgressServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | `GR-1.1` front-end routing in this tracker; `AS-1.1` ingress and `AS-1.4` timers in [Automation runtime tracker](./automation-and-scheduler-runtime.md); Redis lease coordination is the shared infrastructure handoff | The current durable owner row and lease boundary are game-instance scoped. Add proof for Redis lease acquisition/loss before and after durable fence installation, same-token revalidation, stale-fence rejection, and takeover reconciliation; true region-partitioned leases, cluster scheduling, and front-end forwarding remain unimplemented. | | `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, remote result reconciliation, and bounded restart/reset paths are live; startup recovery re-enqueues old accepted-but-unstaged commands under their existing identity and leaves them `ACCEPTED` when Redis, identity, eligibility, or a raced transition prevents safe materialization; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `drift-found`: focused unit recovery tests cover accepted-row re-drive, unchanged retryable state on uncertainty, serializer-free identity/payload-idempotent queue/pending behavior, remote reconciliation, and retryability on Redis/eligibility races, but do not provide combined PostgreSQL/real-Redis restart proof, lane/cost preservation, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake; the real-Redis serializer integration test is present but skipped when Docker is unavailable | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | 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 45465dbe18..f07989c9a8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -77,7 +77,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. The finite namespace controller-index migration-driver source and packaging prefix have focused source/protocol, packaging, resource-integrity, and static image-contract evidence, but do not prove namespace-aware atomic takeover. The V34.3 PostgreSQL fixture is unrun; physical PostgreSQL and Redis execution, final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Namespace-aware binding and [SESSION-02 atomic transfer](../../architecture/system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) remain incomplete; issuer-index and region reconciliation plus retained-binding inventory/conversion remain open. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head [Validation run 38046952247](https://github.com/benhook1013/FireMUD/actions/runs/38046952247) executed 2,051 unit, 232 integration, and 39 cross-service Game Session cases with zero skips or failures; the V34.3 PostgreSQL fixture ran one case successfully. This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 32ffea91b5..36af762c63 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -42,10 +42,6 @@ service GameSessionControlPlaneService { // Read exact durable owner proof for a World-owned initial-admission hold. rpc GetInitialAdmissionBindProof(GetInitialAdmissionBindProofRequest) returns (GetInitialAdmissionBindProofResponse); - // Read the exact canonical Game Session-owned initial-admission terminal outcome for World. - rpc GetCanonicalInitialAdmissionOwnerProof( - GetCanonicalInitialAdmissionOwnerProofRequest) - returns (GetCanonicalInitialAdmissionOwnerProofResponse); rpc ValidateBuiltInCommandAlias(ValidateBuiltInCommandAliasRequest) returns (ValidateBuiltInCommandAliasResponse); rpc ListAdmissionPointers(ListAdmissionPointersRequest) @@ -92,6 +88,14 @@ service GameSessionControlPlaneService { returns (PurgeQueuedTickCommandsForPluginVersionResponse); } +// Dedicated World-only read surface for canonical initial-admission owner proof. +service CanonicalInitialAdmissionOwnerProofReadService { + // Read the exact canonical Game Session-owned initial-admission terminal outcome for World. + rpc GetCanonicalInitialAdmissionOwnerProof( + GetCanonicalInitialAdmissionOwnerProofRequest) + returns (GetCanonicalInitialAdmissionOwnerProofResponse); +} + message StartSessionRequest { string tenant_id = 1; string game_template_id = 2; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java index 3442966f06..91320e5472 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java @@ -102,6 +102,10 @@ public void reserve(CanonicalInitialAdmissionRequest request) { requireSameRequestIdentity(existing, request); return; } + if (existing == null + && request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + lockAllAdmissionRepresentationsForNoPrior(); + } CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); CanonicalInitialAdmissionLaunchTarget launchTarget = lockLaunchTarget(request, existing == null); @@ -117,6 +121,24 @@ public void reserve(CanonicalInitialAdmissionRequest request) { "Another initial-admission request already owns the pending realm attempt"); } + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + pointerRepository.requireNoAdmissionPointerRepresentations( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.worldSlug(), + catalog.realmSlug(), + launchTarget.association().gameSessionTenantId(), + launchTarget.gameInstanceId()); + } else { + pointerRepository.lockExpectedClosedForRealm( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.expectedPriorPointerVersion(), + request.expectedCatalogRevision()); + } + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); int inserted = dsl.execute( @@ -687,8 +709,10 @@ private void verifyCommittedReadback(Attempt attempt) { || attempt.gameSessionTenantId() != evidence.get("audit_game_session_tenant_id", Long.class) || attempt.gameInstanceId() != evidence.get("game_instance_id", Long.class) || attempt.gameInstanceId() != evidence.get("audit_game_instance_id", Long.class) - || attempt.pointerVersion() != evidence.get("pointer_version", Long.class) - || attempt.pointerVersion() != evidence.get("audit_pointer_version", Long.class) + || !pointerVersionMatches( + attempt.pointerVersion(), evidence.get("pointer_version", Long.class)) + || !pointerVersionMatches( + attempt.pointerVersion(), evidence.get("audit_pointer_version", Long.class)) || attempt.expectedCatalogRevision() != evidence.get("catalog_revision", Long.class) || attempt.expectedCatalogRevision() != evidence.get("audit_catalog_revision", Long.class) || !"OPEN".equals(evidence.get("admission_state", String.class)) @@ -820,6 +844,10 @@ private void verifyOriginalClosedOrigin(Attempt attempt, boolean requireCurrent) } } + static boolean pointerVersionMatches(Long attemptVersion, Long storedVersion) { + return Objects.equals(attemptVersion, storedVersion); + } + private boolean hasAttemptPointerEvidence(Attempt attempt) { Record exists = dsl.fetchOne( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java index 1d62abf2e4..59058cc4f2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java @@ -404,6 +404,74 @@ public ExpectedClosedEvidence lockExpectedClosed(PreparedExpectedClosed prepared return new ExpectedClosedEvidence(lockedOrigin); } + /** + * Resolves and locks the exact current original CLOSED origin in the caller's writable owner + * transaction, without relying on a separate committed-read preparation transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ExpectedClosedEvidence lockExpectedClosedForRealm( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + long expectedPointerVersion, + long expectedCatalogRevision) { + requireReadSelector(targetNamespace, canonicalTenantId); + requireReadSelector(targetNamespace, realmId); + requirePositive(expectedPointerVersion, "expectedPointerVersion"); + requirePositive(expectedCatalogRevision, "expectedCatalogRevision"); + requireWritableOwnerTransaction(); + + var outcomes = + dsl.fetch( + "SELECT request_id FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "ORDER BY request_id LIMIT 2", + targetNamespace, + canonicalTenantId, + realmId); + if (outcomes.size() != 1) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Realm does not have one exact original canonical CLOSED request outcome"); + } + UUID originalRequestId = required(outcomes.getFirst(), "request_id", UUID.class); + Record outcome = findRequest(targetNamespace, originalRequestId); + if (outcome == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED request outcome is missing"); + } + CreateCanonicalClosedAdmissionPointerRequest originRequest = requestFromOutcome(outcome); + if (!targetNamespace.equals(originRequest.targetNamespace()) + || !canonicalTenantId.equals(originRequest.canonicalTenantId()) + || !realmId.equals(originRequest.realmId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED request does not match the requested realm"); + } + + CanonicalRealmCatalogSnapshot lockedCatalog = + catalogRepository.lockExactInitialPublicProduction( + targetNamespace, + canonicalTenantId, + realmId, + originRequest.catalogCreationRequestId(), + expectedCatalogRevision); + Record lockedPointer = lockCanonicalPointer(originRequest); + if (lockedPointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED pointer row is missing"); + } + Record lockedOutcome = findRequest(targetNamespace, originalRequestId); + if (lockedOutcome == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED request outcome is missing"); + } + + CanonicalClosedAdmissionPointerSnapshot lockedOrigin = + verifyOrigin( + targetNamespace, originalRequestId, lockedOutcome, lockedCatalog, lockedPointer); + requireExpectedVersions(lockedOrigin, expectedPointerVersion, expectedCatalogRevision); + return new ExpectedClosedEvidence(lockedOrigin); + } + /** Reads and verifies the immutable request outcome from committed owner rows. */ @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) public Optional readByRequest( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java index ddbeb11d97..537e9a9012 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java @@ -12,7 +12,7 @@ import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionReconciliationRequiredException; -import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOwnerProofReadServiceGrpc; import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofResponse; @@ -23,7 +23,8 @@ * remains valid through a later transaction owned by another service. */ public final class CanonicalInitialAdmissionOwnerReadGrpcService - extends GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceImplBase { + extends CanonicalInitialAdmissionOwnerProofReadServiceGrpc + .CanonicalInitialAdmissionOwnerProofReadServiceImplBase { private final CanonicalInitialAdmissionRepository repository; private final CanonicalInitialAdmissionOwnerReadWorkloadGuard workloadGuard; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java index 668891e3c6..345829eb03 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java @@ -3,7 +3,7 @@ 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.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOwnerProofReadServiceGrpc; /** Exact same-namespace World workload authorization for canonical owner proof readback. */ public final class CanonicalInitialAdmissionOwnerReadWorkloadGuard { @@ -16,9 +16,10 @@ public CanonicalInitialAdmissionOwnerReadWorkloadGuard(String trustedNamespace) public void requireWorldManagementOwnerReadCaller() { GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); - if (!"game_session.v1.GameSessionControlPlaneService/GetCanonicalInitialAdmissionOwnerProof" + if (!"game_session.v1.CanonicalInitialAdmissionOwnerProofReadService/GetCanonicalInitialAdmissionOwnerProof" .equals( - GameSessionControlPlaneServiceGrpc.getGetCanonicalInitialAdmissionOwnerProofMethod() + CanonicalInitialAdmissionOwnerProofReadServiceGrpc + .getGetCanonicalInitialAdmissionOwnerProofMethod() .getFullMethodName()) || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) || peerIdentity == null diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index 3a126350f6..be7673ce79 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -24,6 +24,7 @@ import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalClosedAdmissionPointerRequest; import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; @@ -116,6 +117,19 @@ void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { fixture.initialAdmissionRepository.reserve(request); return null; }); + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(request); + return null; + }); + assertThat( + fixture.initialAdmissionRepository.read(NAMESPACE, request.initialAdmissionRequestId())) + .map(CanonicalInitialAdmissionOwnerProof::outcome) + .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) + .isEqualTo(1); CanonicalInitialAdmissionWorldProof changedProof = new CanonicalInitialAdmissionWorldProof( @@ -430,6 +444,159 @@ void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { .isZero(); } + @Test + void newNoPriorPointerReservationRejectsAnAlreadyOpenRealmWithoutLeavingPendingAttempt() { + Fixture fixture = fixture(); + PreparedAdmission preparedAdmission = prepareAdmission(fixture); + CanonicalRealmCatalogSnapshot catalog = preparedAdmission.catalog(); + CompleteLaunchBindingEvidence binding = preparedAdmission.binding(); + CanonicalInitialAdmissionRequest firstRequest = initialAdmissionRequest(catalog, binding); + + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(firstRequest); + return null; + }); + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.commit( + firstRequest, testWorldProof(firstRequest), null); + return null; + }); + assertThat( + fixture.initialAdmissionRepository.read( + NAMESPACE, firstRequest.initialAdmissionRequestId())) + .map(CanonicalInitialAdmissionOwnerProof::outcome) + .contains(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + + CanonicalInitialAdmissionRequest staleRequest = + initialAdmissionRequest( + catalog, + binding, + "canonical-stale-no-prior-" + catalog.realmId(), + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + uuid(117), + uuid(118)); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(staleRequest); + return null; + })) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository.CanonicalClosedPointerConflictException + .class) + .hasMessageContaining("already names this target"); + + assertNoAttemptAndNoPending(fixture, staleRequest); + } + + @Test + void expectedClosedReservationRequiresExactCurrentOriginalClosedEvidence() { + Fixture fixture = fixture(); + PreparedAdmission preparedAdmission = prepareAdmission(fixture); + CanonicalRealmCatalogSnapshot catalog = preparedAdmission.catalog(); + CompleteLaunchBindingEvidence binding = preparedAdmission.binding(); + CreateCanonicalClosedAdmissionPointerRequest closeRequest = + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(115), + NAMESPACE, + TENANT, + catalog.realmId(), + CATALOG_REQUEST, + catalog.catalogRevision(), + "canonical-initial-admission-test", + "Create exact CLOSED origin"); + var preparedClosed = fixture.pointerRepository.prepareInitialClosed(closeRequest); + fixture.transactions.execute( + status -> { + fixture.pointerRepository.createInitialClosed(preparedClosed); + return null; + }); + + CanonicalInitialAdmissionRequest unsupportedPriorVersion = + initialAdmissionRequest( + catalog, + binding, + "canonical-expected-closed-v129-" + catalog.realmId(), + CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED, + 129L, + uuid(119), + uuid(120)); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(unsupportedPriorVersion); + return null; + })) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("versions do not match"); + assertNoAttemptAndNoPending(fixture, unsupportedPriorVersion); + + CanonicalInitialAdmissionRequest firstOpenRequest = + initialAdmissionRequest( + catalog, + binding, + "canonical-expected-closed-v1-" + catalog.realmId(), + CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED, + 1L, + uuid(121), + uuid(122)); + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(firstOpenRequest); + return null; + }); + assertThat( + fixture.initialAdmissionRepository.read( + NAMESPACE, firstOpenRequest.initialAdmissionRequestId())) + .map(CanonicalInitialAdmissionOwnerProof::outcome) + .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + var preparedExpectedClosed = + fixture.pointerRepository.prepareExpectedClosedForRealm( + NAMESPACE, TENANT, catalog.realmId(), 1L, catalog.catalogRevision()); + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.commit( + firstOpenRequest, testWorldProof(firstOpenRequest), preparedExpectedClosed); + return null; + }); + CanonicalInitialAdmissionOwnerProof committed = + fixture + .initialAdmissionRepository + .read(NAMESPACE, firstOpenRequest.initialAdmissionRequestId()) + .orElseThrow(); + assertThat(committed.provesCommit()).isTrue(); + assertThat(committed.committedPointerVersion()).isEqualTo(2L); + + CanonicalInitialAdmissionRequest staleRequest = + initialAdmissionRequest( + catalog, + binding, + "canonical-stale-expected-closed-" + catalog.realmId(), + CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED, + 1L, + uuid(123), + uuid(124)); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(staleRequest); + return null; + })) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class); + + assertNoAttemptAndNoPending(fixture, staleRequest); + } + @Test void directlyConstructedOwnerServiceRunsMutationsInExplicitPostgresTransactions() { Fixture fixture = fixture(); @@ -757,11 +924,26 @@ private static CompleteLaunchBindingEvidence completeBinding( private static CanonicalInitialAdmissionRequest initialAdmissionRequest( CanonicalRealmCatalogSnapshot catalog, CompleteLaunchBindingEvidence binding) { - String requestId = "canonical-first-open-" + catalog.realmId(); + return initialAdmissionRequest( + catalog, + binding, + "canonical-first-open-" + catalog.realmId(), + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + uuid(113), + uuid(114)); + } + + private static CanonicalInitialAdmissionRequest initialAdmissionRequest( + CanonicalRealmCatalogSnapshot catalog, + CompleteLaunchBindingEvidence binding, + String requestId, + CanonicalInitialAdmissionRequest.OriginKind origin, + Long expectedPriorPointerVersion, + UUID holdId, + UUID holdFence) { long activeEpoch = 2L; UUID canonicalVersionId = binding.releaseAttestation().canonicalVersionId(); - CanonicalInitialAdmissionRequest.OriginKind origin = - CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER; String requestDigest = CanonicalInitialAdmissionRequest.computeRequestDigest( NAMESPACE, @@ -775,7 +957,7 @@ private static CanonicalInitialAdmissionRequest initialAdmissionRequest( activeEpoch, catalog.catalogRevision(), origin, - null, + expectedPriorPointerVersion, requestId); return new CanonicalInitialAdmissionRequest( NAMESPACE, @@ -789,14 +971,50 @@ private static CanonicalInitialAdmissionRequest initialAdmissionRequest( activeEpoch, catalog.catalogRevision(), origin, - null, + expectedPriorPointerVersion, requestId, requestDigest, - uuid(113), - uuid(114), + holdId, + holdFence, digest("e")); } + private static void assertNoAttemptAndNoPending( + Fixture fixture, CanonicalInitialAdmissionRequest request) { + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")), + DSL.field(DSL.name("initial_admission_request_id"), String.class) + .eq(request.initialAdmissionRequestId()))) + .isZero(); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")), + DSL.field(DSL.name("status"), String.class).eq("PENDING"))) + .isZero(); + } + + private static PreparedAdmission prepareAdmission(Fixture fixture) { + IntakeReceipt source = fixture.registerSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest preparationRequest = + preparationRequest(source, catalog); + AuthoredWorldLaunchDescriptorClient syntheticGameDesign = + syntheticGameDesignClient(preparationRequest, catalog, source); + GameSessionCanonicalLaunchPreparationService preparationService = + new GameSessionCanonicalLaunchPreparationService( + syntheticGameDesign, + fixture.catalogRepository, + fixture.sourceRepository, + fixture.preparationRepository, + fixture.transactionManager, + NAMESPACE); + CanonicalLaunchPreparationSnapshot preparation = preparationService.prepare(preparationRequest); + CompleteLaunchBindingEvidence binding = preparationService.readCompleteBinding(preparation); + fixture.createTestOnlyFreshMappingAndRunningLaunch(source, binding); + return new PreparedAdmission(catalog, binding); + } + private static CanonicalInitialAdmissionWorldProof testWorldProof( CanonicalInitialAdmissionRequest request) { return new CanonicalInitialAdmissionWorldProof( @@ -844,6 +1062,9 @@ private static UUID uuid(int value) { return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); } + private record PreparedAdmission( + CanonicalRealmCatalogSnapshot catalog, CompleteLaunchBindingEvidence binding) {} + private record Fixture( DSLContext dsl, DataSourceTransactionManager transactionManager, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java new file mode 100644 index 0000000000..0c06aeb817 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +class CanonicalInitialAdmissionRepositoryTest { + @Test + void pointerAndAuditVersionsUseValueEqualityBeyondLongCache() { + Long attemptVersion = Long.valueOf(129L); + Long pointerVersion = Long.valueOf(129L); + Long auditVersion = Long.valueOf(129L); + + assertThat(attemptVersion).isNotSameAs(pointerVersion); + assertThat(pointerVersion).isNotSameAs(auditVersion); + assertThat( + CanonicalInitialAdmissionRepository.pointerVersionMatches( + attemptVersion, pointerVersion)) + .isTrue(); + assertThat( + CanonicalInitialAdmissionRepository.pointerVersionMatches(attemptVersion, auditVersion)) + .isTrue(); + } + + @Test + void pointerAndAuditVersionComparisonRejectsNullMismatch() { + assertThat(CanonicalInitialAdmissionRepository.pointerVersionMatches(null, 129L)).isFalse(); + assertThat(CanonicalInitialAdmissionRepository.pointerVersionMatches(129L, null)).isFalse(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java index cca7021e17..fa430b7a96 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java @@ -1,4 +1,4 @@ -package net.firedevops.firemud.gamesession.service.impl; +package unit.net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -28,7 +28,11 @@ import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionReconciliationRequiredException; +import net.firedevops.firemud.gamesession.service.impl.CanonicalInitialAdmissionOwnerReadGrpcService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalInitialAdmissionOwnerReadWorkloadGuard; import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOwnerProofOutcome; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOwnerProofReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofResponse; import org.junit.jupiter.api.AfterEach; @@ -51,6 +55,24 @@ void clearContext() { SessionContext.clear(); } + @Test + void ownerProofReadUsesDedicatedServiceIdentityOutsideControlPlane() { + String methodName = + CanonicalInitialAdmissionOwnerProofReadServiceGrpc + .getGetCanonicalInitialAdmissionOwnerProofMethod() + .getFullMethodName(); + + assertEquals( + "game_session.v1.CanonicalInitialAdmissionOwnerProofReadService", + CanonicalInitialAdmissionOwnerProofReadServiceGrpc.getServiceDescriptor().getName()); + assertEquals( + "game_session.v1.CanonicalInitialAdmissionOwnerProofReadService/GetCanonicalInitialAdmissionOwnerProof", + methodName); + assertNotEquals( + GameSessionControlPlaneServiceGrpc.getServiceDescriptor().getName(), + CanonicalInitialAdmissionOwnerProofReadServiceGrpc.getServiceDescriptor().getName()); + } + @Test void sameNamespaceWorldWorkloadReceivesCompletePendingTupleWithoutTerminalFields() { CanonicalInitialAdmissionRepository repository = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java index 1a2d6f589d..a953c225ed 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java @@ -1,4 +1,4 @@ -package net.firedevops.firemud.gamesession.service.impl; +package unit.net.firedevops.firemud.gamesession.service.impl; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -22,6 +22,7 @@ import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import net.firedevops.firemud.gamesession.service.impl.DatabaseCanonicalInitialAdmissionService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.PlatformTransactionManager; From b4b58953fd05a2cb8d46e51f52eb6ffaae78953e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:29:35 +1300 Subject: [PATCH 15/22] Consolidate read-only mTLS preconditions and correct proof references --- .../game-session-service/api-contracts.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 4 +- .../player-access-and-session.md | 16 +-- .../AuthoredWorldLaunchDescriptorClient.java | 41 ++------ ...alStartSessionOwnerEvidenceReadClient.java | 38 ++------ .../common/grpc/FileBackedGrpcMtlsPolicy.java | 49 ++++++++++ ...WorldCanonicalInstanceLifecycleClient.java | 39 ++------ .../grpc/FileBackedGrpcMtlsPolicyTest.java | 97 +++++++++++++++++++ 8 files changed, 175 insertions(+), 111 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicy.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 2704db9cea..c1a619d39b 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,7 +8,7 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -The original-claim preparation remains inactive and default-denied: the exact owner repositories, authenticated Account-projection read/pin clients, and descriptor evidence are not registered for runtime admission. Earlier exact-head [Validation run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` executed 68 selected physical PostgreSQL cases with zero skips, including fresh-schema-to-V39 and the explicit V34.3-to-V39 baseline upgrade. The later exact-head [Validation run 38046952247](https://github.com/benhook1013/FireMUD/actions/runs/38046952247) on `141a7136c95f5bc235f93e93b3860bdf0a274480` completed the Game Session suites with 2,051 unit, 232 integration, and 39 cross-service cases; all 2,322 cases passed with zero skips, including the current descriptor, association, owner-attempt, and initial-admission migrations/readback cases. These are code and database test results, not runtime activation: production composition, World-backed playable admission, continuous owner authority through commit, and historical-owner reconciliation remain unproved. +The original-claim preparation remains inactive and default-denied: the exact owner repositories, authenticated Account-projection read/pin clients, and descriptor evidence are not registered for runtime admission. It does not establish production composition, World-backed playable admission, continuous owner authority through commit, or historical-owner reconciliation. Current implementation and proof status are recorded in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). The canonical initial-admission preparation remains inactive: its durable pre-hold intent repository/coordinator, exact World hold client, lifecycle read client, and method-specific Game Session owner-proof read are wired locally but are not registered for runtime admission. The coordinator commits immutable intent before requesting the World hold and attaches only the exact World-issued identity in a separate owner transaction. The same-namespace World-only proof RPC returns a point-in-time `PENDING` snapshot or a terminal outcome backed by a positive committed pointer and matching audit, or a durable `ABORTED` result; it does not acquire or renew a lease. The hold client reads the exact hold status and lifecycle snapshot over workload mTLS and preserves request correlation. Neither snapshot provides continuous protection through the pointer/audit commit or cross-owner terminal reconciliation. The narrower historical original-operation read is described under [restricted original-claim evidence continuation](#restricted-original-claim-evidence-continuation); neither read establishes those missing guarantees. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 9d63d3a8d2..5933419f49 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for Game Session runtime and tick This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. -Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads and an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple. The latter returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38046952247](https://github.com/benhook1013/FireMUD/actions/runs/38046952247) on `141a7136c95f5bc235f93e93b3860bdf0a274480` executed 2,051 unit, 232 integration, and 39 cross-service Game Session cases with zero skips or failures, including the owner-proof RPC and PostgreSQL-backed owner/descriptor/association cases. The prior [Validation run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` is earlier-head evidence for 68 selected physical PostgreSQL cases with zero skips. Neither endpoint is deployed; these results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. +Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads and an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple. The latter returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither endpoint is deployed; these results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. Gameplay-session context remains on the implementation-local `sessionctx:*` keys and per-instance binding identity. The target authenticated `session:game:{tenantGameplayTag}:...` family, persisted tenant-tag allocation, and namespace-qualified controller uniqueness are not implemented or end-to-end proved; the canonical tenancy and focused-isolation requirements remain in [Multi-Tenancy](../../architecture/system-architecture-multi-tenancy.md#data-separation-per-service). @@ -49,7 +49,7 @@ These links add decision provenance only; they do not upgrade any Game Session i | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation, and lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and opt-in fixture coordination are wired locally. Historical original-owner evidence reads are read-only. These preparations remain inactive and grant no player-admission authority; general `StartSession` retry integration is not claimed. | `proven` for front-door routing through the existing WebSocket, normalization, and gRPC tests. The owner-proof producer is covered by [CanonicalInitialAdmissionOwnerReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java), with same-namespace caller checks in [CanonicalInitialAdmissionOwnerReadWorkloadGuard](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java); durable owner behavior is covered by [DatabaseCanonicalInitialAdmissionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java) and [CanonicalInitialAdmissionRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java). Exact-head [Validation run 38046952247](https://github.com/benhook1013/FireMUD/actions/runs/38046952247) on `141a7136c95f5bc235f93e93b3860bdf0a274480` executed 2,051 unit, 232 integration, and 39 cross-service cases with zero skips or failures. Earlier [run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) is prior-head evidence for 68 selected physical PostgreSQL cases with zero skips. Cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [DatabaseCanonicalInitialAdmissionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java); [CanonicalInitialAdmissionIntentRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java); [CanonicalInitialAdmissionOwnerReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java); [CanonicalInitialAdmissionOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java); [canonical initial-admission owner-proof RPC](../../../protos/game-session/v1/game_session_service.proto); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java) | [CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [DatabaseCanonicalInitialAdmissionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java); [CanonicalInitialAdmissionRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); [CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java); [CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; ambiguous outcomes continue to fence World termination. The owner boundary is game-instance scoped and does not implement independently partitioned-region forwarding. | +| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation, and lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and opt-in fixture coordination are wired locally. Historical original-owner evidence reads are read-only. These preparations remain inactive and grant no player-admission authority; general `StartSession` retry integration is not claimed. | `proven` for front-door routing through the existing WebSocket, normalization, and gRPC tests. The owner-proof producer is covered by [CanonicalInitialAdmissionOwnerReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java). The historical original-owner producer and caller guard are exercised by [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java) and [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java). Durable owner behavior is covered by [DatabaseCanonicalInitialAdmissionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java) and [CanonicalInitialAdmissionRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java). Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service cases; all 2,327 passed with zero skips, failures, or errors. Cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [DatabaseCanonicalInitialAdmissionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java); [CanonicalInitialAdmissionIntentRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java); [CanonicalInitialAdmissionOwnerReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java); [CanonicalInitialAdmissionOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java); [canonical initial-admission owner-proof RPC](../../../protos/game-session/v1/game_session_service.proto); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java) | [CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [DatabaseCanonicalInitialAdmissionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java); [CanonicalInitialAdmissionRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); [CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java); [CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; ambiguous outcomes continue to fence World termination. The owner boundary is game-instance scoped and does not implement independently partitioned-region forwarding. | | `GR-1.2` Tick timelines, action fairness, queues, and scheduling | `partial`: current bounded scheduler, per-entity queue selection, gameplay-command ordering (including timer/automation-origin work only after materialization as gameplay commands with retained provenance/order fields), durable batch/effect staging, pressure signals, and sealed selected-work manifests for gameplay commands are live; directly selected timer/retry/remote-follow-up source-claim manifests remain target-state; it still uses universal work-item selection and does not implement the accepted separate actor-action/passive-effect lane classification, phase budgets, or lane-preserving retry contract; the complete in-place command-status lifecycle accepted by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) is not | `drift-found`: the shipped scheduler and queue/effect seams have focused proof, but lane/source classification, separate lane budgets, and passive/inbound non-actor-turn behavior are not proved; the accepted command-status lifecycle in [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) remains unimplemented and is not fully proved | [ticks](../../architecture/system-architecture-ticks.md); [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | [TickScheduler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [TickServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game-session-service.proto](../../../protos/game-session/v1/game_session_service.proto) | [TickSchedulerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java) | `AS-1.4` timer progress and `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); `GR-1.3` ownership in this tracker | Add the [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) acknowledgement dimensions, authoritative attempt history, bound-tick summary, convergence contract, persistence, and focused proof to `GetGameplayCommandStatus`; separately add TICK-01 source classification, lane/cost metadata, phase budgets, lane-preserving retry identity, and focused actor/passive scheduling proof; adaptive timing and true region-wide scheduling remain separate gaps. | | `GR-1.3` Region leases, fencing, and executor coordination | `partial`: durable runtime ownership, epoch/fence snapshots, pause/resume, stale-owner rejection/requeue, and current runtime-progress publication are live at the game-instance boundary; the TICK-02 Redis lease plus durable executor-fence install/revalidate handshake and true region takeover boundary remain target-state | `proven`: current tests cover fence/scope admission, tick progress, stale execution, and operator reads, but do not prove the TICK-02 lease/fence handshake or takeover reconciliation | [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [RuntimeRegionStatus](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/RuntimeRegionStatus.java); [runtime ownership read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java); [TickRuntimeProgressService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java); [TickRuntimeProgressServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | `GR-1.1` front-end routing in this tracker; `AS-1.1` ingress and `AS-1.4` timers in [Automation runtime tracker](./automation-and-scheduler-runtime.md); Redis lease coordination is the shared infrastructure handoff | The current durable owner row and lease boundary are game-instance scoped. Add proof for Redis lease acquisition/loss before and after durable fence installation, same-token revalidation, stale-fence rejection, and takeover reconciliation; true region-partitioned leases, cluster scheduling, and front-end forwarding remain unimplemented. | | `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, remote result reconciliation, and bounded restart/reset paths are live; startup recovery re-enqueues old accepted-but-unstaged commands under their existing identity and leaves them `ACCEPTED` when Redis, identity, eligibility, or a raced transition prevents safe materialization; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `drift-found`: focused unit recovery tests cover accepted-row re-drive, unchanged retryable state on uncertainty, serializer-free identity/payload-idempotent queue/pending behavior, remote reconciliation, and retryability on Redis/eligibility races, but do not provide combined PostgreSQL/real-Redis restart proof, lane/cost preservation, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake; the real-Redis serializer integration test is present but skipped when Docker is unavailable | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | 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 f07989c9a8..56ba19805c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,19 +14,19 @@ This inactive owner continuation may read or replay the exact immutable associat Previously recorded focused local unit and transport evidence includes the [authorization coordinator test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java), [continuation service test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java), [redemption client test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java), and [mTLS redemption client test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java). The implementation anchors are [authorization coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java), [owner attempt repository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java), [template association repository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java), and [descriptor continuation service](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java), with schema support in [V35](../../../services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql), [V37](../../../services/game-session-service/src/main/resources/db/migration/V37__start_session_template_association_pin.sql), and [V38](../../../services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql). -Integration sources cover fresh schema, explicit V34.3 baseline upgrade, original-claim and reference expiry while writes wait on PostgreSQL locks, and the coordinator boundary: [owner attempt repository integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java), [template association repository integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java), [launch descriptor repository integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java), and [authorization coordinator integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java). The earlier [CI run 38034433313](https://github.com/benhook1013/FireMUD/actions/runs/38034433313) on `f23871f6c4` is historical partial evidence: its owner-attempt and association suites passed, while three descriptor expiry regressions failed and are not counted. The later exact-head [CI run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` executed 68 selected physical PostgreSQL tests with zero skips: 46 launch/owner/history cases (owner attempt 12, association 10, descriptor 12, historical association 8, coordinator 3, run-owned launch 1), 16 admission/pointer cases (intent 4, bind 1, pointer migration 8, CAS 2, request-ID migration 1), and 6 command-history cases. The selected artifacts include fresh-schema-to-V39 and `v34_3BaselineUpgradePreservesLegitimateEvidenceAndCreatesContinuationConstraints` V34.3-to-V39 execution. This closes the physical-proof gap only for those exact source fixtures; regressions added or changed after that run remain unexecuted until a later physical run. +Historical earlier-head [Validation run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` executed 68 selected PostgreSQL cases with zero skips; that result applies only to its selected fixtures and source head. The latest exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases. All 2,327 passed with zero skips, failures, or errors. Its JUnit artifacts include the owner-attempt (12), template-association (10), launch-descriptor (12), original-association read (8), authorization-coordinator (3), and V34.3 request-ID migration (1) suites. This is aggregate current-head physical proof; it does not assert one-to-one matching of the 21 failures from the earlier failed job. -The restricted original-claim continuation remains inactive and default-denied: its owner repositories, typed Account read/pin clients, and descriptor evidence producer remain unregistered, do not alter the composed production implementation, and authorize neither mutation nor player admission. Exact-head [CI run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) provides physical PostgreSQL evidence for the selected existing owner/history fixtures, including fresh-schema-to-V39 and V34.3-to-V39 upgrade paths; it does not prove runtime registration, World-backed admission, historical-owner reconciliation, or playable closure. The later consolidated local Game Session check passed the new unit regressions and compiled the integration sources; new or changed PostgreSQL regressions still require physical execution. +The restricted original-claim continuation remains inactive and default-denied: its owner repositories, typed Account read/pin clients, and descriptor evidence producer remain unregistered, do not alter the composed production implementation, and authorize neither mutation nor player admission. The latest exact-head run above physically executed the current owner/history integration suites; it does not prove runtime registration, World-backed admission, historical-owner reconciliation, or playable closure. The earlier local check that compiled integration sources without running PostgreSQL is historical local-environment evidence, superseded for the listed fixture suites by the hosted result. -The latest inactive hold client reads the exact immutable identity, actual hold status and full lifecycle snapshot over workload mTLS. Common authored fixtures are shared rather than duplicated. The original STARTING association read carries the full stored post-authorization tuple and actual owner attempt/fence, but still requires an unexpired pending claim; it is not an after-expiry association endpoint. The composed local gate passed in 1m59s: 287 Common and 2,010 Game Session unit definitions had zero failures (17 Game Session skips); integration definitions executed 18 and skipped 200, while cross-service definitions executed one and skipped 38. Cached task outputs are included. Physical Game Session job `114071452179` on `c79103014c1b991f4caaa3f1fef04652ec1adda8` failed 21 of 218 integration cases: 20 shared fixture timestamp violations and one fresh source-bound tenant guard rejecting a canonical pointer insert. Replacement physical proof remains required after the corrections. Hold snapshots and retained tuples do not supply continuous commit authority. The authenticated historical original-owner evidence producer is implemented locally but remains unregistered and undeployed; live hold validation, continuous protection through the pointer/audit commit, and cross-owner terminal reconciliation remain incomplete. +The inactive hold client reads the exact immutable identity, actual hold status, and full lifecycle snapshot over workload mTLS. The original STARTING association read carries the stored post-authorization tuple and actual owner attempt/fence, but requires an unexpired pending claim; it is not an after-expiry association endpoint. Historical Game Session job `114071452179` on `c79103014c1b991f4caaa3f1fef04652ec1adda8` failed 21 of 218 integration cases (20 shared-fixture timestamp violations and one source-bound tenant guard rejection). The later exact-head run 38049505627 completed 234 integration cases with no failures or skips, but the artifact evidence here does not map each earlier failed case one by one. Hold snapshots and retained tuples do not supply continuous commit authority. The authenticated historical original-owner evidence producer remains unregistered and undeployed; live hold validation, continuous protection through pointer/audit commit, and cross-owner terminal reconciliation remain incomplete. -Game Session has an unregistered original-claim evidence-continuation preparation: owner repositories, typed read/pin carriers, before-and-after authenticated Account projection reads outside SQL, and database-clock claim/reference-expiry checks at descriptor pinning. Consolidated Common/Game Session unit and non-container integration checks pass, as do generated-source compilation, formatting, static analysis, and documentation checks. PostgreSQL fixtures cover expiry, exact replay, mismatch, and pin races but remain unexecuted locally without Docker. Genuine Account original-redeemed receiver revalidation and full pointer/audit/live-owner composition remain required; mocked responses do not prove that receiver. This preparation grants no new mutation authorization or admission and does not establish playable closure. The bounded contract is owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). +Game Session has an unregistered original-claim evidence-continuation preparation: owner repositories, typed read/pin carriers, before-and-after authenticated Account projection reads outside SQL, and database-clock claim/reference-expiry checks at descriptor pinning. Earlier Docker-disabled local snapshots compiled the PostgreSQL fixtures but did not execute them locally; the latest exact-head Validation artifact now records successful physical execution of the owner-attempt, association, descriptor, and coordinator integration suites. Genuine Account original-redeemed receiver revalidation and full pointer/audit/live-owner composition remain required; mocked responses do not prove that receiver. This preparation grants no new mutation authorization or admission and does not establish playable closure. The bounded contract is owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). -The same inactive preparation includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These repositories, coordinator and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Earlier consolidated local checks passed in 2m36s and after exact parent reconciliation in 54s: 271 Common and 1,992 Game Session unit definitions had zero failures (17 Game Session skips); 208 integration definitions executed 18 and skipped 190 without Docker, while cross-service definitions executed one and skipped 38. These include reused task outputs rather than a claim that every definition executed again. The PostgreSQL fixtures compile but have not physically executed locally. World Management's published change `2cb445617` supplies the canonical World hold request and immutable identity, including both origin selectors and the request-binding digest; the older numeric hold RPC is not that interface. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. +The same inactive preparation includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event, and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These repositories, coordinator, and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Earlier local checks that reused cached task outputs and lacked Docker are historical local-only results; they do not supersede the latest exact-head physical test evidence and do not establish activation. World Management's published change `2cb445617` supplies the canonical World hold request and immutable identity, including both origin selectors and the request-binding digest; the older numeric hold RPC is not that interface. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup, and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. -The newer inactive consumer adds exact mTLS World acquisition/identity and lifecycle read clients, the V28-backed durable pre-hold intent repository, and a coordinator that commits the immutable request before contacting World and attaches only the exact returned hold identity in a separate owner transaction. Remote failure preserves the pending intent for the same request; attached or terminal replay returns historical evidence only. Owner repositories also expose non-mutating historical reads of the complete original StartSession tuple, actual attempt/fence, attached Account projection and immutable first template pin after expiry, separately from the still-unexpired live continuation. Consolidated Common/Game Session checks, generated and integration-source compilation, formatting, Checkstyle, SpotBugs, links and Markdown checks passed in 1m5s. The local snapshot has 283 Common and 2,006 Game Session unit definitions with zero failures and 17 Game Session skips; integration definitions executed 18 and skipped 200, and cross-service executed one and skipped 38 without Docker. Cached task outputs are included, not claimed as fresh re-execution. The new PostgreSQL ordering fixture checks that a separate connection sees the exact committed pending intent before World acquisition and that remote failure/retry preserves one exact intent; it has not physically executed locally. The authenticated historical original-owner evidence producer is implemented locally but remains unregistered and undeployed. Live hold validation, continuous protection through pointer/audit commit, and cross-owner terminal reconciliation remain unimplemented. Neither a historical identity nor a lifecycle snapshot proves those guarantees, and no runtime registration or activation is added. +The newer inactive consumer adds exact mTLS World acquisition/identity and lifecycle read clients, the V28-backed durable pre-hold intent repository, and a coordinator that commits immutable intent before contacting World and attaches only the exact returned hold identity in a separate owner transaction. Remote failure preserves pending intent for the same request; attached or terminal replay returns historical evidence only. Owner repositories also expose non-mutating historical reads of the complete original StartSession tuple, actual attempt/fence, attached Account projection, and immutable first template pin after expiry, separately from the still-unexpired live continuation. The latest exact-head artifact confirms its listed PostgreSQL suites executed successfully; it does not prove the consumer is registered, that a genuine World verifier participates at runtime, or that hold authority remains continuous through pointer/audit commit. Cross-owner terminal reconciliation, concurrent termination/restart proof, and playable closure remain open. -This bounded update adds a unit assertion for the original authorization-expiry bind and PostgreSQL regression definitions for an expired reference with a live owner lease and for a reference expiring while the initial association write is blocked. The descriptor integration fixture now creates the association while its original reference is live, waits for natural expiry, then checks that descriptor pinning remains denied while the owner lease is live. These updated regression definitions were not executed in this task; no exact-head unit or physical PostgreSQL result is claimed, and the `AA-2.1` capability row below retains the capability status. +The latest exact-head Validation artifact records the descriptor, association, owner-attempt, and authorization-coordinator integration suites as passing (12, 10, 12, and 3 cases respectively), along with the historical original-association read suite (8 cases). It also records the historical owner producer and workload-guard unit suites as passing (6 and 4 cases). This aggregate run is not a one-to-one audit of the 21 failures in job 114071452179; the `AA-2.1` capability remains partial because namespace-aware atomic takeover, final Account admission, runtime activation, and live playable proof are still open. The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. Historical and current bounded proof, failures, and pending physical validation are recorded below. Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Hosted-terms acceptance, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898/#2848 and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). @@ -77,7 +77,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head [Validation run 38046952247](https://github.com/benhook1013/FireMUD/actions/runs/38046952247) executed 2,051 unit, 232 integration, and 39 cross-service Game Session cases with zero skips or failures; the V34.3 PostgreSQL fixture ran one case successfully. This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases with zero skips or failures; the V34.3 PostgreSQL fixture ran one case successfully. This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java index 0cfe9621fe..c0b6147199 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java @@ -2,14 +2,13 @@ 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.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -164,38 +163,10 @@ private void requireNamespace(String targetNamespace) { private static CommonGrpcClientProperties requireFileBackedMtls( CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null) { - throw new IllegalArgumentException("gRPC mTLS configuration is required"); - } - if (tlsProperties.isPlaintext()) { - throw new IllegalArgumentException("Launch descriptor reads require 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( - "Launch descriptor reads require file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Launch descriptor reads require file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException exception) { - throw new IllegalArgumentException( - "Launch descriptor " + label + " must be a readable file-backed path", exception); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Launch descriptor " + label + " must be an existing readable file"); - } + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "Launch descriptor reads", + "gRPC mTLS configuration is required", + "Launch descriptor reads require workload mTLS"); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java index b4603bd61e..1a5404d5d2 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.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; @@ -12,6 +10,7 @@ import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Result; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -132,35 +131,10 @@ public synchronized void close() throws IOException { private static CommonGrpcClientProperties requireFileBackedMtls( CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException("Historical StartSession evidence reads require 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( - "Historical StartSession evidence reads require file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Historical StartSession evidence reads require file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Historical StartSession " + label + " must be a readable file-backed path", invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Historical StartSession " + label + " must be an existing readable file"); - } + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "Historical StartSession evidence reads", + "Historical StartSession evidence reads require mTLS", + "Historical StartSession evidence reads require mTLS"); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicy.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicy.java new file mode 100644 index 0000000000..25c4bb4e58 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicy.java @@ -0,0 +1,49 @@ +package net.firedevops.firemud.common.grpc; + +import java.nio.file.Files; +import java.nio.file.Path; + +/** Validates the file-backed client credentials required by selected internal mTLS reads. */ +public final class FileBackedGrpcMtlsPolicy { + private FileBackedGrpcMtlsPolicy() {} + + /** Requires non-plaintext gRPC TLS configured with three existing, readable filesystem files. */ + public static CommonGrpcClientProperties require( + CommonGrpcClientProperties tlsProperties, + String purpose, + String missingConfigurationMessage, + String plaintextMessage) { + if (tlsProperties == null) { + throw new IllegalArgumentException(missingConfigurationMessage); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException(plaintextMessage); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain", purpose); + requireReadableFile(tlsProperties.getPrivateKey(), "private key", purpose); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate", purpose); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label, String purpose) { + String materialMessage = purpose + " requires file-backed certificate, key, and CA material"; + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException(materialMessage); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException(materialMessage); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + purpose + " " + label + " must be a readable file-backed path"); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + purpose + " " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java index 33aef52809..600429372a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java @@ -2,14 +2,13 @@ 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.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; @@ -121,36 +120,10 @@ public synchronized void close() throws IOException { private static CommonGrpcClientProperties requireFileBackedMtls( CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException("World canonical lifecycle 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( - "World canonical lifecycle read requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "World canonical lifecycle read requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "World canonical lifecycle read " + label + " must be a readable file-backed path", - invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "World canonical lifecycle read " + label + " must be an existing readable file"); - } + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "World canonical lifecycle read", + "World canonical lifecycle read requires workload mTLS", + "World canonical lifecycle read requires workload mTLS"); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java new file mode 100644 index 0000000000..b7577ae257 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class FileBackedGrpcMtlsPolicyTest { + private static final String PURPOSE = "test read"; + private static final String NULL_CONFIGURATION_MESSAGE = "gRPC mTLS configuration is required"; + private static final String PLAINTEXT_MESSAGE = "test read requires workload mTLS"; + + @Test + void acceptsReadableFileBackedMtlsMaterial(@TempDir Path directory) throws Exception { + CommonGrpcClientProperties properties = propertiesWithFiles(directory); + + assertThat(require(properties)).isSameAs(properties); + } + + @Test + void rejectsMissingOrPlaintextConfiguration() { + assertThatThrownBy(() -> require(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(NULL_CONFIGURATION_MESSAGE); + + CommonGrpcClientProperties plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> require(plaintext)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(PLAINTEXT_MESSAGE); + } + + @Test + void rejectsMissingClasspathInvalidDirectoryAndNonexistentMaterial(@TempDir Path directory) + throws Exception { + for (String material : new String[] {"certChain", "privateKey", "caCert"}) { + CommonGrpcClientProperties missingProperties = propertiesWithFiles(directory); + setPath(missingProperties, material, null); + assertThatThrownBy(() -> require(missingProperties)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + } + + CommonGrpcClientProperties classpathProperties = propertiesWithFiles(directory); + classpathProperties.setCaCert("classpath:ca.crt"); + assertThatThrownBy(() -> require(classpathProperties)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties invalidPathProperties = propertiesWithFiles(directory); + invalidPathProperties.setPrivateKey("\u0000sensitive-path"); + assertThatThrownBy(() -> require(invalidPathProperties)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("private key") + .hasMessageNotContaining("sensitive-path"); + + CommonGrpcClientProperties directoryProperties = propertiesWithFiles(directory); + directoryProperties.setCaCert(directory.toString()); + assertThatThrownBy(() -> require(directoryProperties)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file") + .hasMessageNotContaining(directory.toString()); + + CommonGrpcClientProperties missingFileProperties = propertiesWithFiles(directory); + String missingPath = directory.resolve("sensitive-missing-ca.crt").toString(); + missingFileProperties.setCaCert(missingPath); + assertThatThrownBy(() -> require(missingFileProperties)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file") + .hasMessageNotContaining(missingPath); + } + + private static CommonGrpcClientProperties require(CommonGrpcClientProperties properties) { + return FileBackedGrpcMtlsPolicy.require( + properties, PURPOSE, NULL_CONFIGURATION_MESSAGE, PLAINTEXT_MESSAGE); + } + + private static CommonGrpcClientProperties propertiesWithFiles(Path directory) throws Exception { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(Files.createTempFile(directory, "client-cert", ".pem").toString()); + properties.setPrivateKey(Files.createTempFile(directory, "client-key", ".pem").toString()); + properties.setCaCert(Files.createTempFile(directory, "client-ca", ".pem").toString()); + return properties; + } + + private static void setPath(CommonGrpcClientProperties properties, String material, String path) { + switch (material) { + case "certChain" -> properties.setCertChain(path); + case "privateKey" -> properties.setPrivateKey(path); + case "caCert" -> properties.setCaCert(path); + default -> throw new IllegalArgumentException("Unknown test material"); + } + } +} From 7fe21073badefbecd046e44b9f455c1e363c3702 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:56:38 +1300 Subject: [PATCH 16/22] Fix canonical OPEN intake and watcher close review findings --- .../player-access-and-session.md | 2 +- .../AuthoredWorldLaunchDescriptorClient.java | 8 +- ...thoredWorldLaunchDescriptorClientTest.java | 120 +++++++++++++++ .../CanonicalInitialAdmissionRepository.java | 18 ++- ...eSessionAuthoredWorldSourceRepository.java | 10 ++ ...ialAdmissionRepositoryIntegrationTest.java | 5 + ...nonicalInitialAdmissionRepositoryTest.java | 137 ++++++++++++++++++ ...sionAuthoredWorldSourceRepositoryTest.java | 85 +++++++++++ 8 files changed, 380 insertions(+), 5 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryTest.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 56ba19805c..7b1082af5c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -64,7 +64,7 @@ Deployment must not advertise retained credential/security-write workflows as re - `AA-2.1` / `AA-2.2` / `AA-3.3`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) remains the canonical target link for stable namespace-aware selection, admission, reconnect, and runtime replacement; [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) owns namespace-scoped controller identity, uniqueness, takeover, and binding-generation fencing. Existing account/session and realm-routing evidence remains partial and does not prove namespace-aware atomic takeover, replacement, or cleanup behavior. - `AA-3.3`: [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) adds the player-visible lifecycle consequence that only an active, admissible realm is exposed; Temporal coordination does not become admission authority. Existing lifecycle and reconnect caveats remain. -- The finite namespace controller-index migration-driver prefix is source and packaging preparation only. The most recent independent Common Security and Game Session full checks completed without failures or errors; those checks do not prove the newly adjudicated fixes or physical PostgreSQL/Redis execution. Distribution packaging, exact source-to-jar migration resource comparison, synthetic missing/changed/duplicate resource rejection, ShellCheck, and documentation checks pass. Physical PostgreSQL/Redis execution, final image build and immutable image authority, trusted bootstrap/execution, and live playable proof remain unrun; Docker-disabled local checks do not establish PostgreSQL fixture behavior. Issuer-index and region reconciliation and final Account admission have no proof in this slice. This status does not establish an empty retained-binding inventory, prove conversion of non-empty retained data, or authorize running the driver. `AA-2.1` and `AA-2.2` remain `partial` / `drift-found`; gameplay completion under #2967/#2898 remains separate. See [Game Session Operations](../../architecture/microservices/game-session-service/operations.md#namespace-controller-index-migration-driver), the canonical [Legacy controller-index migration gate](../../architecture/system-architecture-session-behavior.md#legacy-controller-index-migration-gate), and the unrun [V34.3 intent request-ID PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java). +- The finite namespace controller-index migration-driver prefix is source and packaging preparation only. The most recent independent Common Security and Game Session full checks completed without failures or errors; those checks do not prove the newly adjudicated fixes or complete physical PostgreSQL/Redis execution. Distribution packaging, exact source-to-jar migration resource comparison, synthetic missing/changed/duplicate resource rejection, ShellCheck, and documentation checks pass. The [V34.3 intent request-ID PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) passed in exact-head Validation run 38049505627 as recorded above; that single fixture does not establish the complete migration-driver PostgreSQL/Redis path. Complete driver execution, final image build and immutable image authority, trusted bootstrap/execution, and live playable proof remain unrun; Docker-disabled local checks do not establish PostgreSQL fixture behavior. Issuer-index and region reconciliation and final Account admission have no proof in this slice. This status does not establish an empty retained-binding inventory, prove conversion of non-empty retained data, or authorize running the driver. `AA-2.1` and `AA-2.2` remain `partial` / `drift-found`; gameplay completion under #2967/#2898 remains separate. See [Game Session Operations](../../architecture/microservices/game-session-service/operations.md#namespace-controller-index-migration-driver) and the canonical [Legacy controller-index migration gate](../../architecture/system-architecture-session-behavior.md#legacy-controller-index-migration-gate). These links add decision provenance only; they do not upgrade player-access or session capability status. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java index c0b6147199..fca083a629 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java @@ -139,9 +139,11 @@ protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub(ManagedC } @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/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java new file mode 100644 index 0000000000..7d8989739e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import io.grpc.ManagedChannel; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +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.TlsCertificateWatcher; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AuthoredWorldLaunchDescriptorClientTest { + @Test + void closeReleasesClientMonitorBeforeClosingCertificateWatcher(@TempDir Path directory) + throws Exception { + String previousReloadPolicy = System.getProperty("firemud.grpc.tls-reload.enabled"); + System.setProperty("firemud.grpc.tls-reload.enabled", "false"); + try { + Path certificate = Files.writeString(directory.resolve("tls.crt"), "certificate"); + Path privateKey = Files.writeString(directory.resolve("tls.key"), "private-key"); + Path caCertificate = Files.writeString(directory.resolve("ca.crt"), "ca-certificate"); + CommonGrpcClientProperties tlsProperties = new CommonGrpcClientProperties(); + tlsProperties.setCertChain(certificate.toString()); + tlsProperties.setPrivateKey(privateKey.toString()); + tlsProperties.setCaCert(caCertificate.toString()); + CountingChannelFactory channelFactory = new CountingChannelFactory(); + AuthoredWorldLaunchDescriptorClient client = + new AuthoredWorldLaunchDescriptorClient( + new ServiceEndpointsProperties(), tlsProperties, channelFactory, "test-namespace"); + client.init(); + + TlsCertificateWatcher watcher = mock(TlsCertificateWatcher.class); + CountDownLatch callbackFinished = new CountDownLatch(1); + AtomicBoolean callbackAcquiredMonitor = new AtomicBoolean(); + AtomicReference callbackFailure = new AtomicReference<>(); + doAnswer( + invocation -> { + assertThat(Thread.holdsLock(client)).isFalse(); + Thread callback = + new Thread( + () -> { + try { + synchronized (client) { + callbackAcquiredMonitor.set(true); + } + } catch (Throwable failure) { + callbackFailure.set(failure); + } finally { + callbackFinished.countDown(); + } + }, + "authored-world-launch-descriptor-test-callback"); + callback.start(); + if (!callbackFinished.await(1, TimeUnit.SECONDS)) { + callback.interrupt(); + callback.join(TimeUnit.SECONDS.toMillis(1)); + throw new AssertionError("Watcher callback could not acquire the client monitor"); + } + callback.join(TimeUnit.SECONDS.toMillis(1)); + assertThat(callback.isAlive()).isFalse(); + assertThat(callbackAcquiredMonitor.get()).isTrue(); + assertThat(callbackFailure.get()).isNull(); + return null; + }) + .when(watcher) + .close(); + setWatcher(client, watcher); + + client.close(); + + verify(watcher).close(); + assertThat(channelFactory.buildAttempts.get()).isEqualTo(1); + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Authored-world launch descriptor client is closed"); + assertThat(channelFactory.buildAttempts.get()).isEqualTo(1); + } finally { + if (previousReloadPolicy == null) { + System.clearProperty("firemud.grpc.tls-reload.enabled"); + } else { + System.setProperty("firemud.grpc.tls-reload.enabled", previousReloadPolicy); + } + } + } + + private static void setWatcher( + AuthoredWorldLaunchDescriptorClient client, TlsCertificateWatcher watcher) + throws ReflectiveOperationException { + Field watcherField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); + watcherField.setAccessible(true); + watcherField.set(client, watcher); + } + + private static final class CountingChannelFactory extends GrpcChannelFactory { + private final AtomicInteger buildAttempts = new AtomicInteger(); + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + buildAttempts.incrementAndGet(); + return mock(ManagedChannel.class); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java index 91320e5472..91db3f4cd5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java @@ -412,7 +412,18 @@ public CurrentOpenSnapshot readCurrentOpenSnapshotForRealm( throw new CanonicalInitialAdmissionReconciliationRequiredException( "Current canonical OPEN pointer changed during owner readback"); } - return new CurrentOpenSnapshot(proof, before.snapshotDigest(proof)); + return new CurrentOpenSnapshot(proof, snapshotDigestOrReconciliation(before, proof)); + } + + private static String snapshotDigestOrReconciliation( + CurrentOpenPointer pointer, CanonicalInitialAdmissionOwnerProof proof) { + try { + return pointer.snapshotDigest(proof); + } catch (IllegalArgumentException | NullPointerException malformed) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN snapshot contains malformed persisted projection evidence", + malformed); + } } private CurrentOpenPointer readCurrentOpenPointer( @@ -1496,5 +1507,10 @@ public static class CanonicalInitialAdmissionReconciliationRequiredException public CanonicalInitialAdmissionReconciliationRequiredException(String message) { super(message); } + + public CanonicalInitialAdmissionReconciliationRequiredException( + String message, Throwable cause) { + super(message, cause); + } } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java index e411647eaa..3335f54ded 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java @@ -337,6 +337,7 @@ private void requireExactSource( private AuthoredWorldSourceEvidence validateSource(AuthoredWorldSourceEvidence source) { Objects.requireNonNull(source, "source"); + requireCanonicalOpenWorldDisplayName(source.worldDisplayName()); try { return new AuthoredWorldSourceEvidence( source.schemaVersion(), @@ -358,6 +359,15 @@ private AuthoredWorldSourceEvidence validateSource(AuthoredWorldSourceEvidence s } } + private static void requireCanonicalOpenWorldDisplayName(String worldDisplayName) { + if (worldDisplayName == null + || worldDisplayName.isBlank() + || !worldDisplayName.equals(worldDisplayName.trim())) { + throw new InvalidIntakeEvidenceException( + "Game Design authored-world source display name is not canonical for an OPEN pointer"); + } + } + private void requireActiveOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index be7673ce79..74f802f4bb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -253,6 +253,11 @@ void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { assertThat(committed.canonicalVersionId()).isEqualTo(CANONICAL_VERSION); assertThat(committed.committedPointerVersion()).isEqualTo(1L); assertThat(committed.auditEventId()).isPositive(); + CanonicalInitialAdmissionRepository.CurrentOpenSnapshot currentSnapshot = + fixture.initialAdmissionRepository.readCurrentOpenSnapshotForRealm( + NAMESPACE, TENANT, request.realmId()); + assertThat(currentSnapshot.ownerProof()).isEqualTo(committed); + assertThat(currentSnapshot.admissionPointerSnapshotDigest()).matches("[0-9a-f]{64}"); assertThat( fixture.dsl.fetchCount( DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java index 0c06aeb817..58bf67985d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java @@ -1,7 +1,17 @@ package net.firedevops.firemud.gamesession.repository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; import org.junit.jupiter.api.Test; class CanonicalInitialAdmissionRepositoryTest { @@ -27,4 +37,131 @@ void pointerAndAuditVersionComparisonRejectsNullMismatch() { assertThat(CanonicalInitialAdmissionRepository.pointerVersionMatches(null, 129L)).isFalse(); assertThat(CanonicalInitialAdmissionRepository.pointerVersionMatches(129L, null)).isFalse(); } + + @Test + void malformedPersistedOpenProjectionRequiresReconciliationAtSnapshotBoundary() { + CanonicalInitialAdmissionOwnerProof proof = committedProof(); + Object validPointer = currentOpenPointer(validOpenFields()); + + assertThat(snapshotDigest(validPointer, proof)).matches("[0-9a-f]{64}"); + + Map paddedName = validOpenFields(); + paddedName.put("world_display_name", " Demo World "); + assertMalformedProjection( + currentOpenPointer(paddedName), proof, IllegalArgumentException.class); + + Map invalidOrigin = validOpenFields(); + invalidOrigin.put("initial_admission_origin_kind", "UNKNOWN_ORIGIN"); + assertMalformedProjection( + currentOpenPointer(invalidOrigin), proof, IllegalArgumentException.class); + + Map nullOrigin = validOpenFields(); + nullOrigin.put("initial_admission_origin_kind", null); + assertMalformedProjection(currentOpenPointer(nullOrigin), proof, NullPointerException.class); + } + + private static void assertMalformedProjection( + Object pointer, CanonicalInitialAdmissionOwnerProof proof, Class cause) { + assertThatThrownBy(() -> snapshotDigest(pointer, proof)) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalInitialAdmissionReconciliationRequiredException.class) + .hasCauseInstanceOf(cause); + } + + private static String snapshotDigest(Object pointer, CanonicalInitialAdmissionOwnerProof proof) { + try { + Method method = + CanonicalInitialAdmissionRepository.class.getDeclaredMethod( + "snapshotDigestOrReconciliation", pointer.getClass(), proof.getClass()); + method.setAccessible(true); + return (String) method.invoke(null, pointer, proof); + } catch (InvocationTargetException invocation) { + if (invocation.getCause() instanceof RuntimeException cause) { + throw cause; + } + throw new AssertionError(invocation.getCause()); + } catch (ReflectiveOperationException reflectionFailure) { + throw new AssertionError(reflectionFailure); + } + } + + private static Object currentOpenPointer(Map fields) { + try { + Class pointerType = + Class.forName( + CanonicalInitialAdmissionRepository.class.getName() + "$CurrentOpenPointer"); + Constructor constructor = pointerType.getDeclaredConstructor(Map.class); + constructor.setAccessible(true); + return constructor.newInstance(fields); + } catch (ReflectiveOperationException reflectionFailure) { + throw new AssertionError(reflectionFailure); + } + } + + private static Map validOpenFields() { + Map fields = new HashMap<>(); + fields.put("representation_version", 3); + fields.put("target_namespace", "gameplay"); + fields.put("canonical_tenant_id", uuid(1)); + fields.put("world_slug", "demo-world"); + fields.put("world_display_name", "Demo World"); + fields.put("realm_id", uuid(2)); + fields.put("realm_slug", "main"); + fields.put("realm_display_name", "Production Main"); + fields.put("playable_state_namespace_id", uuid(3)); + fields.put("state_scope", "SHARED"); + fields.put("catalog_revision", 41L); + fields.put("pointer_version", 73L); + fields.put("admission_state", "OPEN"); + fields.put("visible", true); + fields.put("public_production_realm", true); + fields.put("requires_character_selection", null); + fields.put("character_creation_policy", "ALLOW_NEW"); + fields.put("canonical_game_instance_id", uuid(4)); + fields.put("canonical_version_id", uuid(5)); + fields.put("initial_admission_request_id", "initial-admission-request"); + fields.put("initial_admission_request_digest", "a".repeat(64)); + fields.put("initial_admission_origin_kind", "NO_PRIOR_POINTER"); + fields.put("initial_admission_prior_pointer_version", null); + fields.put("initial_admission_active_epoch", 82L); + fields.put("initial_admission_hold_id", uuid(6)); + fields.put("initial_admission_hold_fence", uuid(7)); + fields.put("initial_admission_hold_binding_digest", "sha256:" + "b".repeat(64)); + fields.put("last_updated_by", "game-session-canonical-initial-admission"); + fields.put("last_update_reason", "World-held initial admission"); + fields.put("prepared_version_upgrade_id", null); + return fields; + } + + private static CanonicalInitialAdmissionOwnerProof committedProof() { + return new CanonicalInitialAdmissionOwnerProof( + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + "initial-admission-request", + "a".repeat(64), + "gameplay", + uuid(1), + "demo-world", + uuid(2), + uuid(3), + "SHARED", + uuid(4), + uuid(5), + 82L, + 41L, + OriginKind.NO_PRIOR_POINTER, + null, + uuid(6), + uuid(7), + "sha256:" + "b".repeat(64), + 73L, + 27L, + "sha256:" + "f".repeat(64), + false, + Instant.parse("2026-10-07T00:00:00Z")); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryTest.java new file mode 100644 index 0000000000..d7b02680e7 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepositoryTest.java @@ -0,0 +1,85 @@ +package unit.net.firedevops.firemud.gamesession.repository; + +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.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.InvalidIntakeEvidenceException; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionAuthoredWorldSourceRepositoryTest { + private static final String NAMESPACE = "authored-world-intake-unit"; + private static final UUID TENANT = uuid(1); + private static final UUID SOURCE_OPERATION = uuid(2); + private static final UUID SOURCE_REGISTRATION_REQUEST = uuid(3); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsPaddedOpenWorldDisplayNameBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + GameSessionAuthoredWorldSourceRepository repository = + new GameSessionAuthoredWorldSourceRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.register(uuid(4), source(" Violet Wilds "))) + .isInstanceOf(InvalidIntakeEvidenceException.class) + .hasMessageContaining("not canonical for an OPEN pointer"); + + verifyNoInteractions(dsl); + } + + private static AuthoredWorldSourceEvidence source(String worldDisplayName) { + String tenantSlug = "tenant-authored-world-unit"; + String worldSlug = "violet-wilds"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + SOURCE_REGISTRATION_REQUEST, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION_REQUEST, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName, + 821, + "gds-tenant-821", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION_REQUEST, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName, + 821, + "gds-tenant-821", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } +} From dee8317077ed1cb525c0e0ae1e974aa2761772e6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:25:29 +1300 Subject: [PATCH 17/22] Document malformed projection reconciliation exception boundary --- .../repository/CanonicalInitialAdmissionRepository.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java index 91db3f4cd5..d2e67d0b16 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java @@ -415,6 +415,11 @@ public CurrentOpenSnapshot readCurrentOpenSnapshotForRealm( return new CurrentOpenSnapshot(proof, snapshotDigestOrReconciliation(before, proof)); } + @SuppressFBWarnings( + value = "DCN_NULLPOINTER_EXCEPTION", + justification = + "Canonical projection validation rejects missing persisted fields with NullPointerException;" + + " this narrow readback boundary translates that rejection into required reconciliation.") private static String snapshotDigestOrReconciliation( CurrentOpenPointer pointer, CanonicalInitialAdmissionOwnerProof proof) { try { From 257f6d476d5e851aa8ad8b854bf29563581c9827 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 03:22:07 +1300 Subject: [PATCH 18/22] Fix owner client shutdown and strengthen original admission proof --- ...e-session-runtime-and-tick-coordination.md | 2 +- ...alStartSessionOwnerEvidenceReadClient.java | 8 +- ...WorldCanonicalInstanceLifecycleClient.java | 8 +- ...onicalInstanceLifecycleClientMtlsTest.java | 98 +++++++++++++++++++ ...artSessionOwnerEvidenceReadClientTest.java | 95 ++++++++++++++++++ .../CanonicalInitialAdmissionRepository.java | 13 ++- ...nonicalInitialAdmissionRepositoryTest.java | 61 ++++-------- ...tialAdmissionOwnerReadGrpcServiceTest.java | 28 ++++++ 8 files changed, 262 insertions(+), 51 deletions(-) diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 5933419f49..28dde7abcb 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -49,7 +49,7 @@ These links add decision provenance only; they do not upgrade any Game Session i | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation, and lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and opt-in fixture coordination are wired locally. Historical original-owner evidence reads are read-only. These preparations remain inactive and grant no player-admission authority; general `StartSession` retry integration is not claimed. | `proven` for front-door routing through the existing WebSocket, normalization, and gRPC tests. The owner-proof producer is covered by [CanonicalInitialAdmissionOwnerReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java). The historical original-owner producer and caller guard are exercised by [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java) and [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java). Durable owner behavior is covered by [DatabaseCanonicalInitialAdmissionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java) and [CanonicalInitialAdmissionRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java). Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service cases; all 2,327 passed with zero skips, failures, or errors. Cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [DatabaseCanonicalInitialAdmissionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java); [CanonicalInitialAdmissionIntentRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java); [CanonicalInitialAdmissionOwnerReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java); [CanonicalInitialAdmissionOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java); [canonical initial-admission owner-proof RPC](../../../protos/game-session/v1/game_session_service.proto); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java) | [CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [DatabaseCanonicalInitialAdmissionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java); [CanonicalInitialAdmissionRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); [CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java); [CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; ambiguous outcomes continue to fence World termination. The owner boundary is game-instance scoped and does not implement independently partitioned-region forwarding. | +| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation, and lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and opt-in fixture coordination are wired locally. Historical original-owner evidence reads are read-only. These preparations remain inactive and grant no player-admission authority; general `StartSession` retry integration is not claimed. | `proven` for front-door routing through [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java), [GameSessionWebSocketHandlerIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java), [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java), [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java), and [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java). The owner-proof producer is covered by [CanonicalInitialAdmissionOwnerReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java). The historical original-owner producer and caller guard are exercised by [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java) and [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java). Durable owner behavior is covered by [DatabaseCanonicalInitialAdmissionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java) and [CanonicalInitialAdmissionRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java). Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service cases; all 2,327 passed with zero skips, failures, or errors. Cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [DatabaseCanonicalInitialAdmissionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java); [CanonicalInitialAdmissionIntentRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java); [CanonicalInitialAdmissionOwnerReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java); [CanonicalInitialAdmissionOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java); [canonical initial-admission owner-proof RPC](../../../protos/game-session/v1/game_session_service.proto); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java) | [CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [DatabaseCanonicalInitialAdmissionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java); [CanonicalInitialAdmissionRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); [CanonicalInitialAdmissionIntentRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java); [CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; ambiguous outcomes continue to fence World termination. The owner boundary is game-instance scoped and does not implement independently partitioned-region forwarding. | | `GR-1.2` Tick timelines, action fairness, queues, and scheduling | `partial`: current bounded scheduler, per-entity queue selection, gameplay-command ordering (including timer/automation-origin work only after materialization as gameplay commands with retained provenance/order fields), durable batch/effect staging, pressure signals, and sealed selected-work manifests for gameplay commands are live; directly selected timer/retry/remote-follow-up source-claim manifests remain target-state; it still uses universal work-item selection and does not implement the accepted separate actor-action/passive-effect lane classification, phase budgets, or lane-preserving retry contract; the complete in-place command-status lifecycle accepted by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) is not | `drift-found`: the shipped scheduler and queue/effect seams have focused proof, but lane/source classification, separate lane budgets, and passive/inbound non-actor-turn behavior are not proved; the accepted command-status lifecycle in [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) remains unimplemented and is not fully proved | [ticks](../../architecture/system-architecture-ticks.md); [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | [TickScheduler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [TickServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game-session-service.proto](../../../protos/game-session/v1/game_session_service.proto) | [TickSchedulerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java) | `AS-1.4` timer progress and `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); `GR-1.3` ownership in this tracker | Add the [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) acknowledgement dimensions, authoritative attempt history, bound-tick summary, convergence contract, persistence, and focused proof to `GetGameplayCommandStatus`; separately add TICK-01 source classification, lane/cost metadata, phase budgets, lane-preserving retry identity, and focused actor/passive scheduling proof; adaptive timing and true region-wide scheduling remain separate gaps. | | `GR-1.3` Region leases, fencing, and executor coordination | `partial`: durable runtime ownership, epoch/fence snapshots, pause/resume, stale-owner rejection/requeue, and current runtime-progress publication are live at the game-instance boundary; the TICK-02 Redis lease plus durable executor-fence install/revalidate handshake and true region takeover boundary remain target-state | `proven`: current tests cover fence/scope admission, tick progress, stale execution, and operator reads, but do not prove the TICK-02 lease/fence handshake or takeover reconciliation | [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [RuntimeRegionStatus](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/RuntimeRegionStatus.java); [runtime ownership read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java); [TickRuntimeProgressService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java); [TickRuntimeProgressServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | `GR-1.1` front-end routing in this tracker; `AS-1.1` ingress and `AS-1.4` timers in [Automation runtime tracker](./automation-and-scheduler-runtime.md); Redis lease coordination is the shared infrastructure handoff | The current durable owner row and lease boundary are game-instance scoped. Add proof for Redis lease acquisition/loss before and after durable fence installation, same-token revalidation, stale-fence rejection, and takeover reconciliation; true region-partitioned leases, cluster scheduling, and front-end forwarding remain unimplemented. | | `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, remote result reconciliation, and bounded restart/reset paths are live; startup recovery re-enqueues old accepted-but-unstaged commands under their existing identity and leaves them `ACCEPTED` when Redis, identity, eligibility, or a raced transition prevents safe materialization; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `drift-found`: focused unit recovery tests cover accepted-row re-drive, unchanged retryable state on uncertainty, serializer-free identity/payload-idempotent queue/pending behavior, remote reconciliation, and retryability on Redis/eligibility races, but do not provide combined PostgreSQL/real-Redis restart proof, lane/cost preservation, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake; the real-Redis serializer integration test is present but skipped when Docker is unavailable | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java index 1a5404d5d2..3b18cd404f 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java @@ -112,9 +112,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/world/WorldCanonicalInstanceLifecycleClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java index 600429372a..630a9116bc 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java @@ -101,9 +101,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/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java index 682315cc0f..45a7c564d2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java @@ -2,8 +2,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; import io.grpc.Metadata; import io.grpc.Server; import io.grpc.ServerCall; @@ -18,6 +22,7 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -30,14 +35,19 @@ import java.util.Base64; import java.util.List; import java.util.UUID; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +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.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import net.firedevops.firemud.common.world.RoomTemplateRef; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; @@ -195,6 +205,74 @@ void refusesPlaintextClasspathFilesAndCallsBeforeExplicitInitialization() throws assertThat(applicationCalls).hasValue(0); } + @Test + void closeReleasesClientMonitorBeforeClosingCertificateWatcher() throws Exception { + String previousReloadPolicy = System.getProperty("firemud.grpc.tls-reload.enabled"); + System.setProperty("firemud.grpc.tls-reload.enabled", "false"); + try { + CountingChannelFactory channelFactory = new CountingChannelFactory(); + client = + new WorldCanonicalInstanceLifecycleClient( + new ServiceEndpointsProperties(), + pki.clientProperties(tempDirectory), + channelFactory, + NAMESPACE); + client.init(); + + TlsCertificateWatcher watcher = mock(TlsCertificateWatcher.class); + CountDownLatch callbackFinished = new CountDownLatch(1); + AtomicBoolean callbackAcquiredMonitor = new AtomicBoolean(); + AtomicReference callbackFailure = new AtomicReference<>(); + doAnswer( + invocation -> { + assertThat(Thread.holdsLock(client)).isFalse(); + Thread callback = + new Thread( + () -> { + try { + synchronized (client) { + callbackAcquiredMonitor.set(true); + } + } catch (Throwable failure) { + callbackFailure.set(failure); + } finally { + callbackFinished.countDown(); + } + }, + "world-canonical-lifecycle-client-test-callback"); + callback.start(); + if (!callbackFinished.await(1, TimeUnit.SECONDS)) { + callback.interrupt(); + callback.join(TimeUnit.SECONDS.toMillis(1)); + throw new AssertionError("Watcher callback could not acquire the client monitor"); + } + callback.join(TimeUnit.SECONDS.toMillis(1)); + assertThat(callback.isAlive()).isFalse(); + assertThat(callbackAcquiredMonitor.get()).isTrue(); + assertThat(callbackFailure.get()).isNull(); + return null; + }) + .when(watcher) + .close(); + setWatcher(client, watcher); + + client.close(); + + verify(watcher).close(); + assertThat(channelFactory.buildAttempts.get()).isEqualTo(1); + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessage("World canonical lifecycle client is closed"); + assertThat(channelFactory.buildAttempts.get()).isEqualTo(1); + } finally { + if (previousReloadPolicy == null) { + System.clearProperty("firemud.grpc.tls-reload.enabled"); + } else { + System.setProperty("firemud.grpc.tls-reload.enabled", previousReloadPolicy); + } + } + } + private void startServer( TestIdentity identity, ResponseMode responseMode, @@ -352,6 +430,26 @@ private static UUID uuid(String value) { return UUID.fromString(value); } + private static void setWatcher( + WorldCanonicalInstanceLifecycleClient client, TlsCertificateWatcher watcher) + throws ReflectiveOperationException { + Field watcherField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); + watcherField.setAccessible(true); + watcherField.set(client, watcher); + } + + private static final class CountingChannelFactory extends GrpcChannelFactory { + private final AtomicInteger buildAttempts = new AtomicInteger(); + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + buildAttempts.incrementAndGet(); + return mock(ManagedChannel.class); + } + } + private enum ResponseMode { EXACT, WRONG_READ_REQUEST_ID, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java index 59ecb44f01..e8990603c4 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.common.gamesession; +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.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -10,13 +12,22 @@ import io.grpc.ManagedChannel; import java.io.IOException; +import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Request; +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 org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -88,6 +99,70 @@ void initializesOnlyTheConfiguredGameSessionTargetWithFileBackedMtls(@TempDir Pa eq(true)); } + @Test + void closeReleasesClientMonitorBeforeClosingCertificateWatcher(@TempDir Path dir) + throws Exception { + String previousReloadPolicy = System.getProperty("firemud.grpc.tls-reload.enabled"); + System.setProperty("firemud.grpc.tls-reload.enabled", "false"); + try { + CountingChannelFactory channelFactory = new CountingChannelFactory(); + client = newClient(fileBackedMtls(dir), channelFactory); + client.init(); + + TlsCertificateWatcher watcher = mock(TlsCertificateWatcher.class); + CountDownLatch callbackFinished = new CountDownLatch(1); + AtomicBoolean callbackAcquiredMonitor = new AtomicBoolean(); + AtomicReference callbackFailure = new AtomicReference<>(); + doAnswer( + invocation -> { + assertThat(Thread.holdsLock(client)).isFalse(); + Thread callback = + new Thread( + () -> { + try { + synchronized (client) { + callbackAcquiredMonitor.set(true); + } + } catch (Throwable failure) { + callbackFailure.set(failure); + } finally { + callbackFinished.countDown(); + } + }, + "historical-original-owner-read-test-callback"); + callback.start(); + if (!callbackFinished.await(1, TimeUnit.SECONDS)) { + callback.interrupt(); + callback.join(TimeUnit.SECONDS.toMillis(1)); + throw new AssertionError("Watcher callback could not acquire the client monitor"); + } + callback.join(TimeUnit.SECONDS.toMillis(1)); + assertThat(callback.isAlive()).isFalse(); + assertThat(callbackAcquiredMonitor.get()).isTrue(); + assertThat(callbackFailure.get()).isNull(); + return null; + }) + .when(watcher) + .close(); + setWatcher(client, watcher); + + client.close(); + + verify(watcher).close(); + assertThat(channelFactory.buildAttempts.get()).isEqualTo(1); + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Historical StartSession evidence client is closed"); + assertThat(channelFactory.buildAttempts.get()).isEqualTo(1); + } finally { + if (previousReloadPolicy == null) { + System.clearProperty("firemud.grpc.tls-reload.enabled"); + } else { + System.setProperty("firemud.grpc.tls-reload.enabled", previousReloadPolicy); + } + } + } + private HistoricalOriginalStartSessionOwnerEvidenceReadClient newClient( CommonGrpcClientProperties tls, GrpcChannelFactory factory) { return new HistoricalOriginalStartSessionOwnerEvidenceReadClient( @@ -119,4 +194,24 @@ private static Request request(String namespace) { UUID.fromString("44444444-4444-4444-8444-444444444444"), 9L); } + + private static void setWatcher( + HistoricalOriginalStartSessionOwnerEvidenceReadClient client, TlsCertificateWatcher watcher) + throws ReflectiveOperationException { + Field watcherField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); + watcherField.setAccessible(true); + watcherField.set(client, watcher); + } + + private static final class CountingChannelFactory extends GrpcChannelFactory { + private final AtomicInteger buildAttempts = new AtomicInteger(); + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + buildAttempts.incrementAndGet(); + return mock(ManagedChannel.class); + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java index d2e67d0b16..7f5b8bed88 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java @@ -415,12 +415,13 @@ public CurrentOpenSnapshot readCurrentOpenSnapshotForRealm( return new CurrentOpenSnapshot(proof, snapshotDigestOrReconciliation(before, proof)); } + /** Package-private same-package test seam for malformed persisted projection evidence. */ @SuppressFBWarnings( value = "DCN_NULLPOINTER_EXCEPTION", justification = "Canonical projection validation rejects missing persisted fields with NullPointerException;" + " this narrow readback boundary translates that rejection into required reconciliation.") - private static String snapshotDigestOrReconciliation( + static String snapshotDigestOrReconciliation( CurrentOpenPointer pointer, CanonicalInitialAdmissionOwnerProof proof) { try { return pointer.snapshotDigest(proof); @@ -1289,9 +1290,13 @@ private static void requireText(String value, String label, int maxLength) { } } - /** Full persisted pointer-row identity used to detect any before/after read drift. */ - private record CurrentOpenPointer(Map fields) { - private CurrentOpenPointer { + /** + * Full persisted pointer-row identity used to detect any before/after read drift. + * + *

Package-private test seam keeps projection validation directly testable without reflection. + */ + record CurrentOpenPointer(Map fields) { + CurrentOpenPointer { fields = Collections.unmodifiableMap(new LinkedHashMap<>(fields)); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java index 58bf67985d..a5f3d585fd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java @@ -3,9 +3,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.time.Instant; import java.util.HashMap; import java.util.Map; @@ -41,64 +38,48 @@ void pointerAndAuditVersionComparisonRejectsNullMismatch() { @Test void malformedPersistedOpenProjectionRequiresReconciliationAtSnapshotBoundary() { CanonicalInitialAdmissionOwnerProof proof = committedProof(); - Object validPointer = currentOpenPointer(validOpenFields()); + CanonicalInitialAdmissionRepository.CurrentOpenPointer validPointer = + new CanonicalInitialAdmissionRepository.CurrentOpenPointer(validOpenFields()); - assertThat(snapshotDigest(validPointer, proof)).matches("[0-9a-f]{64}"); + assertThat( + CanonicalInitialAdmissionRepository.snapshotDigestOrReconciliation(validPointer, proof)) + .matches("[0-9a-f]{64}"); Map paddedName = validOpenFields(); paddedName.put("world_display_name", " Demo World "); assertMalformedProjection( - currentOpenPointer(paddedName), proof, IllegalArgumentException.class); + new CanonicalInitialAdmissionRepository.CurrentOpenPointer(paddedName), + proof, + IllegalArgumentException.class); Map invalidOrigin = validOpenFields(); invalidOrigin.put("initial_admission_origin_kind", "UNKNOWN_ORIGIN"); assertMalformedProjection( - currentOpenPointer(invalidOrigin), proof, IllegalArgumentException.class); + new CanonicalInitialAdmissionRepository.CurrentOpenPointer(invalidOrigin), + proof, + IllegalArgumentException.class); Map nullOrigin = validOpenFields(); nullOrigin.put("initial_admission_origin_kind", null); - assertMalformedProjection(currentOpenPointer(nullOrigin), proof, NullPointerException.class); + assertMalformedProjection( + new CanonicalInitialAdmissionRepository.CurrentOpenPointer(nullOrigin), + proof, + NullPointerException.class); } private static void assertMalformedProjection( - Object pointer, CanonicalInitialAdmissionOwnerProof proof, Class cause) { - assertThatThrownBy(() -> snapshotDigest(pointer, proof)) + CanonicalInitialAdmissionRepository.CurrentOpenPointer pointer, + CanonicalInitialAdmissionOwnerProof proof, + Class cause) { + assertThatThrownBy( + () -> + CanonicalInitialAdmissionRepository.snapshotDigestOrReconciliation(pointer, proof)) .isInstanceOf( CanonicalInitialAdmissionRepository .CanonicalInitialAdmissionReconciliationRequiredException.class) .hasCauseInstanceOf(cause); } - private static String snapshotDigest(Object pointer, CanonicalInitialAdmissionOwnerProof proof) { - try { - Method method = - CanonicalInitialAdmissionRepository.class.getDeclaredMethod( - "snapshotDigestOrReconciliation", pointer.getClass(), proof.getClass()); - method.setAccessible(true); - return (String) method.invoke(null, pointer, proof); - } catch (InvocationTargetException invocation) { - if (invocation.getCause() instanceof RuntimeException cause) { - throw cause; - } - throw new AssertionError(invocation.getCause()); - } catch (ReflectiveOperationException reflectionFailure) { - throw new AssertionError(reflectionFailure); - } - } - - private static Object currentOpenPointer(Map fields) { - try { - Class pointerType = - Class.forName( - CanonicalInitialAdmissionRepository.class.getName() + "$CurrentOpenPointer"); - Constructor constructor = pointerType.getDeclaredConstructor(Map.class); - constructor.setAccessible(true); - return constructor.newInstance(fields); - } catch (ReflectiveOperationException reflectionFailure) { - throw new AssertionError(reflectionFailure); - } - } - private static Map validOpenFields() { Map fields = new HashMap<>(); fields.put("representation_version", 3); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java index fa430b7a96..5f6bfbfa35 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -19,8 +20,10 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamesession.CanonicalInitialAdmissionOwnerGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; @@ -151,6 +154,31 @@ void committedReadbackFailsClosedWhenPriorPointerVersionCannotAdvance() { assertEquals(Status.Code.FAILED_PRECONDITION, result.status().getCode()); } + @Test + void codecRejectsOverflowingPriorPointerWithTheExplicitOverflowCause() { + HoldIdentity exactHold = identity(InitialAdmissionOrigin.EXPECT_CLOSED, Long.MAX_VALUE); + CanonicalInitialAdmissionOwnerProof existingProof = + ownerProof(exactHold, "COMMITTED", TENANT, 1L); + GameSessionCanonicalInitialAdmissionOwnerProof proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + exactHold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + existingProof.committedPointerVersion(), + existingProof.auditEventId(), + existingProof.proofDigest(), + existingProof.positiveDurableAbort(), + existingProof.terminalAt()); + + IllegalArgumentException failure = + assertThrows( + IllegalArgumentException.class, + () -> CanonicalInitialAdmissionOwnerGrpcCodec.toResponse(exactHold, proof)); + + assertEquals( + "Expected prior pointer version cannot advance without overflow", failure.getMessage()); + assertTrue(failure.getCause() instanceof ArithmeticException); + } + @Test void committedOwnerReadbackMapsExactPointerAuditAndTerminalProof() { CanonicalInitialAdmissionRepository repository = From b51f562e29303088ee323de6e1f9aec678b0b597 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 03:58:26 +1300 Subject: [PATCH 19/22] Consolidate original-claim physical proof record --- .../player-access-and-session.md | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 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 7b1082af5c..4dadf43ffb 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,19 +14,21 @@ This inactive owner continuation may read or replay the exact immutable associat Previously recorded focused local unit and transport evidence includes the [authorization coordinator test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java), [continuation service test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java), [redemption client test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java), and [mTLS redemption client test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java). The implementation anchors are [authorization coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java), [owner attempt repository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java), [template association repository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepository.java), and [descriptor continuation service](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java), with schema support in [V35](../../../services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql), [V37](../../../services/game-session-service/src/main/resources/db/migration/V37__start_session_template_association_pin.sql), and [V38](../../../services/game-session-service/src/main/resources/db/migration/V38__start_session_launch_descriptor_pin.sql). -Historical earlier-head [Validation run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` executed 68 selected PostgreSQL cases with zero skips; that result applies only to its selected fixtures and source head. The latest exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases. All 2,327 passed with zero skips, failures, or errors. Its JUnit artifacts include the owner-attempt (12), template-association (10), launch-descriptor (12), original-association read (8), authorization-coordinator (3), and V34.3 request-ID migration (1) suites. This is aggregate current-head physical proof; it does not assert one-to-one matching of the 21 failures from the earlier failed job. +#### Consolidated exact-head and historical proof -The restricted original-claim continuation remains inactive and default-denied: its owner repositories, typed Account read/pin clients, and descriptor evidence producer remain unregistered, do not alter the composed production implementation, and authorize neither mutation nor player admission. The latest exact-head run above physically executed the current owner/history integration suites; it does not prove runtime registration, World-backed admission, historical-owner reconciliation, or playable closure. The earlier local check that compiled integration sources without running PostgreSQL is historical local-environment evidence, superseded for the listed fixture suites by the hosted result. +Historical earlier-head [Validation run 38041747105](https://github.com/benhook1013/FireMUD/actions/runs/38041747105) on `6785bcc2d95735117c6191fe367bcad46f769b4c` executed 68 selected PostgreSQL cases with zero skips; that result applies only to its selected fixtures and source head. Historical Game Session job `114071452179` on `c79103014c1b991f4caaa3f1fef04652ec1adda8` failed 21 of 218 integration cases: 20 shared-fixture timestamp violations and one source-bound tenant guard rejection. Later exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases; all 2,327 passed with zero skips, failures, or errors. Its JUnit artifacts include the owner-attempt (12), template-association (10), launch-descriptor (12), original-association read (8), authorization-coordinator (3), and V34.3 request-ID migration (1) suites, plus the historical owner producer and workload-guard unit suites (6 and 4). This is aggregate physical proof for the recorded source head and listed fixtures; the artifact does not map the earlier job's failures one by one, and it does not prove current code at a later source head, runtime registration, World-backed admission, namespace-aware atomic takeover, issuer-index or region reconciliation, retained-binding inventory/conversion, final Account admission, live playable closure, or the complete migration-driver PostgreSQL/Redis path. The V34.3 fixture result does not establish that complete driver path. -The inactive hold client reads the exact immutable identity, actual hold status, and full lifecycle snapshot over workload mTLS. The original STARTING association read carries the stored post-authorization tuple and actual owner attempt/fence, but requires an unexpired pending claim; it is not an after-expiry association endpoint. Historical Game Session job `114071452179` on `c79103014c1b991f4caaa3f1fef04652ec1adda8` failed 21 of 218 integration cases (20 shared-fixture timestamp violations and one source-bound tenant guard rejection). The later exact-head run 38049505627 completed 234 integration cases with no failures or skips, but the artifact evidence here does not map each earlier failed case one by one. Hold snapshots and retained tuples do not supply continuous commit authority. The authenticated historical original-owner evidence producer remains unregistered and undeployed; live hold validation, continuous protection through pointer/audit commit, and cross-owner terminal reconciliation remain incomplete. +The restricted original-claim continuation remains inactive and default-denied: its owner repositories, typed Account read/pin clients, and descriptor evidence producer remain unregistered, do not alter the composed production implementation, and authorize neither mutation nor player admission. The exact-head run recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof) physically executed the listed owner/history integration suites; it does not prove runtime registration, World-backed admission, historical-owner reconciliation, or playable closure. The earlier local check that compiled integration sources without running PostgreSQL is historical local-environment evidence, superseded for the listed fixture suites by that hosted result. -Game Session has an unregistered original-claim evidence-continuation preparation: owner repositories, typed read/pin carriers, before-and-after authenticated Account projection reads outside SQL, and database-clock claim/reference-expiry checks at descriptor pinning. Earlier Docker-disabled local snapshots compiled the PostgreSQL fixtures but did not execute them locally; the latest exact-head Validation artifact now records successful physical execution of the owner-attempt, association, descriptor, and coordinator integration suites. Genuine Account original-redeemed receiver revalidation and full pointer/audit/live-owner composition remain required; mocked responses do not prove that receiver. This preparation grants no new mutation authorization or admission and does not establish playable closure. The bounded contract is owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). +The inactive hold client reads the exact immutable identity, actual hold status, and full lifecycle snapshot over workload mTLS. The original STARTING association read carries the stored post-authorization tuple and actual owner attempt/fence, but requires an unexpired pending claim; it is not an after-expiry association endpoint. Historical failure provenance and the later artifact's limitation in matching those failures are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). Hold snapshots and retained tuples do not supply continuous commit authority. The authenticated historical original-owner evidence producer remains unregistered and undeployed; live hold validation, continuous protection through pointer/audit commit, and cross-owner terminal reconciliation remain incomplete. -The same inactive preparation includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event, and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These repositories, coordinator, and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Earlier local checks that reused cached task outputs and lacked Docker are historical local-only results; they do not supersede the latest exact-head physical test evidence and do not establish activation. World Management's published change `2cb445617` supplies the canonical World hold request and immutable identity, including both origin selectors and the request-binding digest; the older numeric hold RPC is not that interface. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup, and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. +Game Session has an unregistered original-claim evidence-continuation preparation: owner repositories, typed read/pin carriers, before-and-after authenticated Account projection reads outside SQL, and database-clock claim/reference-expiry checks at descriptor pinning. Earlier Docker-disabled local snapshots compiled the PostgreSQL fixtures but did not execute them locally; the listed physical fixture execution is recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). Genuine Account original-redeemed receiver revalidation and full pointer/audit/live-owner composition remain required; mocked responses do not prove that receiver. This preparation grants no new mutation authorization or admission and does not establish playable closure. The bounded contract is owned by [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation). -The newer inactive consumer adds exact mTLS World acquisition/identity and lifecycle read clients, the V28-backed durable pre-hold intent repository, and a coordinator that commits immutable intent before contacting World and attaches only the exact returned hold identity in a separate owner transaction. Remote failure preserves pending intent for the same request; attached or terminal replay returns historical evidence only. Owner repositories also expose non-mutating historical reads of the complete original StartSession tuple, actual attempt/fence, attached Account projection, and immutable first template pin after expiry, separately from the still-unexpired live continuation. The latest exact-head artifact confirms its listed PostgreSQL suites executed successfully; it does not prove the consumer is registered, that a genuine World verifier participates at runtime, or that hold authority remains continuous through pointer/audit commit. Cross-owner terminal reconciliation, concurrent termination/restart proof, and playable closure remain open. +The same inactive preparation includes canonical launch preparation, exact original CLOSED-pointer evidence, a one-shot Account redemption coordinator/client, and a separate initial-admission owner operation that binds the supplied World hold to the pointer, append-only audit event, and terminal owner readback in one writable SQL transaction. The original-claim continuation remains read/pin-only and does not authorize that operation. These repositories, coordinator, and owner service are not registered, and no genuine World verifier or positive runtime wiring is supplied. Earlier local checks that reused cached task outputs and lacked Docker are historical local-only results; they do not supersede the limited exact-head evidence recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof) or establish activation. World Management's published change `2cb445617` supplies the canonical World hold request and immutable identity, including both origin selectors and the request-binding digest; the older numeric hold RPC is not that interface. Authentic Account/World participation, concurrent termination/restart proof, composed fresh-image startup, and `LOGIN → PLAY → LOOK` remain required before activation or playable closure. -The latest exact-head Validation artifact records the descriptor, association, owner-attempt, and authorization-coordinator integration suites as passing (12, 10, 12, and 3 cases respectively), along with the historical original-association read suite (8 cases). It also records the historical owner producer and workload-guard unit suites as passing (6 and 4 cases). This aggregate run is not a one-to-one audit of the 21 failures in job 114071452179; the `AA-2.1` capability remains partial because namespace-aware atomic takeover, final Account admission, runtime activation, and live playable proof are still open. +The newer inactive consumer adds exact mTLS World acquisition/identity and lifecycle read clients, the V28-backed durable pre-hold intent repository, and a coordinator that commits immutable intent before contacting World and attaches only the exact returned hold identity in a separate owner transaction. Remote failure preserves pending intent for the same request; attached or terminal replay returns historical evidence only. Owner repositories also expose non-mutating historical reads of the complete original StartSession tuple, actual attempt/fence, attached Account projection, and immutable first template pin after expiry, separately from the still-unexpired live continuation. The listed PostgreSQL suite results are in the [consolidated proof record](#consolidated-exact-head-and-historical-proof); they do not prove the consumer is registered, that a genuine World verifier participates at runtime, or that hold authority remains continuous through pointer/audit commit. Cross-owner terminal reconciliation, concurrent termination/restart proof, and playable closure remain open. + +The exact-head artifact and the historical owner/history suite results are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof), including the limitation that the aggregate artifact does not map the earlier job's failures one by one. The `AA-2.1` capability remains partial because namespace-aware atomic takeover, final Account admission, runtime activation, and live playable proof are still open. The current Account source/currentness cut preserves V1–V40, V40.1, V53, and V73 unchanged and adds V74–V89 for source/global-role guards, draft-source writer exclusion and fences, immutable reset/logout/security-operation receipts, creator and tenant-bootstrap provenance, individual Creator Party and hosted-terms/environment-binding persistence, and source-change journals. V90–V97 add persistence relations and guards across Account, control-UI issuance, selected-publication authorization/settlement, and Game Logic. V98 adds Account-owned persistence for exact hosted-terms disclosure handoffs and immutable captured source evidence, with database guards on binding immutability, result transitions, and source insertion phase. This schema does not activate a writer, legal authority verifier, dispatch RPC, or consumer. Fresh repository-created Accounts retain their V40 source baselines; retained pre-V40 Accounts are not backfilled or admitted. Password reset now atomically consumes the token, updates the Account, appends its canonical event/receipt, and reads back current source evidence, with an unresolved original source intent fencing mutation until the owner outcome is known. A distinct overlapping source change maps to retryable `AUTH_UNAVAILABLE` before a second reset intent is stored; unrelated persistence failures propagate and roll back. Each affected operation is settled against its own exact owner readbacks; mixed owner outcomes within an operation remain pending, while distinct operations may have different terminal outcomes. Historical and current bounded proof, failures, and pending physical validation are recorded below. Strict codecs and passive projections add no signer/issuer or StartSession activation. Logout-all production remains unregistered and unwired; the fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Hosted-terms acceptance, authenticated publication, and registry/runtime binding remain unregistered. Tenant creator bootstrap is default-denied without a separately registered genuine authorization/source participant; no public or new route is added. These source-only primitives provide no authenticated public JOIN, cross-service target-through-commit gate, Game Session text JOIN, or playable closure. Existing #2898/#2848 and Entity/World gaps and capability statuses remain unchanged; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). @@ -64,7 +66,7 @@ Deployment must not advertise retained credential/security-write workflows as re - `AA-2.1` / `AA-2.2` / `AA-3.3`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) remains the canonical target link for stable namespace-aware selection, admission, reconnect, and runtime replacement; [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) owns namespace-scoped controller identity, uniqueness, takeover, and binding-generation fencing. Existing account/session and realm-routing evidence remains partial and does not prove namespace-aware atomic takeover, replacement, or cleanup behavior. - `AA-3.3`: [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) adds the player-visible lifecycle consequence that only an active, admissible realm is exposed; Temporal coordination does not become admission authority. Existing lifecycle and reconnect caveats remain. -- The finite namespace controller-index migration-driver prefix is source and packaging preparation only. The most recent independent Common Security and Game Session full checks completed without failures or errors; those checks do not prove the newly adjudicated fixes or complete physical PostgreSQL/Redis execution. Distribution packaging, exact source-to-jar migration resource comparison, synthetic missing/changed/duplicate resource rejection, ShellCheck, and documentation checks pass. The [V34.3 intent request-ID PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) passed in exact-head Validation run 38049505627 as recorded above; that single fixture does not establish the complete migration-driver PostgreSQL/Redis path. Complete driver execution, final image build and immutable image authority, trusted bootstrap/execution, and live playable proof remain unrun; Docker-disabled local checks do not establish PostgreSQL fixture behavior. Issuer-index and region reconciliation and final Account admission have no proof in this slice. This status does not establish an empty retained-binding inventory, prove conversion of non-empty retained data, or authorize running the driver. `AA-2.1` and `AA-2.2` remain `partial` / `drift-found`; gameplay completion under #2967/#2898 remains separate. See [Game Session Operations](../../architecture/microservices/game-session-service/operations.md#namespace-controller-index-migration-driver) and the canonical [Legacy controller-index migration gate](../../architecture/system-architecture-session-behavior.md#legacy-controller-index-migration-gate). +- The finite namespace controller-index migration-driver prefix is source and packaging preparation only. The most recent independent Common Security and Game Session full checks completed without failures or errors; those checks do not prove the newly adjudicated fixes or complete physical PostgreSQL/Redis execution. Distribution packaging, exact source-to-jar migration resource comparison, synthetic missing/changed/duplicate resource rejection, ShellCheck, and documentation checks pass. The [V34.3 intent request-ID PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) passed in the exact-head run summarized in the [consolidated proof record](#consolidated-exact-head-and-historical-proof); that fixture does not establish the complete migration-driver PostgreSQL/Redis path. Complete driver execution, final image build and immutable image authority, trusted bootstrap/execution, and live playable proof remain unrun; Docker-disabled local checks do not establish PostgreSQL fixture behavior. Issuer-index and region reconciliation and final Account admission have no proof in this slice. This status does not establish an empty retained-binding inventory, prove conversion of non-empty retained data, or authorize running the driver. `AA-2.1` and `AA-2.2` remain `partial` / `drift-found`; gameplay completion under #2967/#2898 remains separate. See [Game Session Operations](../../architecture/microservices/game-session-service/operations.md#namespace-controller-index-migration-driver) and the canonical [Legacy controller-index migration gate](../../architecture/system-architecture-session-behavior.md#legacy-controller-index-migration-gate). These links add decision provenance only; they do not upgrade player-access or session capability status. @@ -77,7 +79,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) executed 2,054 unit, 234 integration, and 39 cross-service Game Session cases with zero skips or failures; the V34.3 PostgreSQL fixture ran one case successfully. This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | From 33ee8692c0ec1f3814cea2f228739af4fbf575cc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 04:34:00 +1300 Subject: [PATCH 20/22] test: compare canonical initial admission digests directly --- .../CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java index 5f6bfbfa35..03ded86d4e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java @@ -374,8 +374,7 @@ private static void assertCompleteTuple( assertEquals(REQUEST_ID, response.getInitialAdmissionRequestId()); assertEquals( request.initialAdmissionRequestDigest(), response.getInitialAdmissionRequestDigest()); - assertNotEquals( - "sha256:" + request.initialAdmissionRequestDigest(), identity.holdBindingDigest()); + assertNotEquals(request.initialAdmissionRequestDigest(), identity.holdBindingDigest()); assertEquals(TENANT.toString(), response.getCanonicalTenantId()); assertEquals("demo-world", response.getWorldSlug()); assertEquals(REALM.toString(), response.getRealmId()); From 929d8690e6f5ba92a03b132781071fa6434792c1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:16:47 +1300 Subject: [PATCH 21/22] test: prove replay after unexpected first-party disconnect --- ...essionWebSocketHandlerIntegrationTest.java | 36 ++++++++++--------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 4328a578f1..060a1b0b01 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -1082,7 +1082,8 @@ && containsKind(json(payload), "PROMPT"), } @Test - void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Exception { + void websocketFirstPartyUnexpectedDisconnectRetainsReplayStateForFreshReconnect() + throws Exception { when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) .thenReturn( Optional.of( @@ -1093,35 +1094,37 @@ void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Excep 1, 44L))); - GameplayWebSocketDriver.CloseEvent firstCloseEvent; - try (GameplayWebSocketDriver client = - openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "logout-1"))) { - client.send("LOGIN"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("PLAY demo Emberline"); - client.awaitMatching( - payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - client.send("LOGOUT"); - firstCloseEvent = client.awaitClosed(); - } + GameplayWebSocketDriver firstClient = + openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "disconnect-1")); + firstClient.send("LOGIN"); + firstClient.awaitMatching( + payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); + firstClient.send("PLAY demo Emberline"); + firstClient.awaitMatching( + payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); + firstClient.abort(); - assertThat(firstCloseEvent.reason()).isEqualTo("logout"); - verify(screenBufferService, never()).clear(22L, 1L, 123L); GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); + assertThat(sessionContextService.findByTenantAndSessionId(22L, 1L)).isPresent(); assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of("123"))) .containsKey("123"); java.util.List secondPayloads; try (GameplayWebSocketDriver client = - openFirstPartyDriver("2", firstPartyClaims("demo", "production", "1", "1", "logout-2"))) { + openFirstPartyDriver( + "2", firstPartyClaims("demo", "production", "1", "1", "disconnect-2"))) { client.send("LOGIN"); client.awaitMatching( payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); client.send("PLAY demo Emberline"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); + client.awaitMatching( + payload -> + "transcript_chunk".equals(json(payload).path("eventType").asText()) + && payload.contains("First-party replay"), + "replayed first-party transcript chunk"); secondPayloads = client.responses(); } @@ -1132,6 +1135,7 @@ void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Excep payload -> "transcript_chunk".equals(json(payload).path("eventType").asText()) && payload.contains("First-party replay")); + verify(screenBufferService, never()).clear(22L, 1L, 123L); } @Test From c71731cb3da9dc6002b39cba70e09d0ff71d9f95 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:48:55 +1300 Subject: [PATCH 22/22] test: expose controller publisher contract failure diagnostics --- ...d-identity-controller-workflow-contract.sh | 89 +++++++++++++++++-- 1 file changed, 80 insertions(+), 9 deletions(-) diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index f179f534a2..c8467b09e1 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -3606,6 +3606,50 @@ if grep -Fq "sha256:$(printf '1%.0s' {1..64})" "$controller_publish_output"; the exit 1 fi +assert_controller_publish_log_contains() { + local assertion="$1" + local expected="$2" + local log_path="$3" + local observed='' + if [[ -f "$log_path" ]]; then + observed="$(<"$log_path")" + fi + if ! grep -Fq -- "$expected" "$log_path" 2>/dev/null; then + printf 'controller publisher %s assertion failed: expected=%q observed=%q file=%s\n' \ + "$assertion" "$expected" "$observed" "$log_path" >&2 + exit 1 + fi +} + +assert_controller_publish_exact_line() { + local assertion="$1" + local expected="$2" + local log_path="$3" + local observed='' + if [[ -f "$log_path" ]]; then + observed="$(<"$log_path")" + fi + if ! grep -Fxq -- "$expected" "$log_path" 2>/dev/null; then + printf 'controller publisher %s assertion failed: expected exact line=%q observed=%q file=%s\n' \ + "$assertion" "$expected" "$observed" "$log_path" >&2 + exit 1 + fi +} + +assert_controller_publish_empty_output() { + local assertion="$1" + local output_path="$2" + local observed='' + if [[ -f "$output_path" ]]; then + observed="$(<"$output_path")" + fi + if [[ -s "$output_path" ]]; then + printf 'controller publisher %s assertion failed: expected empty output observed=%q file=%s\n' \ + "$assertion" "$observed" "$output_path" >&2 + exit 1 + fi +} + controller_duplicate_count="$TEMP_DIR/controller-duplicate-count" controller_duplicate_output="$TEMP_DIR/controller-duplicate.output" if ( @@ -3624,9 +3668,13 @@ if ( echo "controller publication accepted more than one successful push digest" >&2 exit 1 fi -grep -Fq 'did not report exactly one exact sha256 digest' \ +assert_controller_publish_log_contains \ + 'duplicate-digest rejection' \ + 'did not report exactly one exact sha256 digest' \ "$TEMP_DIR/controller-duplicate.stderr" -test ! -s "$controller_duplicate_output" +assert_controller_publish_empty_output \ + 'duplicate-digest rejection' \ + "$controller_duplicate_output" controller_zero_count="$TEMP_DIR/controller-zero-count" controller_zero_output="$TEMP_DIR/controller-zero.output" @@ -3646,9 +3694,13 @@ if ( echo "controller publication accepted a successful push without a digest" >&2 exit 1 fi -grep -Fq 'did not report exactly one exact sha256 digest' \ +assert_controller_publish_log_contains \ + 'zero-digest rejection' \ + 'did not report exactly one exact sha256 digest' \ "$TEMP_DIR/controller-zero.stderr" -test ! -s "$controller_zero_output" +assert_controller_publish_empty_output \ + 'zero-digest rejection' \ + "$controller_zero_output" controller_failure_count="$TEMP_DIR/controller-failure-count" controller_failure_output="$TEMP_DIR/controller-failure.output" @@ -3668,11 +3720,30 @@ if ( echo "controller publication accepted three failed push attempts" >&2 exit 1 fi -test "$(<"$controller_failure_count")" -eq 3 -grep -Fxq '5' "$TEMP_DIR/controller-failure-sleep.log" -grep -Fxq '10' "$TEMP_DIR/controller-failure-sleep.log" -grep -Fq 'after 3 attempts' "$TEMP_DIR/controller-failure.stderr" -test ! -s "$controller_failure_output" +controller_failure_count_observed='' +if [[ -f "$controller_failure_count" ]]; then + controller_failure_count_observed="$(<"$controller_failure_count")" +fi +if [[ "$controller_failure_count_observed" != 3 ]]; then + printf 'controller publisher exhausted-retry attempt-count assertion failed: expected=3 observed=%q file=%s\n' \ + "$controller_failure_count_observed" "$controller_failure_count" >&2 + exit 1 +fi +assert_controller_publish_exact_line \ + 'exhausted-retry first backoff' \ + '5' \ + "$TEMP_DIR/controller-failure-sleep.log" +assert_controller_publish_exact_line \ + 'exhausted-retry second backoff' \ + '10' \ + "$TEMP_DIR/controller-failure-sleep.log" +assert_controller_publish_log_contains \ + 'exhausted-retry terminal failure' \ + 'after 3 attempts' \ + "$TEMP_DIR/controller-failure.stderr" +assert_controller_publish_empty_output \ + 'exhausted-retry failure' \ + "$controller_failure_output" preview_derive_step="$TEMP_DIR/preview-derive-step.sh" python3 - "$preview" "$preview_derive_step" <<'PY'